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
/
bup_server.coffee
3507 lines (3253 loc) · 140 KB
/
bup_server.coffee
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
###############################################################################
#
# SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal.
#
# Copyright (C) 2014, William Stein
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
#################################################################
#
# bup_server -- a node.js program that provides a TCP server
# that is used by the hubs to organize project storage
#
# (c) William Stein, 2014
#
# NOT released under any open source license.
#
# Interactive use:
#
# x={};s=require('bup_server').global_client(cb:(err,c)->x.c=c;x.p=x.c.get_project('0069cdc2-3baa-4561-9c9e-17cb08e9b849'))
#
#################################################################
async = require('async')
winston = require('winston')
program = require('commander')
daemon = require('start-stop-daemon')
net = require('net')
fs = require('fs')
message = require('message')
misc = require('misc')
misc_node = require('misc_node')
uuid = require('node-uuid')
cassandra = require('cassandra')
cql = require("cassandra-driver")
# Set the log level
winston.remove(winston.transports.Console)
winston.add(winston.transports.Console, {level: 'debug', timestamp:true, colorize:true})
{defaults, required} = misc
TIMEOUT = 60*60
# never do a save action more frequently than this - more precisely, saves just get
# ignored until this much time elapses *and* an interesting file changes.
MIN_SAVE_INTERVAL_S = 60*10 # 10 minutes
STORAGE_SERVERS_UPDATE_INTERVAL_S = 60*3 # How frequently (in seconds) to query the database for the list of storage servers
IDLE_TIMEOUT_INTERVAL_S = 120 # The idle timeout checker runs once ever this many seconds.
ZPOOL = if process.env.BUP_POOL? then process.env.BUP_POOL else 'bup'
#console.log("ZPOOL=",ZPOOL)
CONF = "/bup/conf"
fs.exists CONF, (exists) ->
if exists
# only makes sense to do this on server nodes...
fs.chmod(CONF, 0o700) # just in case...
DATA = 'data'
###########################
## server-side: Storage server code
###########################
bup_storage = (opts) =>
opts = defaults opts,
args : required
timeout : TIMEOUT
cb : required
winston.debug("bup_storage: running #{misc.to_json(opts.args)}")
misc_node.execute_code
command : "sudo"
args : ["/usr/local/bin/bup_storage.py", "--zpool", ZPOOL].concat(opts.args)
timeout : opts.timeout
bash : false
path : process.cwd()
cb : (err, output) =>
winston.debug("bup_storage: finished running #{misc.to_json(opts.args)} -- #{err}")
if err
if output?.stderr
opts.cb(output.stderr)
else
opts.cb(err)
else
opts.cb(undefined, if output.stdout then misc.from_json(output.stdout) else undefined)
# A single project from the point of view of the storage server -- this runs on the compute machine
class Project
constructor: (opts) ->
opts = defaults opts,
project_id : required
verbose : true
@project_id = opts.project_id
@verbose = opts.verbose
dbg: (f, args, m) =>
if @verbose
winston.debug("Project(#{@project_id}).#{f}(#{misc.to_json(args)}): #{m}")
exec: (opts) =>
opts = defaults opts,
args : required
timeout : TIMEOUT
cb : required
args = []
for a in opts.args
args.push(a)
args.push(@project_id)
@dbg("exec", opts.args, "executing bup_storage.py script")
bup_storage
args : args
timeout : opts.timeout
cb : opts.cb
action: (opts) =>
opts = defaults opts,
action : required # sync, save, etc.
timeout : TIMEOUT
param : undefined # if given, should be an array or string
cb : undefined # cb?(err)
@dbg('action', opts)
if opts.action == 'get_state'
@get_state(cb : (err, state) => opts.cb?(err, state))
return
state = undefined
result = undefined
# STATES: stopped, starting, running, restarting, stopping, saving, error
async.series([
(cb) =>
@get_state
cb : (err, s) =>
state = s; cb(err)
(cb) =>
if opts.param == 'force'
force = true
delete opts.param
else
force = false
switch opts.action
when 'start'
if state in ['stopped', 'error'] or force
@state = 'starting'
@_action
action : 'start'
param : opts.param
timeout : opts.timeout
cb : (err, r) =>
result = r
if err
@dbg("action", opts, "start -- error starting=#{err}")
@state = 'error'
else
@dbg("action", opts, "started successfully -- changing state to running")
@state = 'running'
cb(err)
else
cb()
when 'restart'
if state in ['running', 'error'] or force
@state = 'restarting'
@_action
action : 'restart'
param : opts.param
timeout : opts.timeout
cb : (err, r) =>
result = r
if err
@dbg("action", opts, "failed to restart -- #{err}")
@state = 'error'
else
@dbg("action", opts, "restarted successfully -- changing state to running")
@state = 'running'
cb(err)
else
cb()
when 'stop'
if state in ['running', 'error'] or force
@state = 'stopping'
@_action
action : 'stop'
param : opts.param
timeout : opts.timeout
cb : (err, r) =>
result = r
if err
@dbg("action", opts, "failed to stop -- #{err}")
@state = 'error'
else
@dbg("action", opts, "stopped successfully -- changing state to stopped")
@state = 'stopped'
cb(err)
else
cb()
when 'save'
if state in ['running'] or force
if not @_last_save? or misc.walltime() - @_last_save >= MIN_SAVE_INTERVAL_S
@state = 'saving'
@_last_save = misc.walltime()
@_action
action : 'save'
param : opts.param
timeout : opts.timeout
cb : (err, r) =>
result = r
if err
@dbg("action", opts, "failed to save -- #{err}")
@state = 'error'
else
@dbg("action", opts, "saved successfully -- changing state from saving back to running")
@state = 'running'
cb(err)
else
# ignore
cb()
else
cb()
else
@_action
action : opts.action
param : opts.param
timeout : opts.timeout
cb : (err, r) =>
result = r
cb(err)
], (err) =>
opts.cb?(err, result)
)
_action: (opts) =>
opts = defaults opts,
action : required # sync, save, etc.
param : undefined # if given, should be an array or string
timeout : TIMEOUT
cb : undefined # cb?(err)
dbg = (m) => @dbg("_action", opts, m)
dbg()
switch opts.action
when "get_state"
@get_state
cb : opts.cb
else
dbg("Doing action #{opts.action} that involves executing script")
args = [opts.action]
if opts.param? and opts.param != 'force'
if typeof opts.param == 'string'
opts.param = misc.split(opts.param) # turn it into an array
args = args.concat(opts.param)
@exec
args : args
timeout : opts.timeout
cb : opts.cb
get_state: (opts) =>
opts = defaults opts,
cb : required
if @state?
if @state not in ['starting', 'stopping', 'restarting'] # stopped, running, saving, error
winston.debug("get_state -- confirming running status")
@_action
action : 'status'
param : '--running'
cb : (err, status) =>
winston.debug("get_state -- confirming based on status=#{misc.to_json(status)}")
if err
@state = 'error'
else if status.running
# set @state to a running state: either 'saving' or 'running'
if @state != 'saving'
@state = 'running'
else
@state = 'stopped'
opts.cb(undefined, @state)
else
winston.debug("get_state -- trusting running status since @state=#{@state}")
opts.cb(undefined, @state)
return
# We -- the server running on this compute node -- don't know the state of this project.
# This might happen if the server were restarted, the machine rebooted, the project not
# ever started, here, etc. So we run a script and try to guess a state.
@_action
action : 'status'
cb : (err, status) =>
@dbg("get_state",'',"basing on status=#{misc.to_json(status)}")
if err
@state = 'error'
else if status.running
@state = 'running'
else
@state = 'stopped'
opts.cb(undefined, @state)
projects = {}
get_project = (project_id) ->
if not projects[project_id]?
projects[project_id] = new Project(project_id: project_id)
return projects[project_id]
handle_mesg = (socket, mesg) ->
winston.debug("storage_server: handling '#{misc.to_safe_str(mesg)}'")
id = mesg.id
if mesg.event == 'storage'
if mesg.action == 'server_id'
mesg.server_id = SERVER_ID
socket.write_mesg('json', mesg)
else
t = misc.walltime()
if mesg.action == 'sync'
if not mesg.param?
mesg.param = []
project = get_project(mesg.project_id)
project.action
action : mesg.action
param : mesg.param
cb : (err, result) ->
if err
resp = message.error(error:err, id:id)
else
resp = message.success(id:id)
if result?
resp.result = result
resp.time_s = misc.walltime(t)
socket.write_mesg('json', resp)
else if mesg.event == 'projects_running_on_server'
projects_running_on_server (err, projects) ->
if err
socket.write_mesg('json', message.error(id:id, error:"error determining running projects -- #{err}"))
else
mesg.projects = projects
socket.write_mesg('json', mesg)
else
socket.write_mesg('json', message.error(id:id, error:"unknown event type: '#{mesg.event}'"))
up_since = undefined
init_up_since = (cb) ->
fs.readFile "/proc/uptime", (err, data) ->
if err
cb(err)
else
up_since = cassandra.seconds_ago(misc.split(data.toString())[0])
cb()
SERVER_ID = undefined
init_server_id = (cb) ->
file = program.server_id_file
fs.exists file, (exists) ->
if not exists
SERVER_ID = uuid.v4()
fs.writeFile file, SERVER_ID, (err) ->
if err
winston.debug("Error writing server_id file!")
cb(err)
else
winston.debug("Wrote new SERVER_ID =#{SERVER_ID}")
cb()
else
fs.readFile file, (err, data) ->
if err
cb(err)
else
SERVER_ID = data.toString()
cb()
projects_running_on_server = (cb) -> # cb(err, projects)
dbg = (m) -> winston.debug("projects_running_on_server: #{m}")
dbg()
uids = []
projects = []
async.series([
(cb) ->
dbg("get uids of active projects")
misc_node.execute_code
command : "ps -Ao uid| sort |uniq"
timeout : 30
bash : true
cb : (err, output) =>
if err
cb(err); return
v = output.stdout.split('\n')
dbg("got #{v.length} uids")
for uid in v
uid = parseInt(uid)
if uid > 65535
uids.push(uid)
cb()
(cb) ->
f = (uid, c) ->
misc_node.execute_code
command : "getent passwd '#{uid}' | cut -d: -f6"
timeout : 30
bash : true
cb : (err, output) =>
if err
dbg("WARNING: error getting username for uid #{uid} -- #{err}")
c()
else if output.stdout.indexOf('nobody') != -1
c()
else
dbg("#{uid} --> #{output.stdout}")
v = output.stdout.split('/')
project_id = v[v.length-1].trim()
if project_id.length == 36
projects.push(project_id)
c()
async.map(uids, f, cb)
], (err) =>
cb(err, projects)
)
idle_timeout = () ->
dbg = (m) -> winston.debug("idle_timeout: #{m}")
dbg('Periodic check for projects that are running and call "kill --only_if_idle" on them all.')
projects_running_on_server (err, projects) ->
if err
dbg("ERROR: #{err}")
else
f = (project_id, cb) ->
get_project(project_id).action
action : 'stop'
param : '--only_if_idle'
cb : (err) ->
if err
dbg("WARNING: error stopping #{project_id} -- #{err}")
cb()
async.map projects, f, (err) ->
dbg("finished checking for projects that need to be killed")
start_tcp_server = (cb) ->
winston.info("starting tcp server...")
setInterval(idle_timeout, IDLE_TIMEOUT_INTERVAL_S * 1000)
server = net.createServer (socket) ->
winston.debug("received connection")
socket.id = uuid.v4()
misc_node.unlock_socket socket, secret_token, (err) ->
if err
winston.debug("ERROR: unable to unlock socket -- #{err}")
else
winston.debug("unlocked connection")
misc_node.enable_mesg(socket)
socket.on 'mesg', (type, mesg) ->
if type == "json" # other types ignored -- we only deal with json
winston.debug("received mesg #{misc.to_safe_str(mesg)}")
try
handle_mesg(socket, mesg)
catch e
winston.debug(new Error().stack)
winston.error "ERROR: '#{e}' handling message '#{misc.to_safe_str(mesg)}'"
get_port = (c) ->
if program.port
c()
else
# attempt once to use the same port as in port file, if there is one
fs.exists program.portfile, (exists) ->
if not exists
program.port = 0
c()
else
fs.readFile program.portfile, (err, data) ->
if err
program.port = 0
c()
else
program.port = data.toString()
c()
listen = (c) ->
winston.debug("trying port #{program.port}")
server.listen program.port, program.address, (err) ->
if err
winston.debug("failed to listen to #{program.port} -- #{err}")
c(err)
else
program.port = server.address().port
fs.writeFile(program.portfile, program.port, cb)
winston.debug("listening on #{program.address}:#{program.port}")
c()
get_port () ->
listen (err) ->
if err
winston.debug("fail so let OS assign port...")
program.port = 0
listen()
secret_token = undefined
read_secret_token = (cb) ->
if secret_token?
cb()
return
winston.debug("read_secret_token")
async.series([
# Read or create the file; after this step the variable secret_token
# is set and the file exists.
(cb) ->
fs.exists program.secret_file, (exists) ->
if exists
winston.debug("read '#{program.secret_file}'")
fs.readFile program.secret_file, (err, buf) ->
secret_token = buf.toString().trim()
cb()
else
winston.debug("create '#{program.secret_file}'")
require('crypto').randomBytes 64, (ex, buf) ->
secret_token = buf.toString('base64')
fs.writeFile(program.secret_file, secret_token, cb)
# Ensure restrictive permissions on the secret token file.
(cb) ->
fs.chmod(program.secret_file, 0o600, cb)
], cb)
start_server = () ->
winston.debug("start_server")
async.series [init_server_id, init_up_since, read_secret_token, start_tcp_server], (err) ->
if err
winston.debug("Error starting server -- #{err}")
else
winston.debug("Successfully started server.")
###########################
## GlobalClient -- client for working with *all* storage/compute servers
###########################
###
# Adding new servers form the coffeescript command line and pushing out config files:
c=require('cassandra');x={};d=new c.Salvus(hosts:['10.1.11.2'], keyspace:'salvus', username:'salvus', password:fs.readFileSync('/home/salvus/salvus/salvus/data/secrets/cassandra/salvus').toString().trim(),consistency:1,cb:((e,d)->console.log(e);x.d=d))
require('bup_server').global_client(database:x.d, cb:(e,c)->x.e=e;x.c=c)
(x.c.register_server(host:"10.1.#{i}.5",dc:0,cb:console.log) for i in [10..21])
(x.c.register_server(host:"10.1.#{i}.5",dc:1,cb:console.log) for i in [1..7])
(x.c.register_server(host:"10.3.#{i}.4",dc:1,cb:console.log) for i in [1..8])
x.c.push_servers_files(cb:console.log)
###
# A project viewed globally (but from a particular hub)
class GlobalProject
constructor: (@project_id, @global_client) ->
@database = @global_client.database
get_location_pref: (cb) => # cb(err, server_id)
@database.select_one
table : "projects"
columns : ["bup_location"]
where : {project_id : @project_id}
cb : (err, result) =>
if err
cb(err)
else
cb(undefined, result[0])
set_location_pref: (server_id, cb) =>
@database.update
table : "projects"
set : {bup_location : server_id}
where : {project_id : @project_id}
cb : cb
# If the project is currently running, return its location *and* the datacenter
# of that location. If not running, return where it will next start.
get_running_location_and_dc: (opts) =>
opts = defaults opts,
cb: required #cb(err, {server_id:?, dc:?, running:?}) # running:true if project is running
dbg = (m) => winston.debug("GlobalProject.get_running_location_and_dc(#{@project_id}): #{m}")
server_id = undefined
dc = undefined
running = undefined
async.series([
(cb) =>
dbg("determine where this project is located")
@get_host_where_running
cb : (err, s) =>
dbg("project server_id = #{s}")
server_id = s
if err
cb(err)
else if not server_id?
dbg("not running anywhere")
@get_location_pref (err, s) =>
server_id = s
running = false
cb(err)
else
running = true
cb()
(cb) =>
dbg("get the data center of this project")
@global_client.get_data_center
server_id : server_id
cb : (err, x) =>
dc = x
dbg("data center = #{dc}")
cb(err)
], (err) =>
if err
opts.cb(err)
else
opts.cb(undefined, {server_id:server_id, dc:dc, running:running})
)
# starts project if necessary, waits until it is running, and
# gets the hostname port where the local hub is serving.
local_hub_address: (opts) =>
opts = defaults opts,
timeout : 30
cb : required # cb(err, {host:hostname, port:port, status:status, server_id:server_id})
if @_local_hub_address_queue?
@_local_hub_address_queue.push(opts.cb)
else
@_local_hub_address_queue = [opts.cb]
@_local_hub_address
timeout : opts.timeout
cb : (err, r) =>
for cb in @_local_hub_address_queue
cb(err, r)
delete @_local_hub_address_queue
_local_hub_address: (opts) =>
opts = defaults opts,
timeout : 90
cb : required # cb(err, {host:hostname, port:port, status:status, server_id:server_id})
dbg = (m) -> winston.info("local_hub_address(#{@project_id}): #{m}")
dbg()
server_id = undefined
port = undefined
status = undefined
attempt = (cb) =>
dbg("attempt")
async.series([
(cb) =>
dbg("see if host running")
@get_host_where_running
cb : (err, s) =>
port = undefined
server_id = s
cb(err)
(cb) =>
if not server_id?
dbg("not running anywhere, so try to start")
@start(cb:cb)
else
dbg("running or starting somewhere, so test it out")
@project
server_id : server_id
cb : (err, project) =>
if err
cb(err)
else
project.status
cb : (err, _status) =>
status = _status
port = status?['local_hub.port']
cb()
(cb) =>
if port?
dbg("success -- we got our host #{server_id} at port #{port}")
@_update_project_settings(cb)
else
dbg("fail -- not working yet")
cb(true)
], cb)
t = misc.walltime()
f = () =>
if misc.walltime() - t > opts.timeout
# give up
opts.cb("unable to start project running somewhere within about #{opts.timeout} seconds")
else
# try to open...
attempt (err) =>
if err
dbg("attempt to get address failed -- #{err}; try again in 5 seconds")
setTimeout(f, 5000)
else
# success!?
host = @global_client.servers.by_id[server_id]?.host
if not host?
opts.cb("unknown server #{server_id}")
else
opts.cb(undefined, {host:host, port:port, status:status, server_id:server_id})
f()
_update_project_settings: (cb) =>
dbg = (m) -> winston.debug("GlobalProject.update_project_settings(#{@project_id}): #{m}")
dbg()
@database.select_one
table : 'projects'
columns : ['settings']
where : {project_id: @project_id}
cb : (err, result) =>
dbg("got settings from database: #{misc.to_json(result[0])}")
if err or not result? or not result[0]? # result[0] = undefined if no special settings
cb?(err)
else
opts = result[0]
opts.cb = (err) =>
if err
dbg("set settings for project -- #{err}")
else
dbg("successful set settings")
cb?(err)
@settings(opts)
start: (opts) =>
opts = defaults opts,
target : undefined
cb : undefined
dbg = (m) -> winston.debug("GlobalProject.start(#{@project_id}): #{m}")
dbg()
state = undefined
project = undefined
server_id = undefined
target = opts.target
dbg("target = #{target}")
async.series([
(cb) =>
if target?
cb(); return
@get_location_pref (err, result) =>
if not err and result?
dbg("setting prefered start target to #{result[0]}")
target = result
cb()
else
cb(err)
(cb) =>
dbg("get global state of the project")
@get_state
cb : (err, s) =>
state = s; cb(err)
(cb) =>
running_on = (server_id for server_id, s of state when s in ['running', 'starting', 'restarting', 'saving'])
if running_on.length == 0
dbg("find a place to run project")
v = (server_id for server_id, s of state when s not in ['error'])
if v.length == 0
v = misc.keys(state)
if target? and target in v
dbg("use requested target = #{target}")
server_id = target
cb()
else
dbg("order good servers by most recent save time, and choose randomly from those")
@get_last_save
cb : (err, last_save) =>
if err
cb(err)
else
for server_id in v
if not last_save[server_id]?
last_save[server_id] = 0
w = []
for server_id, timestamp of last_save
if server_id not in v
delete last_save[server_id]
else
w.push(timestamp)
if w.length > 0
w.sort()
newest = w[w.length-1]
# we use date subtraction below because equality testing of dates does *NOT* work correctly
# for our purposes, maybe due to slight rounding errors and milliseconds. And strategically
# it also makes sense to lump 2 projects with a save within a few seconds in our random choice.
v = (server_id for server_id in v when Math.abs(last_save[server_id] - newest) < 10*1000)
dbg("choosing randomly from #{v.length} choices with optimal save time")
server_id = misc.random_choice(v)
if not server_id?
e = "no host available on which to open project"
dbg(e)
cb(e)
else
dbg("our choice is #{server_id}")
cb()
else if running_on.length == 1
dbg("done -- nothing further to do -- project already running on one host: #{misc.to_json(running_on)}")
server_id = undefined
cb()
else
dbg("project running on more than one host -- repair by killing all but first; this will force any clients to move to the correct host when their connections get dropped")
running_on.sort() # sort so any client doing the same thing will kill the same other ones.
@_stop_all(running_on.slice(1))
cb()
(cb) =>
if not server_id? # already running
cb(); return
dbg("got project on #{server_id} so we can start it there")
@project
server_id : server_id
cb : (err, p) =>
project = p; cb (err)
(cb) =>
if not server_id? # already running
cb(); return
dbg("get current non-default settings from the database and set before starting project")
@get_settings
cb : (err, settings) =>
if err
cb(err)
else
settings.cb = cb
project.settings(settings)
(cb) =>
if not server_id? # already running
cb(); return
dbg("start project on #{server_id}")
project.start
cb : (err) =>
if not err
dbg("success -- record that #{server_id} is now our preferred start location")
@set_location_pref(server_id)
cb(err)
], (err) => opts.cb?(err))
restart: (opts) =>
dbg = (m) => winston.debug("GlobalProject.restart(#{@project_id}): #{m}")
dbg()
@running_project
cb : (err, project) =>
if err
dbg("unable to determine running project -- #{err}")
opts.cb(err)
else if project?
dbg("project is running somewhere, so restart it there")
project.restart(opts)
else
dbg("project not running anywhere, so start it somewhere")
@start(opts)
sync_topology: (opts) =>
opts = defaults opts,
cb : required # (err, {host:{dc:n, server_id:server_id, running:true or false}, targets:{'ip_address:port':target_id, ...}})
dbg = (m) => winston.debug("GlobalProject.sync_topology(): #{m}")
resp = {host:{}, targets:{}}
async.series([
(cb) =>
dbg("get host, data center, and if project is running")
@get_running_location_and_dc
cb : (err, x) =>
if err
cb(err)
else
resp.host = x
cb()
(cb) =>
dbg("get the targets for replication")
@get_hosts
cb : (err, t) =>
v = (x for x in t when x != resp.host.server_id)
dbg("sync_targets = #{misc.to_json(v)}")
f = (target_id, cb) =>
@global_client.get_external_ssh
server_id : target_id
dc : resp.host.dc
cb : (err, addr) =>
if err
cb(err)
else
resp.targets[addr] = target_id
cb()
async.map v, f, (err) =>
dbg("sync_targets --> #{misc.to_json(resp.targets)}")
cb(err)
], (err) =>
if err
opts.cb(err)
else
opts.cb(undefined, resp)
)
# Determine the hostname:port to use when making an ssh connection from the
# machine currently hosting this project to some other machine (given by its server_id).
# (similar to sync_topology above)
# **NOT DONE**
ssh_address: (opts) =>
opts = defaults opts,
server_id : required # target machine's id
cb : required # (err, {address:?, port:?})
dbg = (m) => winston.debug("GlobalProject.ssh_address(#{opts.server_id}): #{m}")
host_server_id = undefined
async.series([
(cb) =>
])
save: (opts) =>
opts = defaults opts,
cb : undefined
dbg = (m) => winston.debug("GlobalProject.save(#{@project_id}): #{m}")
# if we just saved this project, return immediately -- note: THIS IS "CLIENT" side, but there is a similar guard on the actual compute node
if @_last_save? and misc.walltime() - @_last_save < MIN_SAVE_INTERVAL_S
dbg("we just saved this project recently")
opts.cb?(undefined)
return
# put this here -- we don't even want to *try* more frequently than MIN_SAVE_INTERVAL_S, in case of save bup repo being broken (?)
@_last_save = misc.walltime()
need_to_save = false
project = undefined
server_id = undefined
targets = undefined
errors = []
async.series([
(cb) =>
dbg("figure out where/if project is running")
@sync_topology
cb : (err, resp) =>
if err
cb(err); return
server_id = resp.host.server_id
if @state?[server_id] == 'saving'
dbg("already saving -- nothing to do")
cb()
else
need_to_save = true
targets = resp.targets
cb()
(cb) =>
if not need_to_save
cb(); return
dbg("get the project")
@project
server_id : server_id
cb : (err, p) =>
project = p; cb(err)
(cb) =>
if not need_to_save
cb(); return
dbg("save the project and sync")
project.save
targets : misc.keys(targets)
cb : (err, result) =>
r = result?.result
dbg("RESULT = #{misc.to_json(result)}")
if not err and r? and r.timestamp? and r.files_saved > 0
dbg("record info about saving #{r.files_saved} files in database")
last_save = {}
last_save[server_id] = new Date(r.timestamp*1000)
if r.sync?
for x in r.sync
if x.host == '' # special case - the server hosting the project
s = server_id