-
Notifications
You must be signed in to change notification settings - Fork 0
/
cm-mooc
executable file
·498 lines (393 loc) · 12.8 KB
/
cm-mooc
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
#!/usr/bin/env python
#
# Developed by Gregor von Laszewski for the MOOC, laszewski@gmail.com
#
# getcharacter is based on http://stackoverflow.com/questions/1829/how-do-i-make-a-menu-that-does-not-require-the-user-to-press-enter-to-make-a-s
#
# all other code based on Gregors early version of cloudmesh
#
#from blessings import Terminal
print "MMMMMMMMMMMMMMMMMMM"
import textwrap
import os
import sys
import select
import termios
import tty
from sh import ssh
from sh import nova
from sh import heat
from sh import cat
from sh import less
from sh import fgrep
import traceback
import hashlib
import random
import getpass
import subprocess
import pipes
######################################################################
# Terminal related methods
######################################################################
"""
# blessings not properly installed on india
term = Terminal()
(terminal_height, terminal_width) = os.popen(
'stty size', 'r').read().split()
def _line(name):
n = len(name)
return '==', name, (int(terminal_width) - n - 4) * '='
def _tline(name):
n = len(name)
return '%s== %s %s%s\n' % (term.white + term.on_blue, name,
(int(terminal_width) - n - 4) * '=',
term.normal)
print _line("first")
print _tline("second")
print
sys.exit()
"""
def logo():
banner = textwrap.dedent("""
FutureGrid - Cloud Mesh MOOC Shell
------------------------------------------------------
____ _ _ __ __ _
/ ___| | ___ _ _ __| | | \/ | ___ ___| |__
| | | |/ _ \| | | |/ _` | | |\/| |/ _ \/ __| '_ \
| |___| | (_) | |_| | (_| | | | | | __/\__ \ | | |
\____|_|\___/ \__,_|\__,_| |_| |_|\___||___/_| |_|
======================================================
""")
return banner
print logo()
username = os.getenv("OS_USERNAME")
tenant = os.getenv("OS_TENANT_NAME")
keyname = "%s-key" % (username)
salt_len = 12
#password_hash = None
if tenant != "fg380":
print "Please change your novarc file and change the tenant name to fg380"
print "The file is located at ~/.futuregrid/openstack_havana/novarc"
sys.exit()
def getcharater():
old_settings = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin.fileno())
select.select([sys.stdin], [], [], 0)
answer = sys.stdin.read(1)
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
return answer
"""
def add_message_if_missing(filename, message):
os.system("touch " + filename)
file = open(filename, 'rw')
lines = file.readlines()
file.close()
res = filter(lambda x: message in x, lines)
if len(res) == 0:
with open("test.txt", "a") as f:
f.write(str(message) + "\n")
"""
def start_vm():
vms = nova("--os-username", username, "--os-tenant-name",
tenant, "list").split("\n")[3:-2]
print vms
print "start vm ..."
def start_stack_vm():
#global password_hash
# if password_hash is None:
password_hash = get_hash_password()
try:
print "start stack vm ..."
vms = heat(
"stack-create", "-f", "/share/project/FG380/bigdata_mooc_temp.yaml",
"-P", "KeyName=%s;PasswdHash=%s" % (keyname, password_hash), username)
print vms
except:
print "ERROR: stack creation failed."
print "Exception in user code:"
print '-' * 60
traceback.print_exc(file=sys.stdout)
print '-' * 60
def suspend_vm():
print "suspend vm ..."
def resume_vm():
print "resume vm ..."
def list_vm():
print "list vm ..."
r = nova("--os-username", username, "--os-tenant-name", tenant, "list")
print r
def list_stack():
print "list stack ..."
r = heat("stack-list")
print r
def delete_stack():
print "delete stack ..."
r = heat("stack-delete", username)
print r
def stack_suspend():
print "suspend stack ..."
r = heat("action-suspend", username)
print r
def stack_resume():
print "resume stack ..."
r = heat("action-resume", username)
print r
def delete_key():
try:
r = nova("keypair-delete", keyname)
r = nova("keypair-list")
print r
except:
print "key not found"
def upload_key():
print "probing keys ..."
names = []
try:
r = nova("keypair-list")
keys = r.split("\n")[3:-2]
for key in keys:
(prefix, name, fingerprint, postfix) = key.split("|")
names.append(name.strip())
except:
print "no key yet uploaded"
if keyname in names:
print "You already have a key with the name %s." % keyname
else:
try:
os.system("nova keypair-add %s > ~/%s" % (keyname, keyname))
os.system("chmod 600 ~/%s" % (keyname))
except:
print "some error occured, yo probably have already a key uploaded"
print
r = nova("keypair-list")
print r
def get_ip_from_stack():
r = fgrep(heat("resource-show", username, "server"),
"physical_resource_id")
vms = r.split("\n")
physical_resource_id = vms[0].split("|")[2].strip()
r = nova("show", physical_resource_id)
network = fgrep(r, "private network")
ips = network.split("|")[2].strip()
(private_ip, public_ip) = ips.replace(" ", "").split(",")
return public_ip
def login():
print "login vm ..."
try:
ip = get_ip_from_stack()
except:
print "IP address not yet assigned, or server not yet created"
return
try:
print "ssh -X -i %s %s" % (os.path.expanduser("~/%s" % keyname), "root@%s" % ip)
os.system("ssh -X -i %s %s" %
(os.path.expanduser("~/%s" % keyname), "root@%s" % ip))
except:
print "ssh failed"
def check():
print "check vm ..."
try:
ip = get_ip_from_stack()
except:
print "IP address not yet assigned, or server not yet created"
return
try:
directory = "/home/ipynb"
command = ["-i", os.path.expanduser("~/%s" % keyname),
"root@%s" % (ip),
"test", "-e", pipes.quote(directory)
]
print "ssh", " ".join(command)
ssh(command)
print ('VM is created successfully . You can login to it')
except:
print ('VM is not ready yet. Please check after some time(~5 Mins)')
def is_account_created(msg):
if (os.path.isfile(os.path.expanduser('~/.futuregrid/openstack_havana/fg380'))):
print msg
else:
print "Your Openstack account is not yet created. It may take a day for this to happen. Please note no accounts will be created in hours outside of Mo-Fr 10am - 4pm EST"
sys.exit()
is_account_created("")
def get_first_stack_vm_id():
try:
r = fgrep(heat("stack-list"), username)
print "Your vms are:"
print r
vms = r.split("\n")
(prefix, id, rest, x, y, z) = vms[0].split("|")
id = id.strip()
print "ID = %s" % id
except:
print "I coudl not find a vm for you, did you start one?"
try:
list_stack()
except:
print "ERROR: you may not be in this project."
print "Please make sure on the portal that you are added to the members of the project."
sys.exit()
def show_default_password():
try :
filename = os.path.expanduser("~/.futuregrid/.moocrc")
with open(filename, "r") as f:
lines = f.readlines()
print "PASSWORD:", lines[0].replace("\n", "")
return lines[0].replace("\n", "")
except :
print "Password is not set yet"
def encode(u, encoding=None):
encoding = encoding or DEFAULT_ENCODING
return u.encode(encoding, "replace")
def cast_bytes(s, encoding=None):
if not isinstance(s, bytes):
return encode(s, encoding)
return s
def no_code(x, encoding=None):
return x
str_to_bytes = no_code
#
# see http://stackoverflow.com/questions/75057/what-is-the-best-way-to-check-the-strength-of-a-password
#
def validate_password(passwd):
if passwd is None:
return False
conditions_met = 0
conditions_total = 1
if len(passwd) >= 6:
if passwd.lower() != passwd:
conditions_met += 1
if len([x for x in passwd if x.isdigit()]) > 0:
conditions_met += 1
if len([x for x in passwd if not x.isalnum()]) > 0:
conditions_met += 1
result = False
if conditions_met >= 1:
result = True
else:
print ("Password length should be >= 6");
return result
def create_passphrase(passphrase=None, algorithm='sha1'):
"""Generate hashed password and salt for use in notebook configuration.
In the notebook configuration, set `c.NotebookApp.password` to
the generated string.
Parameters
----------
passphrase : str
Password to hash. If unspecified, the user is asked to input
and verify a password.
algorithm : str
Hashing algorithm to use (e.g, 'sha1' or any argument supported
by :func:`hashlib.new`).
Returns
-------
hashed_passphrase : str
Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'.
Examples
--------
>>> passwd('mypassword')
'sha1:6395678943659874687436587346'
"""
while not validate_password(passphrase):
print "Please define a pasphrase for your notebook:"
passphrase = None
if passphrase is None:
for i in range(3):
p0 = getpass.getpass('Enter password: ')
p1 = getpass.getpass('Verify password: ')
if p0 == p1:
passphrase = p0
break
else:
print('Passwords do not match.')
#raise UsageError('No matching passwords found. Giving up.')
passphrase = None
writepassword(passphrase)
return passphrase
def get_hash_password():
password = show_default_password()
if password is None:
password = create_passphrase()
return create_hash(password)
def create_hash(passphrase, algorithm='sha1'):
h = hashlib.new(algorithm)
salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len)
h.update(cast_bytes(passphrase, 'utf-8') + str_to_bytes(salt, 'ascii'))
return ':'.join((algorithm, salt, h.hexdigest()))
def writepassword(user_password):
filename = os.path.expanduser("~/.futuregrid/.moocrc")
password_file = open(filename, 'w+')
password_file.write(user_password)
password_file.close()
# chmod go-rwx
#def setup_bashrc():#
#
# filename = "test.txt"
# add_message_if_missing(filename, "module load novaclient")
# add_message_if_missing(filename, "module load heatclient")
# add_message_if_missing(filename, "source ~/.futuregrid/openstack_havana/novarc")
# print "bashrc file created"
# print 70 * '-'
# r = cat(filename)
# print r
# print 70 * '-'
# uploading SSH key to the cloud
# Managing Securiy Groups
# nova secgroup-add-rule default icmp -1 -1 0.0.0.0/0
# nova secgroup-add-rule default tcp 22 22 0.0.0.0/0
# nova secgroup-list-rules default
cont = True
while cont:
print
print """Cloudmesh MOOC FG380 Menu"""
print 70 * '-'
print "user : %s" % (username)
print "tenant: %s" % (tenant)
print "key : %s" % (keyname)
print 70 * '-'
print """
== Keys ================== == VM ====================
1) upload 3) start
2) delete 4) suspend
5) resume
== Login ================= 6) list
7) delete
c) check
l) login
p) notebook password
== Quit ================= == IP =====================
q) Quit cm-mooc 8) list public ip
"""
answer = getcharater()
if "1" in answer:
upload_key()
elif "2" in answer:
delete_key()
elif answer in ["3", "+"]:
start_stack_vm()
elif answer in ["3", "."]:
stack_suspend()
elif answer in ["5", "r"]:
stack_resume()
elif answer in ["6", "?"]:
list_stack()
elif answer in ["7", "-"]:
delete_stack()
elif "8" in answer:
print "retreiving public ip ..."
try:
ip = get_ip_from_stack()
print "Public IP: ", ip
except:
print "no ip found"
elif answer in ["9", "l"]:
login()
elif "c" in answer:
check()
elif "p" in answer:
show_default_password()
elif "0" in answer:
is_account_created("Your OpenStack account is ready to use.")
# elif "0" in answer:
# setup_bashrc()
elif answer in "qQxX":
cont = False