This repository has been archived by the owner on Apr 16, 2018. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathdeleted
1754 lines (1490 loc) · 63 KB
/
deleted
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
compute_id : undefined
_create: (cb) =>
_open_somewhere: (ssh_timeout, cb) =>
# assuming that the project is *not* "zpool imported'" on any host, choose a host and set everything up there.
# Willi create the project if that hasn't happened yet.
dbg = (m) -> @dbg("_open_somewhere",[ssh_timeout],m)
cb()
_close_all_but_one: (open_state, cb) =>
# Assuming that the project currently is "zpool imported" on *multiple* hosts, choose the one with most
# recent activity, and export the others (also sending their streams, and saving to the db.... just in case).
dbg = (m) -> @dbg("_close_all_but_one",open_state,m)
cb()
_verify_project_works_at: (compute_id, ssh_timeout, cb) => # cb(err)
# Determine whether or not it is possible to ssh from this host to the compute host
# and login as the project user within ssh_timeout seconds.
dbg = (m) -> @dbg("_verify_project_works_at",[compute_id, ssh_timeout],m)
cb()
open: (opts) =>
opts = defaults opts,
ssh_timeout : 15
cb : required # cb(err, ip_address of computer on which project is ready to use)
dbg = (m) -> @dbg("open_project",[],m)
state = undefined
compute_id = undefined
works = undefined
host = undefined
async.series([
(cb) =>
dbg('get state')
@state (err, _state) =>
state = _state
cb(err)
(cb) =>
open = (x for x in state when x.import_pool?)
dbg('already open on #{open.length} hosts')
if open.length == 0
@_open_somewhere opts.ssh_timeout, (err, _compute_id) =>
if err
cb(err)
else
compute_id = _compute_id
works = true
cb()
else if open.length == 1
compute_id = open[0].compute_id
cb()
else
@_close_all_but_one open, (err, _compute_id) =>
compute_id = _compute_id
cb(err)
(cb) =>
if works
cb()
else
dbg('verify that project really works at @{compute_id}')
@_verify_project_works_at compute_id, opts.ssh_timeout, (err) =>
if err
dbg("it doesn't work at @{compute_id}")
@_open_somewhere (err, _compute_id) =>
compute_id = _compute_id
cb(err)
else
dbg("yep, it works")
cb()
(cb) =>
compute_id_to_host compute_id, (err, _host) =>
host = _host; cb(err)
], (err) =>
if not err
@compute_id = compute_id
opts.cb(err, host)
)
#############
###
# pool must be an array [['hostname', port, 'token_key...'], ...]
exports.client = (opts) -> # cb(err, client)
opts = defaults opts,
pool : required
cb : required
C = new Client pool, (err) ->
if err
cb(err)
else
cb(false, C)
class Client
constructor : (@pool, cb) -> # cb(err)
@connections = []
f = (i, cb) ->
h = @hosts[i]
@_connect(h[0], h[1], h[2], cb)
async.map @pool, f, (err) ->
cb(err)
_connect: (hostname, port, token_key, cb) =>
socket = misc_node.connect_to_locked_socket
host : @hosts[i][0]
port : @hosts[i][1]
timeout : 15
token : @hosts[i][2]
cb : (err) ->
if err
cb(err)
else
misc_node.enable_mesg(socket)
@connections.push(socket)
cb()
snap_ls : (opts) =>
snap_restore : (opts) =>
snap_log : (opts) =>
###
###
if req.method == "POST"
data = ''
req.on 'data', (chunk) -> data += chunk
req.on 'end', () ->
winston.debug("data = ", data)
winston.debug("got file of length #{data.length} and id #{query.uuid}, #{misc.to_json()}")
###
ocreate_unix_user_on_random_compute_server = (opts) ->
opts = defaults opts,
cb : required
opts.cb(false, {host:'localhost', username:'sage0', port:22})
"""
TO DO
async.series([
(cb) ->
# first get a computer on which to create an account
# (TODO: load balance)
database.random_compute_server
cb : (err, _compute_server) ->
if err
cb(err)
else
compute_server = _compute_server
cb()
], (err) ->
cb(err, unix_user)
)
"""
# The CodeMirrorDiffSyncHub class represents a global hub viewed as a
# remote server for this client.
class CodeMirrorDiffSyncHub
constructor: (@cm_session) ->
connect: (remote) =>
@remote = remote
recv_edits: (edit_stack, last_version_ack, cb) =>
#console.log("Sending the following edits to the server: ", edit_stack, last_version_ack)
@cm_session.call
message : message.codemirror_diffsync(edit_stack:edit_stack, last_version_ack:last_version_ack)
timeout : 5
cb : (err, mesg) =>
#console.log("codemirror sync got back: ", mesg)
if err
cb(err)
else if mesg.event == 'error'
cb(mesg.error)
else
@remote.recv_edits(mesg.edit_stack, mesg.last_version_ack, cb)
class CodeMirrorSession extends EventEmitter
constructor : (opts) ->
opts = defaults opts,
conn : required
project_id : required
path : required
cb : required
@conn = opts.conn
@project_id = opts.project_id
@path = opts.path
@connect (err, session, content) =>
if not err
@init_dsync(content)
opts.cb(err, session, content)
connect: (cb) =>
@conn.call
message: message.codemirror_get_session
path : @path
project_id : @project_id
cb : (err, resp) =>
if err
cb(err)
else if resp.event == 'error'
cb(resp.error)
else
@session_uuid = resp.session_uuid
cb(false, @, resp.content)
init_dsync: (content) =>
@dsync_client = new diffsync.DiffSync(doc:content)
@dsync_server = new CodeMirrorDiffSyncHub(@)
@dsync_client.connect(@dsync_server)
@dsync_server.connect(@dsync_client)
@conn.on 'codemirror_diffsync_ready', (mesg) =>
if mesg.session_uuid == @session_uuid
before = @dsync_client.live
@sync (err) =>
if before != @dsync_client.live
@emit 'change', @dsync_client.live
@sync()
sync: (cb) =>
if @_syncing
# TODO -- ensure that this lock times out -- we do not want to loose sync forever!!
cb("already syncing")
return
@_syncing = true
@dsync_client.push_edits (err) =>
@_syncing = false
cb?(err)
change: (content, cb) =>
if @dsync_client?
@dsync_client.live = content
@sync (err) =>
if err
cb?(err)
else
cb?(false, @dsync_client.live)
else
cb?()
call: (opts) =>
opts = defaults opts,
message : required
timeout : 10
cb : undefined
#console.log("call #{misc.to_json(opts.message)}")
opts.message.session_uuid = @session_uuid
@conn.call
message : opts.message
timeout : opts.timeout
cb : (err, result) =>
if not err and result.event == 'reconnect'
# Try one time to connect then resend message.
@connect (err) =>
if err
opts.cb(err)
else
@conn.call(message: opts.message, cb:opts.cb)
return
opts.cb(err, result)
write_to_disk: (cb) =>
@call
message: message.codemirror_write_to_disk()
cb : cb
read_from_disk: (cb) =>
@call
message : message.codemirror_read_from_disk()
cb : cb
get_content: (cb) => # cb(err, content)
@call
message : message.codemirror_get_content()
cb : (err, resp) => cb(err, resp?.content)
###########################################################
# Receive and process the edits from the other end of the sync connection.
recv_edits: (edit_stack, last_version_ack, cb) =>
if SIMULATE_LOSS and Math.random() < .5 # Simulate packet loss
console.log("Simulating loss!"); cb(true); return
# Keep only edits that we still need to send.
@edit_stack = (edits for edits in @edit_stack when edits.shadow_version > last_version_ack)
if edit_stack.length == 0
cb()
return
if edit_stack[0].shadow_version != @shadow_version and edit_stack[0].shadow_version == @backup_shadow_version
# Lost return packet
@shadow = @_copy(@backup_shadow)
@shadow_version = @backup_shadow_version
@edit_stack = []
# Make a backup, just in case it turns out that our message
# back to the client that we applied these changes is lost
# "Lost return packet."
@backup_shadow = @_copy(@shadow)
@backup_shadow_version = @shadow_version
tasks = []
for edits in edit_stack
tasks.push(
(cb) =>
if edits.shadow_version == @shadow_version
if edits.shadow_checksum != @_checksum(@shadow)
# Data corruption in memory or network: we have to just restart everything from scratch.
cb('reset')
return
@last_version_received = edits.shadow_version
@shadow = @_apply_edits0(edits.edits, @shadow)
@shadow_version += 1
@live = @_apply_edits0(edits.edits, @live)
cb()
# @_apply_edits edits.edits, @shadow, (err, result) =>
# if err
# cb(err)
# else
# @shadow = result
# @shadow_version += 1
# @_apply_edits_to_live(edits.edits, cb)
else
if edits.shadow_version < @shadow_version
# Packet duplication or loss: ignore -- it will sort itself out later.
cb()
else if edits.shadow_version > @shadow_version
# This should be impossible, unless there is data corruption.
cb('reset')
)
async.series(tasks, (err) => cb?(err))
# Connect the client with a codemirror file editing session.
connect_to_codemirror_session: (opts) =>
opts = defaults opts,
client : required
project_id : required
params : undefined
session_uuid : undefined # if undefined, a new session is created; if defined, connect to session or get error
cb : required # cb(err, [session_connected message])
if not opts.session_uuid?
opts.session_uuid = uuid.v4()
@_open_session_socket
session_uuid : opts.session_uuid
project_id : opts.project_id
type : 'codemirror'
params : opts.params
cb : (err, socket) =>
winston.debug("open codemirror session -- #{err}")
if err
opts.cb(err)
return
if not socket.clients?
socket.clients = []
else
socket.clients.push(opts.client)
socket.on 'end', () =>
delete @_sockets[opts.session_uuid]
socket.on 'mesg', (type, mesg) =>
winston.debug("GOT A MESSAGE FROM THE CodeMirror local-hub server: #{misc.to_json(mesg)}")
mesg = message.session_connected(session_uuid : opts.session_uuid)
opts.cb(false, mesg)
############################################################################
############################################################################
class old_Project
constructor: (@project_id) ->
if not @project_id?
throw "When creating Project, the project_id must be defined"
@local_path = "#{project_data}/#{@project_id}/"
owner: (cb) =>
database.get_project_data
project_id : @project_id
columns : ['account_id']
cb : (err, result) =>
if err
cb(err)
else
cb(err, result[0])
##############################################
# Database state stuff
##############################################
_choose_new_host: (cb) ->
# For now we just choose a host at random. In the long run,
# we may experiment with other load balancing algorithms, and
# take into account properties of the project itself. For
# example, we will have an "infinite uptime" option.
database.random_compute_server type:'project', cb:(err, hostinfo) ->
#winston.debug("*** #{err}, #{misc.to_json(hostinfo)}")
if err
cb(err)
else if not hostinfo?
cb("No project servers are currently available.")
else
cb(false, hostinfo.host)
_minus_one_host: (host, cb) ->
database.score_compute_server(host:host, cb:cb, delta:-1)
_plus_one_host: (host, cb) ->
database.score_compute_server(host:host, cb:cb, delta:+1)
_connect: (host, cb) ->
if not host?
throw "BUG -- host must be defined"
if @_socket? and @_socket.host == host
cb(false, @_socket.socket)
return
socket = net.connect {host:host, port:cass.COMPUTE_SERVER_PORTS.project}, () =>
winston.debug("!! connected to #{misc.to_json(host)}")
# connected
misc_node.enable_mesg(socket)
# We cache the connection for later. We only cache a
# connection to *one* host, since a project is only
# supposed to ever be hosted on one compute server.
@_socket = {host:host, socket:socket}
cb(false, socket)
# There are numerous actions that require adding a listener to
# the socket, sending blobs, then removing it. Since many of
# these could happen simultaneously, I'm upping the max
# listeners a bit, just in case.
socket.setMaxListeners(30)
socket.once 'error', (err) =>
if err == 'ECONNREFUSED'
# An error occured connecting -- this suggests
# that the relevant project server is down.
cb(err)
# Make sure not to cache the socket in case anything goes wrong with it.
socket.once 'close', () =>
if @_socket?
delete @_socket
socket.once 'end', () =>
if @_socket?
delete @_socket
socket.once 'timeout', () =>
if @_socket?
delete @_socket
# Returns the host that is currently hosting the project
# (according to the database) or null if the project is not
# currently on any host.
get_host: (cb) => # cb(err, host)
database.get_project_host(project_id:@project_id, cb:cb)
_is_being_opened: (cb) => # cb(err, is_being_opened)
database.is_project_being_opened(project_id:@project_id, cb:cb)
_lock_for_opening: (ttl, cb) => # cb(err)
database.lock_project_for_opening(project_id:@project_id, ttl:ttl, cb:cb)
_remove_opening_lock: (cb) =>
database.remove_project_opening_lock(project_id:@project_id, cb:cb)
_is_being_saved: (cb) => # cb(err, is_being_opened)
database.is_project_being_saved(project_id:@project_id, cb:cb)
_lock_for_saving: (ttl, cb) => # cb(err)
database.lock_project_for_saving(project_id:@project_id, ttl:ttl, cb:cb)
_remove_saving_lock: (cb) =>
database.remove_project_saving_lock(project_id:@project_id, cb:cb)
# Open the project (if necessary) and get a working socket connection to the project_server.
socket: (cb) -> # cb(err, socket)
host = undefined
socket = undefined
async.series([
(c) =>
@open (err, _host) =>
if err
winston.debug("project.socket -- error opening project -- #{to_json(err)}")
c(err)
else
host = _host
winston.debug("project.socket -- deploy to host '#{host}'")
c()
(c) =>
@_connect host, (err, _socket) =>
if err
winston.debug("project.socket -- error connecting to project server #{err}")
c(err)
else
socket = _socket
winston.debug("project.socket -- got a socket connection to the project_server")
c()
], (err) ->
if err
cb(err)
else
cb(false, socket)
)
# Open the project on some host if it is not already opened. If it
# is currently being opened by this or another hub, we return an
# error. (The client can choose to show some sort of notification
# and retry after waiting a moment.)
open: (cb) -> # cb(err, host)
if not cb?
throw "cb must be defined"
host = undefined
had_to_recurse = false
async.series([
# First, we check in the database to see if the project is
# already opened on a compute server, and if so, return
# that host.
(c) =>
winston.debug("open project -- get host")
@get_host (err, _host) ->
host = _host
if err
c(true) # failed -- done
else if _host?
c(true) # done
else
c()
# Is anybody else trying to open this project right now?
(c) =>
winston.debug("open project -- check if anybody else opening project right now")
@_is_being_opened (err, is_being_opened) =>
if err
c(true) # failed -- don't try any further
else if is_being_opened
# In the rare case of two opens at the same
# time, try again repeatedly, up to a total of
# 10 seconds (after which user client will
# have given up).
total_time = 0
delta = 200
try_again = () =>
@get_host (err, _host) ->
if not err and _host? # got it!
host = _host
c(true)
else
delta += delta
if total_time + delta <= 10000
setTimeout(try_again, delta)
else
# give up.
c("Project #{@project_id} is currently being opened by another hub. Please try again in a few seconds. (#{err})")
setTimeout(try_again, delta)
else
# Not open, not being opened, let's get on it!
# The 15 below is a timeout in seconds, after which our lock self-destructs.
@_lock_for_opening(15, c)
# We choose a project server host.
(c) =>
winston.debug("open project -- choose a host")
@_choose_new_host (err, _host) =>
if err
@_remove_opening_lock()
c(err)
else
host = _host
c()
# Open the project on that host
(c) =>
winston.debug("open project -- open on that host (='#{host}')")
@_open_on_host host, (err) =>
@_remove_opening_lock()
if err
if host == 'localhost' or host == '127.0.0.1'
# debugging mode -- just give up instantly.
winston.debug("_open_on_host -- err opening on localhost '#{to_json(err)}'")
host = undefined # so error messages will propagate below.
c(err)
return
# Downvote this host, and try again.
@_minus_one_host host, (err) =>
if err
# This is serious -- if we can't even connect to the database
# to flag a host as down, then there is no point in going on.
host = undefined # so error messages will propagate below.
c(true)
else
# Try again. This will not lead to infinite recursion since each
# time it is called, we just successfully flagged a host as down
# in the database, and eventually we'll run out of hosts.
had_to_recurse = true
@open(cb)
host = undefined # so error messages will propagate below.
c()
else
# Finally, got it!
# Upvote this host, since it worked.
@_plus_one_host(host)
c()
], (err) ->
if not had_to_recurse # the recursive call will call cb
if host? # if host got defined then done
cb(false, host)
else
cb(err)
)
_initialize_local_path: (cb) =>
# Initialize a local copy of the project -- first the simplest possible approach; this will get more complicated later ! TODO
async.series([
(cb) =>
fs.mkdir @local_path, 0o700, cb
(cb) =>
# Just do a local rsync from the template.
misc_node.execute_code
command : "rsync"
args : ['-axH', PROJECT_TEMPLATE, @local_path]
timeout : 30
bash : false
path : SALVUS_HOME
cb : cb
(cb) =>
# Add a gitconfig, if not in local files
gitconfig = @local_path + '.gitconfig'
fs.exists gitconfig, (exists) =>
if exists
cb()
return
@owner((err,account_id) =>
if err
cb(err)
else
database.get_gitconfig account_id: account_id, cb:(err, contents) =>
if err
cb(err)
else
fs.writeFile(gitconfig, contents, cb)
)
], cb)
_open_on_host: (host, cb) =>
# Find out if project already exists on some remote storage server
# If yes, rsync it from there to local
# If no, create project from scratch (locally)
# or create project from a template (another project; like "forking" in
# github) by rsyncing from remote storage server
# In either case, we now have local project -- select a project_server.
# Rsync local project to that project_server.
remote_path = "#{misc_node.username(@project_id)}@#{host}:"
id = uuid.v4() # used to tag communication with the project server
socket = undefined
quota = undefined
idle_timeout = undefined
async.series([
(cb) =>
winston.debug("project: initialize '#{@local_path}'")
fs.exists @local_path, (exists) =>
if not exists
@_initialize_local_path(cb)
else
cb()
# Get a connection to the project server.
(cb) =>
winston.debug("_open_on_host - get a connection to the project server.")
@_connect host, (err, s) ->
if err
cb(err)
else
socket = s
cb()
# Get meta information about the project that is needed to open the project.
(cb) =>
winston.debug("_open_on_host -- get meta information about the project that is needed to open the project.")
database.get_project_open_info project_id:@project_id, cb:(err, result) ->
if err
cb(err)
else
{quota, idle_timeout} = result
cb()
# Send open_project mesg.
(cb) =>
winston.debug("_open_on_host -- Send open_project mesg")
# TODO:
ssh_public_key = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCd5N5Vz1Kv4QqYkWVGxKQfvnZjlMnbdu2wkB9mInLqUAoqkkOTq4B0Qq5rtgMK8AfTYqoi4jAF1R/qJpGLGqAm359Yc6vXOMq5Gy0cDekAb/JOADbmtsYzElv+YhCwnD1MAXqjrv0+W16Y8j6IFjjuvzf4Egnria0s5kddcCwLCkYU9sJUs6OXUDqzK05jhO3PF3P40f3sKKFdZLIH4rVkKdM3ynJ0gNoBqI/xak/9Tz3U0aSZXK7DfO7kjI5PCZr2EVI83u8XAwskDM9XDdifNED3Ctae/x7FkpdpLNiXjOsUKJ0cnJmBFDwO0M4Vt8L8zROy2aH8ZEhD1cqGF69D salvus"
mesg_open_project = message.open_project
id : id
project_id : @project_id
quota : quota
idle_timeout : idle_timeout
ssh_public_key: ssh_public_key # computed on startup of hub
socket.write_mesg 'json', mesg_open_project
cb()
# Wait for response that project user has been created and public key written
(cb) =>
winston.debug("_open_on_host -- wait for the project server to respond")
socket.recv_mesg id:id, type:'json', timeout:30, cb:(mesg) ->
winston.debug("_open_on_host -- received response #{misc.to_json(mesg)}")
switch mesg.event
when 'error'
# something went wrong...
cb(mesg.error)
when 'project_opened'
# finally, got it.
cb()
else
cb("Expected a 'project_opened' message, but got a '#{mesg.event}' message instead.")
# Push files to the project
(cb) =>
winston.debug("_open_on_host -- push files to the project")
misc_node.execute_code
command : "rsync"
args : ['-axH', '--delete', '--exclude', '.ssh', '-e', "ssh -o StrictHostKeyChecking=no", @local_path, remote_path]
timeout : 30
bash : false
path : SALVUS_HOME
cb : (err, output) =>
if err
cb("Error running rsync at all: #{err}")
else
cb()
# Save where project is running to the database
(cb) =>
winston.debug("_open_on_host -- save where (='#{host}') project running to database")
database.set_project_host(project_id:@project_id, host:host, cb:cb)
], cb)
# This is called by 'open' once we determine that the project is
# not already opened, and also we determine on which host we plan
# to open the project.
XXX_open_on_host: (host, cb) ->
socket = undefined
id = uuid.v4() # used to tag communication with the project server
bundles = undefined
quota = undefined
idle_timeout = undefined
async.series([
# Get a connection to the project server.
(c) =>
winston.debug("_open_on_host - get a connection to the project server.")
@_connect host, (err, s) ->
if err
c(err)
else
socket = s
c()
# Get each bundle blob from the database in preparation to
# send it to the project_server.
(c) =>
winston.debug("_open_on_host - get bundle blobs from the database.")
database.get_project_bundles project_id:@project_id, cb:(err, result) ->
if err
c(err)
else
# bundles is an array of pairs [filename, Buffer].
bundles = result
# Make a corresponding list of temporary
# uuid's that will be used when sending the
# bundles.
bundles.uuids = ([uuid.v4(),bundles[i][0]] for i in [0...bundles.length])
c()
# Get meta information about the project that is needed to open the project.
(c) =>
winston.debug("_open_on_host -- get meta information about the project that is needed to open the project.")
database.get_project_open_info project_id:@project_id, cb:(err, result) ->
if err
c(err)
else
{quota, idle_timeout} = result
c()
# Send open_project mesg.
(c) =>
winston.debug("_open_on_host -- Send open_project mesg")
mesg_open_project = message.open_project
id : id
project_id : @project_id
bundle_uuids : bundles.uuids
quota : quota
idle_timeout : idle_timeout
socket.write_mesg 'json', mesg_open_project
c()
# Starting sending the bundles as blobs.
(c) ->
winston.debug("_open_on_host -- start sending #{bundles.length} bundles as blobs")
for i in [0...bundles.length]
socket.write_mesg 'blob', {uuid:bundles.uuids[i][0], blob:bundles[i][1]}
c()
# Wait for the project server to respond with success
# (having received all blobs) or failure (something went wrong).
(c) ->
winston.debug("_open_on_host -- wait for the project server to respond")
socket.recv_mesg id:id, type:'json', timeout:30, cb:(mesg) ->
winston.debug("_open_on_host -- received response #{misc.to_json(mesg)}")
switch mesg.event
when 'error'
# something went wrong...
c(mesg.error)
when 'project_opened'
# finally, got it.
c()
else
c("Expected a 'project_opened' message, but got a '#{mesg.event}' message instead.")
# Save where project is running to the database
(c) =>
winston.debug("_open_on_host -- save where (='#{host}') project running to database")
database.set_project_host(project_id:@project_id, host:host, cb:c)
], cb)
# Save the project to the database. This involves saving at least
# zero (!) bundles to the project_bundles uuid:blob table.
save: (cb) -> # cb(err) -- indicates when done
id = uuid.v4() # used to tag communication with the project server
host = undefined
not_open = false
nothing_to_do = false
async.series([
# If project is already locked for saving (by this or
# another hub), return an error.
(c) =>
@_is_being_saved (err, is_being_saved) =>
if err
c(err)
else if is_being_saved
nothing_to_do = true
c(true)
else
@_lock_for_saving(15, c)
# Determine which project_server is hosting this project.
# If none, then there is nothing further to do.
(c) =>
database.get_project_host project_id:@project_id, cb:(err, _host) =>
if err
c(err)
else
if not _host?
not_open = true
c(true)
else
host = _host
c()
(c) =>
winston.debug("save: rsync files from remote")
remote_path = "#{misc_node.username(@project_id)}@#{host}:"
misc_node.execute_code
command : "rsync"
args : ['-axH', '--stats', '--delete', '--exclude', '.ssh', '-e', "ssh -o StrictHostKeyChecking=no", remote_path, @local_path]
timeout : 30
bash : false
path : SALVUS_HOME
cb : (err, output) =>
if err
c("rsync project --> hub: exited with nonzero code: stderr = #{err}")
else
s = 'Number of files transferred:'
i = output.stdout.indexOf(s)
if i == -1
winston.debug("BUG! Output of rsync doesn't contain '#{s}', but it must!")
else
t = output.stdout.slice(i+s.length+1)
j = t.indexOf('\n')
if t.slice(0,j) != '0'
# Sent at least one file modification.
# Get the size of the resulting directory, and save this to the database.
@size_of_local_copy((err,size) =>
if err
c(err)
else
database.touch_project
project_id : @project_id
size : size
cb : c
)
else
c()
], (err) =>
if err and nothing_to_do
cb?()
return
@_remove_saving_lock()
if not_open
cb?()
else
cb?(err)
)
# return total size in bytes of the local copy of files in the project
size_of_local_copy: (cb) =>
misc_node.execute_code
command : 'du'
args : ['-bs', @local_path]
timeout : 15
bash : false
path : SALVUS_HOME
cb : (err, output) =>
if err
cb(err)
else
i = output.stdout.indexOf(' ')
size = parseInt(output.stdout.slice(0,i))
cb(false, size)
delete: (cb) =>
@close(() => database.delete_project(project_id:@project_id, cb:cb))
# Close the project. This save the project first, then
# kills all processes and clears all disk space.
close: (cb) => # cb(err) -- indicates when done
id = uuid.v4()
socket = undefined
host = undefined
async.series([
(c) =>
@save(c)
# Get project's current host
(c) =>
database.get_project_host project_id:@project_id, cb: (err, _host) ->
if err
c(true)
else
if not _host? # not currently hosted somewhere, so "done" but no error.
c('ok')
else
host = _host
c()
# Connect to the project server that is hosting this project right now.
(c) =>
@_connect host, (err, s) ->
if err
c(err)
else
socket = s
c()