forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmulti.jl
1625 lines (1463 loc) · 44 KB
/
multi.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## multi.jl - multiprocessing
##
## julia starts with one process, and processors can be added using:
## addprocs_local(n) using exec
## addprocs_ssh({"host1","host2",...}) using remote execution
## addprocs_sge(n) using Sun Grid Engine batch queue
##
## remote_call(w, func, args...) -
## tell a worker to call a function on the given arguments.
## returns a RemoteRef to the result.
##
## remote_do(w, f, args...) - remote function call with no result
##
## wait(rr) - wait for a RemoteRef to be finished computing
##
## fetch(rr) - wait for and get the value of a RemoteRef
##
## remote_call_fetch(w, func, args...) - faster fetch(remote_call(...))
##
## pmap(func, lst) -
## call a function on each element of lst (some 1-d thing), in
## parallel.
##
## RemoteRef() - create an uninitialized RemoteRef on the local processor
##
## RemoteRef(p) - ...or on a particular processor
##
## put(r, val) - store a value to an uninitialized RemoteRef
##
## @spawn expr -
## evaluate expr somewhere. returns a RemoteRef. all variables in expr
## are copied to the remote processor.
##
## @spawnat p expr - @spawn specifying where to run
##
## @spawnlocal expr -
## run expr as an asynchronous task on the local processor
##
## @parallel (r) for i=1:n ... end -
## parallel loop. the results from each iteration are reduced using (r).
##
## @everywhere expr - run expr everywhere.
# todo:
# - more indexing
# * take() to empty a Ref (full/empty variables)
# * have put() wait on non-empty Refs
# - removing nodes
# - more dynamic scheduling
# * fetch/wait latency seems to be excessive
# * message aggregation
# - timer events
# - send pings at some interval to detect failed/hung machines
# - integrate event loop with other kinds of i/o (non-messages)
# ? method_missing for waiting (ref/assign/localdata seems to cover a lot)
# * serializing closures
# * recover from i/o errors
# * handle remote execution errors
# * all-to-all communication
# * distributed GC
# * call&wait and call&fetch combined messages
# * aggregate GC messages
# * dynamically adding nodes (then always start with 1 and grow)
# * add readline to event loop
# * GOs/darrays on a subset of nodes
## workers and message i/o ##
function send_msg_unknown(s::IOStream, kind, args)
error("attempt to send to unknown socket")
end
function send_msg(s::IOStream, kind, args...)
id = worker_id_from_socket(s)
if id > -1
return send_msg(worker_from_id(id), kind, args...)
end
send_msg_unknown(s, kind, args)
end
function send_msg_now(s::IOStream, kind, args...)
id = worker_id_from_socket(s)
if id > -1
return send_msg_now(worker_from_id(id), kind, args...)
end
send_msg_unknown(s, kind, args)
end
type Worker
host::String
port::Int16
fd::Int32
socket::IOStream
sendbuf::IOStream
del_msgs::Array{Any,1}
add_msgs::Array{Any,1}
id::Int
gcflag::Bool
function Worker(host::ByteString, port)
fd = ccall(:connect_to_host, Int32, (Ptr{Uint8}, Int16), host, port)
if fd == -1
error("could not connect to $host:$port, errno=$(errno())\n")
end
Worker(host, port, fd, fdio(fd, true))
end
Worker(host,port,fd,sock,id) = new(host, port, fd, sock, memio(), {}, {}, id, false)
Worker(host,port,fd,sock) = Worker(host,port,fd,sock,0)
end
function send_msg_now(w::Worker, kind, args...)
send_msg_(w, kind, args, true)
end
function send_msg(w::Worker, kind, args...)
send_msg_(w, kind, args, false)
end
function flush_gc_msgs(w::Worker)
w.gcflag = false
msgs = w.add_msgs
if !isempty(msgs)
del_all(w.add_msgs)
remote_do(w, add_clients, msgs...)
end
msgs = w.del_msgs
if !isempty(msgs)
del_all(w.del_msgs)
#print("sending delete of $msgs\n")
remote_do(w, del_clients, msgs...)
end
end
function send_msg_(w::Worker, kind, args, now::Bool)
buf = w.sendbuf
ccall(:jl_buf_mutex_lock, Void, (Ptr{Void},), buf.ios)
serialize(buf, kind)
for arg in args
serialize(buf, arg)
end
ccall(:jl_buf_mutex_unlock, Void, (Ptr{Void},), buf.ios)
if !now && w.gcflag
flush_gc_msgs(w)
else
ccall(:jl_enq_send_req, Void, (Ptr{Void}, Ptr{Void}, Int32),
w.socket.ios, w.sendbuf.ios, now ? int32(1) : int32(0))
end
end
function flush_gc_msgs()
for w = (PGRP::ProcessGroup).workers
if isa(w,Worker)
k = w::Worker
if k.gcflag
flush_gc_msgs(k)
end
end
end
end
## process group creation ##
type LocalProcess
end
type Location
host::String
port::Int16
Location(h,p::Integer) = new(h,int16(p))
end
type ProcessGroup
myid::Int
workers::Array{Any,1}
locs::Array{Any,1}
np::Int
# global references
refs::Dict
function ProcessGroup(myid::Integer, w::Array{Any,1}, locs::Array{Any,1})
return new(myid, w, locs, length(w), Dict())
end
end
function add_workers(PGRP::ProcessGroup, w::Array{Any,1})
n = length(w)
locs = map(x->Location(x.host,x.port), w)
# NOTE: currently only node 1 can add new nodes, since nobody else
# has the full list of address:port
newlocs = append(PGRP.locs, locs)
sockets = Dict()
handler = fd->message_handler(fd, sockets)
for i=1:n
push(PGRP.workers, w[i])
w[i].id = PGRP.np+i
send_msg_now(w[i], w[i].id, newlocs)
sockets[w[i].fd] = w[i].socket
add_fd_handler(w[i].fd, handler)
end
PGRP.locs = newlocs
PGRP.np += n
PGRP
end
function _jl_join_pgroup(myid, locs, sockets)
# joining existing process group
np = length(locs)
w = cell(np)
w[myid] = LocalProcess()
handler = fd->message_handler(fd, sockets)
for i = 2:(myid-1)
w[i] = Worker(locs[i].host, locs[i].port)
w[i].id = i
sockets[w[i].fd] = w[i].socket
add_fd_handler(w[i].fd, handler)
send_msg_now(w[i], :identify_socket, myid)
end
for i = (myid+1):np
w[i] = nothing
end
ProcessGroup(myid, w, locs)
end
myid() = (global PGRP; (PGRP::ProcessGroup).myid)
nprocs() = (global PGRP; (PGRP::ProcessGroup).np)
function worker_id_from_socket(s)
global PGRP
for i=1:nprocs()
w = (PGRP::ProcessGroup).workers[i]
if isa(w,Worker)
if is(s, w.socket) || is(s, w.sendbuf)
return i
end
end
end
if isa(s,IOStream) && fd(s)==-1
# serializing to a local buffer
return myid()
end
return -1
end
function worker_from_id(id)
global PGRP
(PGRP::ProcessGroup).workers[id]
end
# establish a Worker connection for processes that connected to us
function _jl_identify_socket(otherid, fd, sock)
global PGRP
i = otherid
#locs = PGRP.locs
@assert i > PGRP.myid
d = i-length(PGRP.workers)
if d > 0
grow(PGRP.workers, d)
PGRP.workers[(end-d+1):end] = nothing
PGRP.np += d
end
PGRP.workers[i] = Worker("", 0, fd, sock, i)
#write(stdout_stream, "$(PGRP.myid) heard from $i\n")
nothing
end
## remote refs and core messages: do, call, fetch, wait, ref, put ##
const _jl_client_refs = WeakKeyDict()
type RemoteRef
where::Int
whence::Int
id::Int
# TODO: cache value if it's fetched, but don't serialize the cached value
function RemoteRef(w, wh, id)
r = new(w,wh,id)
found = key(_jl_client_refs, r, false)
if !is(found,false)
return found
end
_jl_client_refs[r] = true
finalizer(r, send_del_client)
r
end
REQ_ID::Int = 0
function RemoteRef(pid::Integer)
rr = RemoteRef(pid, myid(), REQ_ID)
REQ_ID += 1
if mod(REQ_ID,200) == 0
# force gc after making a lot of refs since they take up
# space on the machine where they're stored, yet the client
# is responsible for freeing them.
gc()
end
rr
end
RemoteRef(w::LocalProcess) = RemoteRef(myid())
RemoteRef(w::Worker) = RemoteRef(w.id)
RemoteRef() = RemoteRef(myid())
global WeakRemoteRef
function WeakRemoteRef(w, wh, id)
return new(w, wh, id)
end
function WeakRemoteRef(pid::Integer)
rr = WeakRemoteRef(pid, myid(), REQ_ID)
REQ_ID += 1
if mod(REQ_ID,200) == 0
gc()
end
rr
end
WeakRemoteRef(w::LocalProcess) = WeakRemoteRef(myid())
WeakRemoteRef(w::Worker) = WeakRemoteRef(w.id)
WeakRemoteRef() = WeakRemoteRef(myid())
end
hash(r::RemoteRef) = hash(r.whence)+3*hash(r.id)
isequal(r::RemoteRef, s::RemoteRef) = (r.whence==s.whence && r.id==s.id)
rr2id(r::RemoteRef) = (r.whence, r.id)
bottom_func() = assert(false)
function lookup_ref(id)
GRP = PGRP::ProcessGroup
wi = get(GRP.refs, id, ())
if is(wi, ())
# first we've heard of this ref
wi = WorkItem(bottom_func)
# this WorkItem is just for storing the result value
GRP.refs[id] = wi
add(wi.clientset, id[1])
end
wi
end
# is a ref uninitialized? (for locally-owned refs only)
#function ref_uninitialized(id)
# wi = lookup_ref(id)
# !wi.done && is(wi.thunk,bottom_func)
#end
#ref_uninitialized(r::RemoteRef) = (assert(r.where==myid());
# ref_uninitialized(rr2id(r)))
function isready(rr::RemoteRef)
rid = rr2id(rr)
if rr.where == myid()
lookup_ref(rid).done
else
remote_call_fetch(rr.where, id->lookup_ref(id).done, rid)
end
end
function del_client(id, client)
global PGRP
wi = lookup_ref(id)
del(wi.clientset, client)
if isempty(wi.clientset)
del((PGRP::ProcessGroup).refs, id)
#print("$(myid()) collected $id\n")
end
nothing
end
function del_clients(pairs::(Any,Any)...)
for p in pairs
del_client(p[1], p[2])
end
end
function send_del_client(rr::RemoteRef)
if rr.where == myid()
del_client(rr2id(rr), myid())
else
w = worker_from_id(rr.where)
push(w.del_msgs, (rr2id(rr), myid()))
w.gcflag = true
end
end
function add_client(id, client)
wi = lookup_ref(id)
add(wi.clientset, client)
nothing
end
function add_clients(pairs::(Any,Any)...)
for p in pairs
add_client(p[1], p[2])
end
end
function send_add_client(rr::RemoteRef, i)
if rr.where == myid()
add_client(rr2id(rr), i)
elseif i != rr.where
# don't need to send add_client if the message is already going
# to the processor that owns the remote ref. it will add_client
# itself inside deserialize().
w = worker_from_id(rr.where)
push(w.add_msgs, (rr2id(rr), i))
w.gcflag = true
end
end
function serialize(s, rr::RemoteRef)
i = worker_id_from_socket(s)
if i != -1
send_add_client(rr, i)
end
invoke(serialize, (Any, Any), s, rr)
end
type GORef
whence
id
end
# special type for serializing references to GlobalObjects.
# Needed because we want to always wait for the G.O. to be computed and
# return it. in contrast, deserialize() for RemoteRef needs to avoid waiting
# on uninitialized RemoteRefs since that might cause a deadlock, while G.O.s
# are a special case where we know waiting on the RR is OK.
function deserialize(s, t::Type{GORef})
gr = force(invoke(deserialize, (Any, CompositeKind), s, t))
rid = (gr.whence, gr.id)
add_client(rid, myid())
function ()
wi = lookup_ref(rid)
if !wi.done
wait(WeakRemoteRef(myid(), rid[1], rid[2]))
end
v = wi.result
if isa(v,WeakRef)
v = v.value
end
assert(isa(v,GlobalObject))
return v.local_identity
end
end
function deserialize(s, t::Type{RemoteRef})
rr = force(invoke(deserialize, (Any, CompositeKind), s, t))
rid = rr2id(rr)
where = rr.where
if where == myid()
add_client(rid, myid())
end
function ()
if where == myid()
wi = lookup_ref(rid)
if !wi.done
if !is(wi.thunk,bottom_func)
#println("$(myid()) waiting for $where,$(rid[1]),$(rid[2])")
wait(WeakRemoteRef(where, rid[1], rid[2]))
#println("...ok")
else
return RemoteRef(where, rid[1], rid[2])
end
end
v = wi.result
# NOTE: this duplicates work_result()
if isa(v,WeakRef)
v = v.value
end
if isa(v,GlobalObject)
if !anyp(r->(r.whence==rid[1] && r.id==rid[2]), v.refs)
# ref not part of the GlobalObject, so it needs to
# manage its own lifetime
RemoteRef(where, rid[1], rid[2])
else
# here the GlobalObject's finalizer will handle removing
# the client ref we added with add_client above.
end
v = v.local_identity
else
# make a RemoteRef so a finalizer is set up to remove us
# as a client. the RR has been converted to its value, so
# we don't need it any more unless there is another reference
# to this RR somewhere on our system.
RemoteRef(where, rid[1], rid[2])
end
return v
else
# make sure this rr gets added to the _jl_client_refs table
RemoteRef(where, rid[1], rid[2])
end
end
end
schedule_call(rid, f_thk, args_thk) =
schedule_call(rid, ()->apply(force(f_thk),force(args_thk)))
function schedule_call(rid, thunk)
global PGRP
wi = WorkItem(thunk)
(PGRP::ProcessGroup).refs[rid] = wi
add(wi.clientset, rid[1])
enq_work(wi)
wi
end
#localize_ref(b::Box) = Box(localize_ref(b.contents))
#function localize_ref(r::RemoteRef)
# if r.where == myid()
# fetch(r)
# else
# r
# end
#end
#localize_ref(x) = x
# make a thunk to call f on args in a way that simulates what would happen if
# the function were sent elsewhere
function local_remote_call_thunk(f, args)
if isempty(args)
return f
end
return ()->f(args...)
# TODO: this seems to be capable of causing deadlocks by waiting on
# Refs buried inside the closure that we don't want to wait on yet.
# linfo = ccall(:jl_closure_linfo, Any, (Any,), f)
# if isa(linfo,LambdaStaticData)
# env = ccall(:jl_closure_env, Any, (Any,), f)
# buf = memio()
# serialize(buf, env)
# seek(buf, 0)
# env = force(deserialize(buf))
# f = ccall(:jl_new_closure, Any, (Ptr{Void}, Any, Any),
# C_NULL, env, linfo)::Function
# end
# f(map(localize_ref,args)...)
end
function remote_call(w::LocalProcess, f, args...)
rr = RemoteRef(w)
schedule_call(rr2id(rr), local_remote_call_thunk(f,args))
rr
end
function remote_call(w::Worker, f, args...)
rr = RemoteRef(w)
#println("$(myid()) asking for $rr")
send_msg(w, :call, rr2id(rr), f, args)
rr
end
remote_call(id::Integer, f, args...) = remote_call(worker_from_id(id), f, args...)
# faster version of fetch(remote_call(...))
function remote_call_fetch(w::LocalProcess, f, args...)
rr = WeakRemoteRef(w)
oid = rr2id(rr)
wi = schedule_call(oid, local_remote_call_thunk(f,args))
wi.notify = ((), :call_fetch, oid, wi.notify)
force(yieldto(Scheduler, WaitFor(:call_fetch, rr)))
end
function remote_call_fetch(w::Worker, f, args...)
# can be weak, because the program will have no way to refer to the Ref
# itself, it only gets the result.
rr = WeakRemoteRef(w)
oid = rr2id(rr)
send_msg(w, :call_fetch, oid, f, args)
force(yieldto(Scheduler, WaitFor(:call_fetch, rr)))
end
remote_call_fetch(id::Integer, f, args...) =
remote_call_fetch(worker_from_id(id), f, args...)
# faster version of wait(remote_call(...))
remote_call_wait(w::LocalProcess, f, args...) = wait(remote_call(w,f,args...))
function remote_call_wait(w::Worker, f, args...)
rr = RemoteRef(w)
oid = rr2id(rr)
send_msg(w, :call_wait, oid, f, args)
yieldto(Scheduler, WaitFor(:wait, rr))
end
remote_call_wait(id::Integer, f, args...) =
remote_call_wait(worker_from_id(id), f, args...)
function remote_do(w::LocalProcess, f, args...)
# the LocalProcess version just performs in local memory what a worker
# does when it gets a :do message.
# same for other messages on LocalProcess.
enq_work(WorkItem(local_remote_call_thunk(f, args)))
nothing
end
function remote_do(w::Worker, f, args...)
send_msg(w, :do, f, args)
nothing
end
remote_do(id::Integer, f, args...) = remote_do(worker_from_id(id), f, args...)
function sync_msg(verb::Symbol, r::RemoteRef)
pg = (PGRP::ProcessGroup)
oid = rr2id(r)
if r.where==myid() || isa(pg.workers[r.where], LocalProcess)
wi = lookup_ref(oid)
if wi.done
if is(verb,:fetch)
return work_result(wi)
else
return r
end
else
# add to WorkItem's notify list
wi.notify = ((), verb, oid, wi.notify)
end
else
send_msg(pg.workers[r.where], verb, oid)
end
# yield to event loop, return here when answer arrives
v = yieldto(Scheduler, WaitFor(verb, r))
return is(verb,:fetch) ? force(v) : r
end
wait(r::RemoteRef) = sync_msg(:wait, r)
fetch(r::RemoteRef) = sync_msg(:fetch, r)
fetch(x::ANY) = x
# writing to an uninitialized ref
function put_ref(rid, val::ANY)
wi = lookup_ref(rid)
if wi.done
wi.notify = ((), :take, rid, wi.notify)
yieldto(Scheduler, WaitFor(:take, RemoteRef(myid(), rid[1], rid[2])))
end
wi.result = val
wi.done = true
notify_done(wi)
end
function put(rr::RemoteRef, val::ANY)
rid = rr2id(rr)
if rr.where == myid()
put_ref(rid, val)
else
remote_call_fetch(rr.where, put_ref, rid, val)
end
val
end
function take_ref(rid)
wi = lookup_ref(rid)
if !wi.done
wait(RemoteRef(myid(), rid[1], rid[2]))
end
val = wi.result
wi.done = false
notify_empty(wi)
val
end
function take(rr::RemoteRef)
rid = rr2id(rr)
if rr.where == myid()
take_ref(rid)
else
remote_call_fetch(rr.where, take_ref, rid)
end
end
## work queue ##
type WorkItem
thunk::Function
task # the Task working on this item, or ()
done::Bool
result
notify::Tuple
argument # value to pass task next time it is restarted
clientset::IntSet
WorkItem(thunk::Function) = new(thunk, (), false, (), (), (), IntSet(64))
WorkItem(task::Task) = new(()->(), task, false, (), (), (), IntSet(64))
end
function work_result(w::WorkItem)
v = w.result
if isa(v,WeakRef)
v = v.value
end
if isa(v,GlobalObject)
v = v.local_identity
end
v
end
type WaitFor
msg::Symbol
rr
end
function enq_work(wi::WorkItem)
global Workqueue
enqueue(Workqueue, wi)
end
enq_work(f::Function) = enq_work(WorkItem(f))
enq_work(t::Task) = enq_work(WorkItem(t))
function perform_work()
global Workqueue
job = pop(Workqueue)
perform_work(job)
end
function perform_work(job::WorkItem)
global Waiting, Workqueue
local result
try
if isa(job.task,Task)
# continuing interrupted work item
arg = job.argument
job.argument = ()
result = is(arg,()) ? yieldto(job.task) : yieldto(job.task, arg)
else
job.task = Task(job.thunk)
job.task.tls = nothing
result = yieldto(job.task)
end
catch e
#show(e)
print("exception on ", myid(), ": ")
show(e)
println()
result = e
end
if istaskdone(job.task)
# job done
job.done = true
job.result = result
end
if job.done
job.task = ()
# do notifications
notify_done(job)
job.thunk = bottom_func # avoid reference retention
elseif isa(result,WaitFor)
# add to waiting set to wait on a sync event
wf::WaitFor = result
rr = wf.rr
#println("$(myid()) waiting for $rr")
oid = rr2id(rr)
waitinfo = (wf.msg, job, rr)
waiters = get(Waiting, oid, false)
if isequal(waiters,false)
Waiting[oid] = {waitinfo}
else
push(waiters, waitinfo)
end
else
# otherwise return to queue
enq_work(job)
end
end
function deliver_result(sock::IOStream, msg, oid, value)
#print("$(myid()) sending result $oid\n")
if is(msg,:fetch) || is(msg,:call_fetch)
val = value
else
@assert is(msg, :wait)
val = oid
end
try
send_msg_now(sock, :result, msg, oid, val)
catch e
# send exception in case of serialization error; otherwise
# request side would hang.
send_msg_now(sock, :result, msg, oid, e)
end
end
const _jl_empty_cell_ = {}
function deliver_result(sock::(), msg, oid, value_thunk)
global Waiting
# restart task that's waiting on oid
jobs = get(Waiting, oid, _jl_empty_cell_)
for i = 1:length(jobs)
j = jobs[i]
if j[1]==msg
job = j[2]
job.argument = value_thunk
enq_work(job)
del(jobs, i)
break
end
end
if isempty(jobs) && !is(jobs,_jl_empty_cell_)
del(Waiting, oid)
end
nothing
end
notify_done (job::WorkItem) = notify_done(job, false)
notify_empty(job::WorkItem) = notify_done(job, true)
# notify waiters that a certain job has finished or Ref has been emptied
function notify_done(job::WorkItem, take)
newnot = ()
while !is(job.notify,())
(sock, msg, oid, job.notify) = job.notify
if take == is(msg,:take)
let wr = work_result(job)
if is(sock,())
deliver_result(sock, msg, oid, ()->wr)
else
deliver_result(sock, msg, oid, wr)
end
if is(msg,:call_fetch)
# can delete the ref right away since we know it is
# unreferenced by the client
del((PGRP::ProcessGroup).refs, oid)
end
end
else
newnot = (sock, msg, oid, newnot)
end
end
job.notify = newnot
nothing
end
## message event handlers ##
# activity on accept fd
function accept_handler(accept_fd, sockets)
global PGRP
connectfd = ccall(:accept, Int32, (Int32, Ptr{Void}, Ptr{Void}),
accept_fd, C_NULL, C_NULL)
#print("accepted.\n")
if connectfd==-1
print("accept error: ", strerror(), "\n")
else
first = isempty(sockets)
sock = fdio(connectfd, true)
sockets[connectfd] = sock
if first
# first connection; get process group info from client
_myid = force(deserialize(sock))
locs = force(deserialize(sock))
PGRP = _jl_join_pgroup(_myid, locs, sockets)
PGRP.workers[1] = Worker("", 0, connectfd, sock, 1)
end
add_fd_handler(connectfd, fd->message_handler(fd, sockets))
end
end
type DisconnectException <: Exception end
# activity on message socket
function message_handler(fd, sockets)
global PGRP
refs = (PGRP::ProcessGroup).refs
sock = sockets[fd]
first = true
while first || nb_available(sock)>0
first = false
try
msg = force(deserialize(sock))
#print("$(myid()) got $msg\n")
# handle message
if is(msg, :call) || is(msg, :call_fetch) || is(msg, :call_wait)
id = force(deserialize(sock))
f = deserialize(sock)
args = deserialize(sock)
#print("$(myid()) got call $id\n")
wi = schedule_call(id, f, args)
if is(msg, :call_fetch)
wi.notify = (sock, :call_fetch, id, wi.notify)
elseif is(msg, :call_wait)
wi.notify = (sock, :wait, id, wi.notify)
end
elseif is(msg, :do)
f = deserialize(sock)
args = deserialize(sock)
#print("$(myid()) got $args\n")
let func=f, ar=args
enq_work(WorkItem(()->apply(force(func),force(ar))))
end
elseif is(msg, :result)
# used to deliver result of wait or fetch
mkind = force(deserialize(sock))
oid = force(deserialize(sock))
val = deserialize(sock)
deliver_result((), mkind, oid, val)
elseif is(msg, :identify_socket)
otherid = force(deserialize(sock))
_jl_identify_socket(otherid, fd, sock)
else
# the synchronization messages
oid = force(deserialize(sock))::(Int,Int)
wi = lookup_ref(oid)
if wi.done
deliver_result(sock, msg, oid, work_result(wi))
else
# add to WorkItem's notify list
# TODO: should store the worker here, not the socket,
# so we don't need to look up the worker later
wi.notify = (sock, msg, oid, wi.notify)
end
end
catch e
if isa(e,EOFError)
#print("eof. $(myid()) exiting\n")
del_fd_handler(fd)
# TODO: remove machine from group
throw(DisconnectException())
else
print("deserialization error: ", e, "\n")
read(sock, Uint8, nb_available(sock))
#while nb_available(sock) > 0 #|| select(sock)
# read(sock, Uint8)
#end
end
end
end
end
## worker creation and setup ##
# the entry point for julia worker processes. does not return.
# argument is descriptor to write listening port # to.
start_worker() = start_worker(1)
function start_worker(wrfd)
port = [int16(9009)]
sockfd = ccall(:open_any_tcp_port, Int32, (Ptr{Int16},), port)
if sockfd == -1
error("could not bind socket")
end
io = fdio(wrfd)
write(io, "julia_worker:") # print header
fprintf(io, "%d#", port[1]) # print port
write(io, getipaddr()) # print hostname
write(io, '\n')
flush(io)
# close stdin; workers will not use it
ccall(:close, Int32, (Int32,), 0)
global const Scheduler = current_task()
worker_sockets = Dict()
add_fd_handler(sockfd, fd->accept_handler(fd, worker_sockets))
try
event_loop(false)
catch e
print("unhandled exception on $(myid()): $e\nexiting.\n")
end
ccall(:close, Int32, (Int32,), sockfd)
ccall(:exit , Void , (Int32,), 0)
end
# establish an SSH tunnel to a remote worker
# returns P such that localhost:P connects to host:port
# function worker_tunnel(host, port)
# localp = 9201
# while !success(`ssh -f -o ExitOnForwardFailure=yes julia@$host -L $localp:$host:$port -N`)
# localp += 1
# end
# localp
# end
function start_remote_workers(machines, cmds)
n = length(cmds)
outs = cell(n)
for i=1:n
let fd = read_from(cmds[i]).fd
let stream = fdio(fd, true)
outs[i] = stream
# redirect console output from workers to the client's stdout
add_fd_handler(fd, fd->write(stdout_stream, readline(stream)))
end
end
end
for c in cmds
spawn(c)
end
w = cell(n)
for i=1:n