forked from ahellander/molns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
molns.py
executable file
·1515 lines (1412 loc) · 68.8 KB
/
molns.py
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
#!/usr/bin/env python
import os
import re
import sys
from MolnsLib.molns_datastore import Datastore, DatastoreException, VALID_PROVIDER_TYPES, get_provider_handle
from MolnsLib.molns_provider import ProviderException
from collections import OrderedDict
import subprocess
from MolnsLib.ssh_deploy import SSHDeploy
import multiprocessing
import json
import logging
logger = logging.getLogger()
#logger.setLevel(logging.INFO) #for Debugging
logger.setLevel(logging.CRITICAL)
###############################################
class MOLNSException(Exception):
pass
###############################################
class MOLNSConfig(Datastore):
def __init__(self, config_dir=None, db_file=None):
Datastore.__init__(self,config_dir=config_dir, db_file=db_file)
def __str__(self):
return "MOLNSConfig(config_dir={0})".format(self.config_dir)
###############################################
class MOLNSbase():
@classmethod
def merge_config(self, obj, config):
for key, conf, value in obj.get_config_vars():
if key not in config:
if value is not None:
myval = value
else:
if 'default' in conf and conf['default']:
if callable(conf['default']):
f1 = conf['default']
try:
myval = f1(obj)
except TypeError:
myval = None
else:
myval = conf['default']
else:
myval = None
obj.config[key] = myval
else:
obj.config[key] = config[key]
@classmethod
def _get_workerobj(cls, args, config):
# Name
worker_obj = None
if len(args) > 0:
worker_name = args[0]
# Get worker db object
try:
worker_obj = config.get_object(name=worker_name, kind='WorkerGroup')
except DatastoreException:
worker_obj = None
#logging.debug("controller_obj {0}".format(controller_obj))
if worker_obj is None:
print "worker group '{0}' is not initialized, use 'molns worker setup {0}' to initialize the controller.".format(worker_name)
else:
print "No worker name specified, please specify a name"
return worker_obj
@classmethod
def _get_controllerobj(cls, args, config):
# Name
if len(args) > 0:
controller_name = args[0]
else:
raise MOLNSException("No controller name given")
# Get controller db object
try:
controller_obj = config.get_object(name=controller_name, kind='Controller')
except DatastoreException:
controller_obj = None
#logging.debug("controller_obj {0}".format(controller_obj))
if controller_obj is None:
raise MOLNSException("controller '{0}' is not initialized, use 'molns controller setup {0}' to initialize the controller.".format(controller_name))
return controller_obj
class MOLNSController(MOLNSbase):
@classmethod
def controller_export(cls, args, config):
""" Export the configuration of a controller. """
if len(args) < 1:
raise MOLNSException("USAGE: molns controller export name [Filename]\n"\
"\tExport the data from the controller with the given name.")
controller_name = args[0]
if len(args) > 1:
filename = args[1]
else:
filename = 'Molns-Export-Controller-' + controller_name + '.json'
# check if provider exists
try:
controller_obj = config.get_object(controller_name, kind='Controller')
except DatastoreException as e:
raise MOLNSException("provider not found")
data = {'name': controller_obj.name,
'provider_name': controller_obj.provider.name,
'config': controller_obj.config}
return {'data': json.dumps(data),
'type': 'file',
'filename': filename}
@classmethod
def controller_import(cls, args, config, json_data=None):
""" Import the configuration of a controller. """
if json_data is None:
if len(args) < 1:
raise MOLNSException("USAGE: molns controller import [Filename.json]\n"\
"\Import the data from the controller with the given name.")
filename = args[0]
with open(filename) as fd:
data = json.load(fd)
else:
data = json_data
controller_name = data['name']
msg = ''
try:
provider_obj = config.get_object(data['provider_name'], kind='Provider')
except DatastoreException as e:
raise MOLNSException("unknown provider '{0}'".format(data['provider_name']))
try:
controller_obj = config.get_object(controller_name, kind='Controller')
msg += "Found existing controller\n"
if controller_obj.provider.name != provider_obj.name:
raise MOLNSException("Import data has provider '{0}'. Controller {1} exists with provider {2}. provider conversion is not possible.".format(data['provider_name'], controller_obj.name, controller_obj.provider.name))
except DatastoreException as e:
controller_obj = config.create_object(ptype=provider_obj.type, name=controller_name, kind='Controller', provider_id=provider_obj.id)
msg += "Creating new controller\n"
cls.merge_config(controller_obj, data['config'])
config.save_object(controller_obj, kind='Controller')
msg += "Controller data imported\n"
return {'msg':msg}
@classmethod
def controller_get_config(cls, name=None, provider_type=None, config=None):
""" Return a list of dict of config var for the controller config.
Each dict in the list has the keys: 'key', 'value', 'type'
Either 'name' or 'provider_type' must be specified.
If 'name' is specified, then it will retreive the value from that
config and return it in 'value' (or return the string '********'
if that config is obfuscated, such passwords).
"""
if config is None:
raise MOLNSException("no config specified")
if name is None and provider_type is None:
raise MOLNSException("Controller name or provider type must be specified")
obj = None
if obj is None and name is not None:
try:
obj = config.get_object(name, kind='Controller')
except DatastoreException as e:
pass
if obj is None and provider_type is not None:
if provider_type not in VALID_PROVIDER_TYPES:
raise MOLNSException("Unknown provider type '{0}'".format(provider_type))
p_hand = get_provider_handle('Controller',provider_type)
obj = p_hand('__tmp__',data={},config_dir=config.config_dir)
if obj is None:
raise MOLNSException("Controller {0} not found".format(name))
ret = []
for key, conf, value in obj.get_config_vars():
if 'ask' in conf and not conf['ask']:
continue
question = conf['q']
if value is not None:
myval = value
else:
if 'default' in conf and conf['default']:
if callable(conf['default']):
f1 = conf['default']
try:
myval = f1()
except TypeError:
pass
else:
myval = conf['default']
else:
myval = None
if myval is not None and 'obfuscate' in conf and conf['obfuscate']:
myval = '********'
ret.append({
'question':question,
'key':key,
'value': myval,
'type':'string'
})
return ret
@classmethod
def setup_controller(cls, args, config):
"""Setup a controller. Set the provider configuration for the head node. Use 'worker setup' to set the configuration for worker nodes
"""
logging.debug("MOLNSController.setup_controller(config={0})".format(config))
# name
if len(args) > 0:
controller_name = args[0]
else:
print "Usage: molns.py controller setup NAME"
return
try:
controller_obj = config.get_object(args[0], kind='Controller')
except DatastoreException as e:
# provider
providers = config.list_objects(kind='Provider')
if len(providers)==0:
print "No providers configured, please configure one ('molns provider setup') before initializing controller."
return
print "Select a provider:"
for n,p in enumerate(providers):
print "\t[{0}] {1}".format(n,p.name)
provider_ndx = int(raw_input_default("enter the number of provider:", default='0'))
provider_id = providers[provider_ndx].id
provider_obj = config.get_object(name=providers[provider_ndx].name, kind='Provider')
logging.debug("using provider {0}".format(provider_obj))
# create object
try:
controller_obj = config.create_object(ptype=provider_obj.type, name=controller_name, kind='Controller', provider_id=provider_id)
except DatastoreException as e:
print e
return
setup_object(controller_obj)
config.save_object(controller_obj, kind='Controller')
@classmethod
def list_controller(cls, args, config):
""" List all the currently configured controllers."""
controllers = config.list_objects(kind='Controller')
if len(controllers) == 0:
return {'msg':"No controllers configured"}
else:
table_data = []
for c in controllers:
try:
p = config.get_object_by_id(c.provider_id, 'Provider')
provider_name = p.name
except DatastoreException as e:
provider_name = 'ERROR: {0}'.format(e)
table_data.append([c.name, provider_name])
return {'type':'table','column_names':['name', 'provider'], 'data':table_data}
@classmethod
def show_controller(cls, args, config):
""" Show all the details of a controller config. """
if len(args) == 0:
raise MOLNSException("USAGE: molns controller show name")
return {'msg':str(config.get_object(name=args[0], kind='Controller'))}
@classmethod
def delete_controller(cls, args, config):
""" Delete a controller config. """
#print "MOLNSProvider.delete_provider(args={0}, config={1})".format(args, config)
if len(args) == 0:
raise MOLNSException("USAGE: molns cluser delete name")
config.delete_object(name=args[0], kind='Controller')
@classmethod
def ssh_controller(cls, args, config):
""" SSH into the controller. """
logging.debug("MOLNSController.ssh_controller(args={0})".format(args))
controller_obj = cls._get_controllerobj(args, config)
if controller_obj is None: return
# Check if any instances are assigned to this controller
instance_list = config.get_controller_instances(controller_id=controller_obj.id)
#logging.debug("instance_list={0}".format(instance_list))
# Check if they are running
ip = None
if len(instance_list) > 0:
for i in instance_list:
status = controller_obj.get_instance_status(i)
logging.debug("instance={0} has status={1}".format(i, status))
if status == controller_obj.STATUS_RUNNING:
ip = i.ip_address
if ip is None:
print "No active instance for this controller"
return
#print " ".join(['/usr/bin/ssh','-oStrictHostKeyChecking=no','-oUserKnownHostsFile=/dev/null','-i',controller_obj.provider.sshkeyfilename(),'ubuntu@{0}'.format(ip)])
#os.execl('/usr/bin/ssh','-oStrictHostKeyChecking=no','-oUserKnownHostsFile=/dev/null','-i',controller_obj.provider.sshkeyfilename(),'ubuntu@{0}'.format(ip))
cmd = ['/usr/bin/ssh','-oStrictHostKeyChecking=no','-oUserKnownHostsFile=/dev/null','-i',controller_obj.provider.sshkeyfilename(),'ubuntu@{0}'.format(ip)]
print " ".join(cmd)
subprocess.call(cmd)
print "SSH process completed"
@classmethod
def upload_controller(cls, args, config):
""" Copy a local file to the controller's home directory. """
logging.debug("MOLNSController.upload_controller(args={0})".format(args))
controller_obj = cls._get_controllerobj(args, config)
if controller_obj is None: return
# Check if any instances are assigned to this controller
instance_list = config.get_controller_instances(controller_id=controller_obj.id)
#logging.debug("instance_list={0}".format(instance_list))
# Check if they are running
ip = None
if len(instance_list) > 0:
for i in instance_list:
status = controller_obj.get_instance_status(i)
logging.debug("instance={0} has status={1}".format(i, status))
if status == controller_obj.STATUS_RUNNING:
ip = i.ip_address
if ip is None:
print "No active instance for this controller"
return
#print " ".join(['/usr/bin/ssh','-oStrictHostKeyChecking=no','-oUserKnownHostsFile=/dev/null','-i',controller_obj.provider.sshkeyfilename(),'ubuntu@{0}'.format(ip)])
#os.execl('/usr/bin/ssh','-oStrictHostKeyChecking=no','-oUserKnownHostsFile=/dev/null','-i',controller_obj.provider.sshkeyfilename(),'ubuntu@{0}'.format(ip))
cmd = ['/usr/bin/scp','-r','-oStrictHostKeyChecking=no','-oUserKnownHostsFile=/dev/null','-i',controller_obj.provider.sshkeyfilename(), args[1], 'ubuntu@{0}:/home/ubuntu/'.format(ip)]
print " ".join(cmd)
subprocess.call(cmd)
print "SCP process completed"
@classmethod
def put_controller(cls, args, config):
""" Copy a local file to the controller's shared area. """
logging.debug("MOLNSController.put_controller(args={0})".format(args))
controller_obj = cls._get_controllerobj(args, config)
if controller_obj is None: return
# Check if any instances are assigned to this controller
instance_list = config.get_controller_instances(controller_id=controller_obj.id)
#logging.debug("instance_list={0}".format(instance_list))
# Check if they are running
ip = None
if len(instance_list) > 0:
for i in instance_list:
status = controller_obj.get_instance_status(i)
logging.debug("instance={0} has status={1}".format(i, status))
if status == controller_obj.STATUS_RUNNING:
ip = i.ip_address
if ip is None:
print "No active instance for this controller"
return
#print " ".join(['/usr/bin/ssh','-oStrictHostKeyChecking=no','-oUserKnownHostsFile=/dev/null','-i',controller_obj.provider.sshkeyfilename(),'ubuntu@{0}'.format(ip)])
#os.execl('/usr/bin/ssh','-oStrictHostKeyChecking=no','-oUserKnownHostsFile=/dev/null','-i',controller_obj.provider.sshkeyfilename(),'ubuntu@{0}'.format(ip))
cmd = ['/usr/bin/scp','-oStrictHostKeyChecking=no','-oUserKnownHostsFile=/dev/null','-i',controller_obj.provider.sshkeyfilename(), args[1], 'ubuntu@{0}:/home/ubuntu/shared'.format(ip)]
print " ".join(cmd)
subprocess.call(cmd)
print "SSH process completed"
@classmethod
def status_controller(cls, args, config):
""" Get status of the head node of a MOLNs controller. """
logging.debug("MOLNSController.status_controller(args={0})".format(args))
if len(args) > 0:
controller_obj = cls._get_controllerobj(args, config)
if controller_obj is None: return
# Check if any instances are assigned to this controller
instance_list = config.get_controller_instances(controller_id=controller_obj.id)
table_data = []
if len(instance_list) > 0:
for i in instance_list:
#provider_name = config.get_object_by_id(i.provider_id, 'Provider').name
try:
p = config.get_object_by_id(i.provider_id, 'Provider')
provider_name = p.name
except DatastoreException as e:
provider_name = 'ERROR: {0}'.format(e)
controller_name = config.get_object_by_id(i.controller_id, 'Controller').name
status = controller_obj.get_instance_status(i)
table_data.append([controller_name, status, 'controller', provider_name, i.provider_instance_identifier, i.ip_address])
else:
return {'msg': "No instance running for this controller"}
# Check if any worker instances are assigned to this controller
instance_list = config.get_worker_instances(controller_id=controller_obj.id)
if len(instance_list) > 0:
for i in instance_list:
worker_name = config.get_object_by_id(i.worker_group_id, 'WorkerGroup').name
worker_obj = cls._get_workerobj([worker_name], config)
#provider_name = config.get_object_by_id(i.provider_id, 'Provider').name
try:
p = config.get_object_by_id(i.provider_id, 'Provider')
provider_name = p.name
except DatastoreException as e:
provider_name = 'ERROR: {0}'.format(e)
status = worker_obj.get_instance_status(i)
table_data.append([worker_name, status, 'worker', provider_name, i.provider_instance_identifier, i.ip_address])
#table_print(['name','status','type','provider','instance id', 'IP address'],table_data)
r = {'type':'table', 'column_names':['name','status','type','provider','instance id', 'IP address'], 'data':table_data}
return r
else:
instance_list = config.get_all_instances()
if len(instance_list) > 0:
table_data = []
for i in instance_list:
provider_name = config.get_object_by_id(i.provider_id, 'Provider').name
controller_name = config.get_object_by_id(i.controller_id, 'Controller').name
if i.worker_group_id is not None:
worker_name = config.get_object_by_id(i.worker_group_id, 'WorkerGroup').name
table_data.append([worker_name, 'worker', provider_name, i.provider_instance_identifier])
else:
table_data.append([controller_name, 'controller', provider_name, i.provider_instance_identifier])
r = {'type':'table', 'column_names':['name','type','provider','instance id'], 'data':table_data}
r['msg']= "\n\tUse 'molns status NAME' to see current status of each instance."
return r
else:
return {'msg': "No instance found"}
@classmethod
def start_controller(cls, args, config, password=None):
""" Start the MOLNs controller. """
logging.debug("MOLNSController.start_controller(args={0})".format(args))
controller_obj = cls._get_controllerobj(args, config)
if controller_obj is None: return
# Check if any instances are assigned to this controller
instance_list = config.get_all_instances(controller_id=controller_obj.id)
# Check if they are running or stopped (if so, resume them)
inst = None
if len(instance_list) > 0:
for i in instance_list:
status = controller_obj.get_instance_status(i)
if status == controller_obj.STATUS_RUNNING:
print "controller already running at {0}".format(i.ip_address)
return
elif status == controller_obj.STATUS_STOPPED:
print "Resuming instance at {0}".format(i.ip_address)
controller_obj.resume_instance(i)
inst = i
break
if inst is None:
# Start a new instance
print "Starting new controller"
inst = controller_obj.start_instance()
# deploying
sshdeploy = SSHDeploy(config=controller_obj.provider, config_dir=config.config_dir)
sshdeploy.deploy_ipython_controller(inst.ip_address, notebook_password=password)
sshdeploy.deploy_molns_webserver(inst.ip_address)
#sshdeploy.deploy_stochss(inst.ip_address, port=443)
@classmethod
def stop_controller(cls, args, config):
""" Stop the head node of a MOLNs controller. """
logging.debug("MOLNSController.stop_controller(args={0})".format(args))
controller_obj = cls._get_controllerobj(args, config)
if controller_obj is None: return
# Check if any instances are assigned to this controller
instance_list = config.get_all_instances(controller_id=controller_obj.id)
# Check if they are running
if len(instance_list) > 0:
for i in instance_list:
if i.worker_group_id is None:
status = controller_obj.get_instance_status(i)
if status == controller_obj.STATUS_RUNNING:
print "Stopping controller running at {0}".format(i.ip_address)
controller_obj.stop_instance(i)
else:
worker_name = config.get_object_by_id(i.worker_group_id, 'WorkerGroup').name
worker_obj = cls._get_workerobj([worker_name], config)
status = worker_obj.get_instance_status(i)
if status == worker_obj.STATUS_RUNNING or status == worker_obj.STATUS_STOPPED:
print "Terminating worker '{1}' running at {0}".format(i.ip_address, worker_name)
worker_obj.terminate_instance(i)
else:
print "No instance running for this controller"
@classmethod
def terminate_controller(cls, args, config):
""" Terminate the head node of a MOLNs controller. """
logging.debug("MOLNSController.terminate_controller(args={0})".format(args))
controller_obj = cls._get_controllerobj(args, config)
if controller_obj is None: return
instance_list = config.get_all_instances(controller_id=controller_obj.id)
logging.debug("\tinstance_list={0}".format([str(i) for i in instance_list]))
# Check if they are running or stopped
if len(instance_list) > 0:
for i in instance_list:
if i.worker_group_id is None:
status = controller_obj.get_instance_status(i)
if status == controller_obj.STATUS_RUNNING or status == controller_obj.STATUS_STOPPED:
print "Terminating controller running at {0}".format(i.ip_address)
controller_obj.terminate_instance(i)
else:
worker_name = config.get_object_by_id(i.worker_group_id, 'WorkerGroup').name
worker_obj = cls._get_workerobj([worker_name], config)
status = worker_obj.get_instance_status(i)
if status == worker_obj.STATUS_RUNNING or status == worker_obj.STATUS_STOPPED:
print "Terminating worker '{1}' running at {0}".format(i.ip_address, worker_name)
worker_obj.terminate_instance(i)
else:
print "No instance running for this controller"
@classmethod
def connect_controller_to_local(cls, args, config):
""" Connect a local iPython installation to the controller. """
logging.debug("MOLNSController.connect_controller_to_local(args={0})".format(args))
if len(args) != 2:
print "USAGE: molns local-connect controller_name profile_name"
return
controller_name = args[1]
profile_name = args[1]
logging.debug("connecting controller {0} to local ipython profile {1}".format(controller_name, profile_name))
controller_obj = cls._get_controllerobj(args, config)
if controller_obj is None: return
# Check if any instances are assigned to this controller
instance_list = config.get_all_instances(controller_id=controller_obj.id)
# Check if they are running
inst = None
if len(instance_list) > 0:
for i in instance_list:
status = controller_obj.get_instance_status(i)
if status == controller_obj.STATUS_RUNNING:
print "Connecting to controller at {0}".format(i.ip_address)
inst = i
break
if inst is None:
print "No instance running for this controller"
return
# deploying
sshdeploy = SSHDeploy(config=controller_obj.provider, config_dir=config.config_dir)
client_file_data = sshdeploy.get_ipython_client_file(inst.ip_address)
home_dir = os.environ.get('HOME')
ipython_client_filename = os.path.join(home_dir, '.ipython/profile_{0}/'.format(profile_name), 'security/ipcontroller-client.json')
logging.debug("Writing file {0}".format(ipython_client_filename))
with open(ipython_client_filename, 'w') as fd:
fd.write(client_file_data)
print "Success"
###############################################
class MOLNSWorkerGroup(MOLNSbase):
@classmethod
def worker_group_export(cls, args, config):
""" Export the configuration of a worker group. """
if len(args) < 1:
raise MOLNSException("USAGE: molns worker export name [Filename]\n"\
"\tExport the data from the worker group with the given name.")
worker_name = args[0]
if len(args) > 1:
filename = args[1]
else:
filename = 'Molns-Export-Worker-' + worker_name + '.json'
# check if provider exists
try:
worker_obj = config.get_object(worker_name, kind='WorkerGroup')
except DatastoreException as e:
raise MOLNSException("worker group not found")
data = {'name': worker_obj.name,
'provider_name': worker_obj.provider.name,
'controller_name': worker_obj.controller.name,
'config': worker_obj.config}
return {'data': json.dumps(data),
'type': 'file',
'filename': filename}
@classmethod
def worker_group_import(cls, args, config, json_data=None):
""" Import the configuration of a worker group. """
if json_data is None:
if len(args) < 1:
raise MOLNSException("USAGE: molns worker import [Filename.json]\n"\
"\Import the data from the worker with the given name.")
filename = args[0]
with open(filename) as fd:
data = json.load(fd)
else:
data = json_data
worker_name = data['name']
msg = ''
try:
provider_obj = config.get_object(data['provider_name'], kind='Provider')
except DatastoreException as e:
raise MOLNSException("unknown provider '{0}'".format(data['provider_name']))
try:
controller_obj = config.get_object(data['controller_name'], kind='Controller')
except DatastoreException as e:
raise MOLNSException("unknown controller '{0}'".format(data['provider_name']))
try:
worker_obj = config.get_object(worker_name, kind='WorkerGroup')
msg += "Found existing worker group\n"
if worker_obj.provider.name != provider_obj.name:
raise MOLNSException("Import data has provider '{0}'. Worker group {1} exists with provider {2}. provider conversion is not possible.".format(data['provider_name'], worker_obj.name, worker_obj.provider.name))
if worker_obj.controller.name != controller_obj.name:
raise MOLNSException("Import data has controller '{0}'. Worker group {1} exists with controller {2}. provider conversion is not possible.".format(data['controller_name'], worker_obj.name, worker_obj.controller.name))
except DatastoreException as e:
worker_obj = config.create_object(ptype=provider_obj.type, name=worker_name, kind='WorkerGroup', provider_id=provider_obj.id, controller_id=controller_obj.id)
msg += "Creating new worker group\n"
cls.merge_config(worker_obj, data['config'])
config.save_object(worker_obj, kind='WorkerGroup')
msg += "Worker group data imported\n"
return {'msg':msg}
@classmethod
def worker_group_get_config(cls, name=None, provider_type=None, config=None):
""" Return a list of dict of config var for the worker group config.
Each dict in the list has the keys: 'key', 'value', 'type'
Either 'name' or 'provider_type' must be specified.
If 'name' is specified, then it will retreive the value from that
config and return it in 'value' (or return the string '********'
if that config is obfuscated, such passwords).
"""
if config is None:
raise MOLNSException("no config specified")
if name is None and provider_type is None:
raise MOLNSException("'name' or 'provider_type' must be specified.")
obj = None
if obj is None and name is not None:
try:
obj = config.get_object(name, kind='WorkerGroup')
except DatastoreException as e:
pass
if obj is None and provider_type is not None:
if provider_type not in VALID_PROVIDER_TYPES:
raise MOLNSException("Unknown provider type '{0}'".format(provider_type))
p_hand = get_provider_handle('WorkerGroup',provider_type)
obj = p_hand('__tmp__',data={},config_dir=config.config_dir)
if obj is None:
raise MOLNSException("Worker group {0} not found".format(name))
ret = []
for key, conf, value in obj.get_config_vars():
if 'ask' in conf and not conf['ask']:
continue
question = conf['q']
if value is not None:
myval = value
else:
if 'default' in conf and conf['default']:
if callable(conf['default']):
f1 = conf['default']
try:
myval = f1()
except TypeError:
pass
else:
myval = conf['default']
else:
myval = None
if myval is not None and 'obfuscate' in conf and conf['obfuscate']:
myval = '********'
ret.append({
'question':question,
'key':key,
'value': myval,
'type':'string'
})
return ret
@classmethod
def setup_worker_groups(cls, args, config):
""" Configure a worker group. """
logging.debug("MOLNSWorkerGroup.setup_worker_groups(config={0})".format(config))
# name
if len(args) == 0:
print "USAGE: molns worker setup name"
return
group_name = args[0]
try:
worker_obj = config.get_object(args[0], kind='WorkerGroup')
except DatastoreException as e:
# provider
providers = config.list_objects(kind='Provider')
if len(providers)==0:
print "No providers configured, please configure one ('molns provider setup') before initializing worker group."
return
print "Select a provider:"
for n,p in enumerate(providers):
print "\t[{0}] {1}".format(n,p.name)
provider_ndx = int(raw_input_default("enter the number of provider:", default='0'))
provider_id = providers[provider_ndx].id
provider_obj = config.get_object(name=providers[provider_ndx].name, kind='Provider')
logging.debug("using provider {0}".format(provider_obj))
# controller
controllers = config.list_objects(kind='Controller')
if len(controllers)==0:
print "No controllers configured, please configure one ('molns controller setup') before initializing worker group."
return
print "Select a controller:"
for n,p in enumerate(controllers):
print "\t[{0}] {1}".format(n,p.name)
controller_ndx = int(raw_input_default("enter the number of controller:", default='0'))
controller_id = controllers[controller_ndx].id
controller_obj = config.get_object(name=controllers[controller_ndx].name, kind='Controller')
logging.debug("using controller {0}".format(controller_obj))
# create object
try:
worker_obj = config.create_object(ptype=provider_obj.type, name=group_name, kind='WorkerGroup', provider_id=provider_id, controller_id=controller_obj.id)
except DatastoreException as e:
print e
return
setup_object(worker_obj)
config.save_object(worker_obj, kind='WorkerGroup')
@classmethod
def list_worker_groups(cls, args, config):
""" List all the currently configured worker groups."""
groups = config.list_objects(kind='WorkerGroup')
if len(groups) == 0:
raise MOLNSException("No worker groups configured")
else:
table_data = []
for g in groups:
#provider_name = config.get_object_by_id(g.provider_id, 'Provider').name
try:
p = config.get_object_by_id(g.provider_id, 'Provider')
provider_name = p.name
except DatastoreException as e:
provider_name = 'ERROR: {0}'.format(e)
try:
c = config.get_object_by_id(g.controller_id, 'Controller')
controller_name = c.name
except DatastoreException as e:
controller_name = 'ERROR: {0}'.format(e)
table_data.append([g.name, provider_name, controller_name])
return {'type':'table','column_names':['name', 'provider', 'controller'], 'data':table_data}
@classmethod
def show_worker_groups(cls, args, config):
""" Show all the details of a worker group config. """
if len(args) == 0:
raise MOLNSException("USAGE: molns worker show name")
return
return {'msg': str(config.get_object(name=args[0], kind='WorkerGroup'))}
@classmethod
def delete_worker_groups(cls, args, config):
""" Delete a worker group config. """
if len(args) == 0:
raise MOLNSException("USAGE: molns worker delete name")
return
config.delete_object(name=args[0], kind='WorkerGroup')
@classmethod
def status_worker_groups(cls, args, config):
""" Get status of the workers of a MOLNs cluster. """
logging.debug("MOLNSWorkerGroup.status_worker_groups(args={0})".format(args))
if len(args) > 0:
worker_obj = cls._get_workerobj(args, config)
if worker_obj is None: return
# Check if any instances are assigned to this worker
instance_list = config.get_all_instances(worker_group_id=worker_obj.id)
# Check if they are running or stopped
if len(instance_list) > 0:
table_data = []
for i in instance_list:
status = worker_obj.get_instance_status(i)
#print "{0} type={3} ip={1} id={2}".format(status, i.ip_address, i.provider_instance_identifier, worker_obj.PROVIDER_TYPE)
worker_name = config.get_object_by_id(i.worker_group_id, 'WorkerGroup').name
provider_name = config.get_object_by_id(i.provider_id, 'Provider').name
status = worker_obj.get_instance_status(i)
table_data.append([worker_name, status, 'worker', provider_name, i.provider_instance_identifier, i.ip_address])
return {'type':'table','column_names':['name','status','type','provider','instance id', 'IP address'],'data':table_data}
else:
return {'msg': "No worker instances running for this cluster"}
else:
raise MOLNSException("USAGE: molns worker status NAME")
@classmethod
def start_worker_groups(cls, args, config):
""" Start workers of a MOLNs cluster. """
logging.debug("MOLNSWorkerGroup.start_worker_groups(args={0})".format(args))
worker_obj = cls._get_workerobj(args, config)
if worker_obj is None: return
num_vms = worker_obj['num_vms']
num_vms_to_start = int(num_vms)
controller_ip = cls.__launch_workers__get_controller(worker_obj, config)
if controller_ip is None: return
#logging.debug("\tcontroller_ip={0}".format(controller_ip))
try:
inst_to_deploy = cls.__launch_worker__start_or_resume_vms(worker_obj, config, num_vms_to_start)
#logging.debug("\tinst_to_deploy={0}".format(inst_to_deploy))
cls.__launch_worker__deploy_engines(worker_obj, controller_ip, inst_to_deploy, config)
except ProviderException as e:
print "Could not start workers: {0}".format(e)
@classmethod
def add_worker_groups(cls, args, config):
""" Add workers of a MOLNs cluster. """
logging.debug("MOLNSWorkerGroup.add_worker_groups(args={0})".format(args))
if len(args) < 2:
print "Usage: molns worker add GROUP num"
return
try:
num_vms_to_start = int(args[1])
except ValueError:
print "'{0}' in not a valid number of engines.".format(args[1])
return
worker_obj = cls._get_workerobj(args, config)
if worker_obj is None: return
controller_ip = cls.__launch_workers__get_controller(worker_obj, config)
if controller_ip is None: return
try:
inst_to_deploy = cls.__launch_worker__start_vms(worker_obj, num_vms_to_start)
cls.__launch_worker__deploy_engines(worker_obj, controller_ip, inst_to_deploy, config)
except ProviderException as e:
print "Could not start workers: {0}".format(e)
@classmethod
def __launch_workers__get_controller(cls, worker_obj, config):
# Check if a controller is running
controller_ip = None
instance_list = config.get_all_instances(controller_id=worker_obj.controller.id)
provider_obj = worker_obj.controller
# Check if they are running or stopped (if so, resume them)
if len(instance_list) > 0:
for i in instance_list:
status = provider_obj.get_instance_status(i)
logging.debug("instance {0} has status {1}".format(i.id, status))
if status == provider_obj.STATUS_RUNNING or status == provider_obj.STATUS_STOPPED:
controller_ip = i.ip_address
print "Controller running at {0}".format(controller_ip)
break
if controller_ip is None:
print "No controller running for this worker group."
return
return controller_ip
@classmethod
def __launch_worker__start_or_resume_vms(cls, worker_obj, config, num_vms_to_start=0):
# Check for any instances are assigned to this worker group
instance_list = config.get_all_instances(worker_group_id=worker_obj.id)
# Check if they are running or stopped (if so, resume them)
inst_to_resume = []
inst_to_deploy = []
if len(instance_list) > 0:
for i in instance_list:
status = worker_obj.get_instance_status(i)
if status == worker_obj.STATUS_RUNNING:
print "Worker running at {0}".format(i.ip_address)
num_vms_to_start -= 1
elif status == worker_obj.STATUS_STOPPED:
print "Resuming worker at {0}".format(i.ip_address)
inst_to_resume.append(i)
num_vms_to_start -= 1
#logging.debug("inst_to_resume={0}".format(inst_to_resume))
if len(inst_to_resume) > 0:
worker_obj.resume_instance(inst_to_resume)
inst_to_deploy.extend(inst_to_resume)
inst_to_deploy.extend(cls.__launch_worker__start_vms(worker_obj, num_vms_to_start))
#logging.debug("inst_to_deploy={0}".format(inst_to_deploy))
return inst_to_deploy
@classmethod
def __launch_worker__start_vms(cls, worker_obj, num_vms_to_start=0):
""" Return a list of booted instances ready to be deployed as workers."""
inst_to_deploy = []
if num_vms_to_start > 0:
# Start a new instances
print "Starting {0} new workers".format(num_vms_to_start)
inst_to_deploy = worker_obj.start_instance(num=num_vms_to_start)
if not isinstance(inst_to_deploy,list):
inst_to_deploy = [inst_to_deploy]
return inst_to_deploy
@classmethod
def __launch_worker__deploy_engines(cls, worker_obj, controller_ip, inst_to_deploy, config):
print "Deploying on {0} workers".format(len(inst_to_deploy))
if len(inst_to_deploy) > 0:
# deploying
controller_ssh = SSHDeploy(config=worker_obj.controller.provider, config_dir=config.config_dir)
engine_ssh = SSHDeploy(config=worker_obj.provider, config_dir=config.config_dir)
engine_file = controller_ssh.get_ipython_engine_file(controller_ip)
controller_ssh_keyfile = worker_obj.controller.provider.sshkeyfilename()
if len(inst_to_deploy) > 1:
logging.debug("__launch_worker__deploy_engines() workpool(size={0})".format(len(inst_to_deploy)))
jobs = []
for i in inst_to_deploy:
logging.debug("multiprocessing.Process(target=engine_ssh.deploy_ipython_engine({0}, engine_file)".format(i.ip_address))
p = multiprocessing.Process(target=engine_ssh.deploy_ipython_engine, args=(i.ip_address, controller_ip, engine_file, controller_ssh_keyfile,))
jobs.append(p)
p.start()
logging.debug("__launch_worker__deploy_engines() joining processes.")
for p in jobs:
p.join()
logging.debug("__launch_worker__deploy_engines() joined processes.")
else:
for i in inst_to_deploy:
logging.debug("starting engine on {0}".format(i.ip_address))
engine_ssh.deploy_ipython_engine(i.ip_address, controller_ip, engine_file, controller_ssh_keyfile)
else:
return
print "Success"
@classmethod
def stop_worker_groups(cls, args, config):
""" Stop workers of a MOLNs cluster. """
logging.debug("MOLNSWorkerGroup.stop_worker_groups(args={0})".format(args))
worker_obj = cls._get_workerobj(args, config)
if worker_obj is None: return
# Check for any instances are assigned to this worker group
instance_list = config.get_all_instances(worker_group_id=worker_obj.id)
# Check if they are running or stopped (if so, resume them)
inst_to_stop = []
if len(instance_list) > 0:
for i in instance_list:
status = worker_obj.get_instance_status(i)
if status == worker_obj.STATUS_RUNNING:
print "Stopping worker at {0}".format(i.ip_address)
inst_to_stop.append(i)
if len(inst_to_stop) > 0:
worker_obj.stop_instance(inst_to_stop)
else:
print "No workers running in the worker group"
@classmethod
def terminate_worker_groups(cls, args, config):
""" Terminate workers of a MOLNs cluster. """
logging.debug("MOLNSWorkerGroup.terminate_worker_groups(args={0})".format(args))
worker_obj = cls._get_workerobj(args, config)
if worker_obj is None: return
# Check for any instances are assigned to this worker group
instance_list = config.get_all_instances(worker_group_id=worker_obj.id)
# Check if they are running or stopped (if so, resume them)
inst_to_stop = []
if len(instance_list) > 0:
for i in instance_list:
status = worker_obj.get_instance_status(i)
if status == worker_obj.STATUS_RUNNING or status == worker_obj.STATUS_STOPPED:
print "Terminating worker at {0}".format(i.ip_address)
inst_to_stop.append(i)
if len(inst_to_stop) > 0:
worker_obj.terminate_instance(inst_to_stop)
else:
print "No workers running in the worker group"
###############################################
class MOLNSProvider(MOLNSbase):
@classmethod
def provider_export(cls, args, config):
""" Export the configuration of a provider. """
if len(args) < 1:
raise MOLNSException("USAGE: molns provider export name [Filename]\n"\
"\tExport the data from the provider with the given name.")
provider_name = args[0]
if len(args) > 1:
filename = args[1]
else:
filename = 'Molns-Export-Provider-' + provider_name + '.json'
# check if provider exists
try:
provider_obj = config.get_object(args[0], kind='Provider')
except DatastoreException as e:
raise MOLNSException("provider not found")
data = {'name': provider_obj.name,
'type': provider_obj.type,
'config': provider_obj.config}
return {'data': json.dumps(data),
'type': 'file',
'filename': filename}
@classmethod
def provider_import(cls, args, config, json_data=None):
""" Import the configuration of a provider. """
if json_data is None:
if len(args) < 1:
raise MOLNSException("USAGE: molns provider import [Filename.json]\n"\
"\Import the data from the provider with the given name.")
filename = args[0]
with open(filename) as fd:
data = json.load(fd)
else:
data = json_data
provider_name = data['name']
msg = ''
if data['type'] not in VALID_PROVIDER_TYPES:
raise MOLNSException("unknown provider type '{0}'".format(data['type']))
try:
provider_obj = config.get_object(provider_name, kind='Provider')
msg += "Found existing provider\n"
if provider_obj.type != data['type']:
raise MOLNSException("Import data has provider type '{0}'. Provier {1} exists with type {2}. Type conversion is not possible.".format(data['type'], provider_obj.name, provider_obj.type))
except DatastoreException as e:
provider_obj = config.create_object(name=provider_name, ptype=data['type'], kind='Provider')
msg += "Creating new provider\n"
cls.merge_config(provider_obj, data['config'])
config.save_object(provider_obj, kind='Provider')
msg += "Provider data imported\n"
return {'msg':msg}
@classmethod
def provider_get_config(cls, name=None, provider_type=None, config=None):
""" Return a list of dict of config var for the provider config.
Each dict in the list has the keys: 'key', 'value', 'type'
Either 'name' or 'provider_type' must be specified.
If 'name' is specified, then it will retreive the value from that
config and return it in 'value' (or return the string '********'
if that config is obfuscated, such passwords).