-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdeis.py
More file actions
executable file
·1395 lines (1224 loc) · 49.5 KB
/
deis.py
File metadata and controls
executable file
·1395 lines (1224 loc) · 49.5 KB
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
"""
This Deis command-line client issues API calls to a Deis controller.
Usage: deis <command> [--formation <formation>] [<args>...]
Auth commands::
register register a new user with a controller
login login to a controller
logout logout from the current controller
Shortcut commands::
create create a new container formation
scale scale container types (web=2, worker=1)
logs print most recent logs for the formation
open open a URL for the formation in a browser
info print a representation of the formation
converge force-converge all nodes in the formation
calculate recalculate and update the formation databag
destroy destroy a container formation
Subcommands, use ``deis help [subcommand]`` to learn more::
formations manage container formations
layers manage layers of nodes
nodes manage nodes of all types
containers manage runtime containers
providers manage cloud provider credentials
flavors manage node flavors on a provider
keys manage ssh keys
config manage environment variables for a formation
builds manage git-push or docker builds
releases manage a formation's release history
Use ``git push deis master`` to deploy to a formation.
"""
from cookielib import MozillaCookieJar
from getpass import getpass
import glob
import json
import os.path
import random
import re
import subprocess
import sys
import time
import urlparse
import webbrowser
import yaml
from docopt import docopt
from docopt import DocoptExit
import requests
__version__ = '0.0.5'
class Session(requests.Session):
"""
Session for making API requests and interacting with the filesystem
"""
def __init__(self):
super(Session, self).__init__()
self.trust_env = False
cookie_file = os.path.expanduser('~/.deis/cookies.txt')
cookie_dir = os.path.dirname(cookie_file)
self.cookies = MozillaCookieJar(cookie_file)
# Create the $HOME/.deis dir if it doesn't exist
if not os.path.isdir(cookie_dir):
os.mkdir(cookie_dir, 0700)
# Load existing cookies if the cookies.txt exists
if os.path.isfile(cookie_file):
self.cookies.load()
self.cookies.clear_expired_cookies()
def clear(self, domain):
"""Clear cookies for the specified domain."""
try:
self.cookies.clear(domain)
self.cookies.save()
except KeyError:
pass
def git_root(self):
"""
Return the absolute path from the git repository root
If no git repository exists, raise an EnvironmentError
"""
try:
git_root = subprocess.check_output(
['git', 'rev-parse', '--show-toplevel'],
stderr=subprocess.PIPE).strip('\n')
except subprocess.CalledProcessError:
raise EnvironmentError('Current directory is not a git repository')
return git_root
def get_formation(self):
"""
Return the formation name for the current directory
The formation is determined by parsing `git remote -v` output.
If no formation is found, raise an EnvironmentError.
"""
git_root = self.git_root()
# try to match a deis remote
remotes = subprocess.check_output(['git', 'remote', '-v'],
cwd=git_root)
m = re.match(r'^deis\W+(?P<url>\S+)\W+\(', remotes, re.MULTILINE)
if not m:
raise EnvironmentError(
'Could not find deis remote in `git remote -v`')
url = m.groupdict()['url']
m = re.match('\S+:(?P<formation>[a-z0-9-]+)(.git)?', url)
if not m:
raise EnvironmentError("Could not parse: {url}".format(**locals()))
return m.groupdict()['formation']
formation = property(get_formation)
def request(self, *args, **kwargs):
"""
Issue an HTTP request with proper cookie handling including
`Django CSRF tokens <https://docs.djangoproject.com/en/dev/ref/contrib/csrf/>`
"""
for cookie in self.cookies:
if cookie.name == 'csrftoken':
if 'headers' in kwargs:
kwargs['headers']['X-CSRFToken'] = cookie.value
else:
kwargs['headers'] = {'X-CSRFToken': cookie.value}
break
response = super(Session, self).request(*args, **kwargs)
self.cookies.save()
return response
class Settings(dict):
"""
Settings backed by a file in the user's home directory
On init, settings are loaded from ~/.deis/client.yaml
"""
def __init__(self):
path = os.path.expanduser('~/.deis')
if not os.path.exists(path):
os.mkdir(path)
self._path = os.path.join(path, 'client.yaml')
if not os.path.exists(self._path):
with open(self._path, 'w') as f:
f.write(yaml.safe_dump({}))
# load initial settings
self.load()
def load(self):
"""
Deserialize and load settings from the filesystem
"""
with open(self._path) as f:
data = f.read()
settings = yaml.safe_load(data)
self.update(settings)
return settings
def save(self):
"""
Serialize and save settings to the filesystem
"""
data = yaml.safe_dump(dict(self))
with open(self._path, 'w') as f:
f.write(data)
return data
def dictify(args):
"""Converts a list of key=val strings into a python dict.
>>> dictify(['MONGODB_URL=http://mongolabs.com/test', 'scale=5'])
{'MONGODB_URL': 'http://mongolabs.com/test', 'scale': 5}
"""
data = {}
for arg in args:
try:
var, val = arg.split('=')
except ValueError:
raise DocoptExit()
# Try to coerce the value to an int since that's a common use case
try:
data[var] = int(val)
except ValueError:
data[var] = val
return data
def trim(docstring):
"""
Function to trim whitespace from docstring
c/o PEP 257 Docstring Conventions
<http://www.python.org/dev/peps/pep-0257/>
"""
if not docstring:
return ''
# Convert tabs to spaces (following the normal Python rules)
# and split into a list of lines:
lines = docstring.expandtabs().splitlines()
# Determine minimum indentation (first line doesn't count):
indent = sys.maxint
for line in lines[1:]:
stripped = line.lstrip()
if stripped:
indent = min(indent, len(line) - len(stripped))
# Remove indentation (first line is special):
trimmed = [lines[0].strip()]
if indent < sys.maxint:
for line in lines[1:]:
trimmed.append(line[indent:].rstrip())
# Strip off trailing and leading blank lines:
while trimmed and not trimmed[-1]:
trimmed.pop()
while trimmed and not trimmed[0]:
trimmed.pop(0)
# Return a single string:
return '\n'.join(trimmed)
class DeisClient(object):
"""
A client which interacts with a Deis controller.
"""
def __init__(self):
self._session = Session()
self._settings = Settings()
def _dispatch(self, method, path, body=None,
headers={'content-type': 'application/json'}, **kwargs):
"""
Dispatch an API request to the active Deis controller
"""
func = getattr(self._session, method.lower())
controller = self._settings['controller']
if not controller:
raise EnvironmentError(
'No active controller. Use `deis login` or `deis register` to get started.')
url = urlparse.urljoin(controller, path, **kwargs)
response = func(url, data=body, headers=headers)
return response
def auth_register(self, args):
"""
Register a new user with a Deis controller
Usage: deis auth:register <controller> [options]
Options:
--username=USERNAME provide a username for the new account
--password=PASSWORD provide a password for the new account
--email=EMAIL provide an email address
"""
controller = args['<controller>']
username = args.get('--username')
if not username:
username = raw_input('username: ')
password = args.get('--password')
if not password:
password = getpass('password: ')
email = args.get('--email')
if not email:
email = raw_input('email: ')
url = urlparse.urljoin(controller, '/api/auth/register')
payload = {'username': username, 'password': password, 'email': email}
response = self._session.post(url, data=payload, allow_redirects=False)
if response.status_code == requests.codes.created: # @UndefinedVariable
self._settings['controller'] = controller
self._settings.save()
print("Registered {}".format(username))
login_args = {'--username': username, '--password': password,
'<controller>': controller}
if self.auth_login(login_args) is False:
print('Login failed')
return
print
self.keys_add({})
print
self.providers_discover({})
print
print 'Use `deis create --flavor=ec2-us-east-1` to create a new formation'
else:
print('Registration failed', response.content)
return False
def auth_login(self, args):
"""
Login by authenticating against a controller
Usage: deis auth:login <controller> [--username=<username> --password=<password>]
"""
controller = args['<controller>']
username = args.get('--username')
headers = {}
if not username:
username = raw_input('username: ')
password = args.get('--password')
if not password:
password = getpass('password: ')
url = urlparse.urljoin(controller, '/api/auth/login/')
payload = {'username': username, 'password': password}
# clear any cookies for this controller's domain
self._session.clear(urlparse.urlparse(url).netloc)
# prime cookies for login
self._session.get(url, headers=headers)
# post credentials to the login URL
response = self._session.post(url, data=payload, allow_redirects=False)
if response.status_code == requests.codes.found: # @UndefinedVariable
self._settings['controller'] = controller
self._settings.save()
print("Logged in as {}".format(username))
return True
else:
print('Login failed')
self._session.cookies.clear()
self._session.cookies.save()
return False
def auth_logout(self, args):
"""
Logout from a controller and clear the user session
Usage: deis auth:logout
"""
controller = self._settings.get('controller')
if controller:
self._dispatch('get', '/api/auth/logout/')
self._session.cookies.clear()
self._session.cookies.save()
self._settings['controller'] = None
self._settings.save()
print('Logged out')
def builds(self, args):
"""
Valid commands for builds:
builds:list list build history for a formation
builds:create coming soon!
Use `deis help [command]` to learn more
"""
return self.builds_list(args)
def builds_create(self, args):
"""
Create a new build for a formation
Usage: deis builds:create - [--formation=<formation>]
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
data = sys.stdin.read()
# url / sha / slug_size / procfile / checksum
j = json.loads(data)
response = self._dispatch('post',
"/api/formations/{}/builds".format(formation),
body=json.dumps(j))
if response.status_code == requests.codes.created: # @UndefinedVariable
print('Build created.')
else:
print('Error!', response.text)
def builds_list(self, args):
"""
List build history for a formation
Usage: deis builds:list
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
response = self._dispatch('get', "/api/formations/{}/builds".format(formation))
if response.status_code == requests.codes.ok: # @UndefinedVariable
print("=== {} Builds".format(formation))
data = response.json()
for item in data['results']:
print("{0[uuid]:<23} {0[created]}".format(item))
else:
print('Error!', response.text)
def config(self, args):
"""
Valid commands for config:
config:list list environment variables for a formation
config:set set environment variables for a formation
config:unset unset environment variables for a formation
Use `deis help [command]` to learn more
"""
return self.config_list(args)
def config_list(self, args):
"""
List environment variables for a formation
Usage: deis config:list
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
response = self._dispatch('get', "/api/formations/{}/config".format(formation))
if response.status_code == requests.codes.ok: # @UndefinedVariable
config = response.json()
values = json.loads(config['values'])
print("=== {} Config".format(formation))
items = values.items()
if len(items) == 0:
print('No configuration')
return
for k, v in values.items():
print("{k}: {v}".format(**locals()))
else:
print('Error!', response.text)
def config_set(self, args):
"""
Set environment variables for a formation
Usage: deis config:set <var>=<value>...
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
body = {'values': json.dumps(dictify(args['<var>=<value>']))}
response = self._dispatch('post',
"/api/formations/{}/config".format(formation),
json.dumps(body))
if response.status_code == requests.codes.created: # @UndefinedVariable
config = response.json()
values = json.loads(config['values'])
print("=== {}".format(formation))
items = values.items()
if len(items) == 0:
print('No configuration')
return
for k, v in values.items():
print("{k}: {v}".format(**locals()))
else:
print('Error!', response.text)
def config_unset(self, args):
"""
Unset an environment variable for a formation
Usage: deis config:unset <key>...
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
values = {}
for k in args.get('<key>'):
values[k] = None
body = {'values': json.dumps(values)}
response = self._dispatch('post',
"/api/formations/{}/config".format(formation),
data=json.dumps(body))
if response.status_code == requests.codes.created: # @UndefinedVariable
config = response.json()
values = json.loads(config['values'])
print("=== {}".format(formation))
items = values.items()
if len(items) == 0:
print('No configuration')
return
for k, v in values.items():
print("{k}: {v}".format(**locals()))
else:
print('Error!', response.text)
def containers(self, args):
"""
Valid commands for containers:
containers:list list containers for a formation
containers:scale scale a formation's containers (i.e web=4 worker=2)
Use `deis help [command]` to learn more
"""
return self.containers_list(args)
def containers_list(self, args):
"""
List containers for a formation
Usage: deis containers:list
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
response = self._dispatch('get',
"/api/formations/{}/containers".format(formation))
databag = self.formations_calculate({}, quiet=True)
procfile = databag['release']['build'].get('procfile', {})
if response.status_code == requests.codes.ok: # @UndefinedVariable
data = response.json()
print("=== {} Containers".format(formation))
c_map = {}
for item in data['results']:
c_map.setdefault(item['type'], []).append(item)
print
for c_type in c_map.keys():
command = procfile.get(c_type, '<none>')
print("--- {c_type}: `{command}`".format(**locals()))
for c in c_map[c_type]:
print("{type}.{num} up {created} ({node})".format(**c))
print
else:
print('Error!', response.text)
def containers_scale(self, args):
"""
Scale containers for a formation
Example: deis containers:scale web=4 worker=2
Usage: deis containers:scale <type=num>...
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
body = {}
for type_num in args.get('<type=num>'):
typ, count = type_num.split('=')
body.update({typ: int(count)})
print('Scaling containers... but first, coffee!')
before = time.time()
response = self._dispatch('post',
"/api/formations/{}/scale/containers".format(formation),
json.dumps(body))
if response.status_code == requests.codes.ok: # @UndefinedVariable
print('done in {}s\n'.format(int(time.time() - before)))
self.containers_list({})
else:
print('Error!', response.text)
def flavors(self, args):
"""
Valid commands for flavors:
flavors:create create a new node flavor
flavors:info print information about a node flavor
flavors:list list available flavors
flavors:delete delete a node flavor
Use `deis help [command]` to learn more
"""
return self.flavors_list(args)
def flavors_create(self, args):
"""
Create a new node flavor
Usage: deis flavors:create --id=<id> --provider=<provider> --params=<params> [options]
Options:
--params=PARAMS provider-specific parameters (size, region, zone, etc.)
--init=INIT override Ubuntu cloud-init with custom YAML
"""
body = {'id': args.get('--id'), 'provider': args.get('--provider')}
fields = ('params', 'init', 'ssh_username', 'ssh_private_key',
'ssh_public_key')
for fld in fields:
opt = args.get('--' + fld)
if opt:
body.update({fld: opt})
response = self._dispatch('post', '/api/flavors', json.dumps(body))
if response.status_code == requests.codes.created: # @UndefinedVariable
print("{0[id]}".format(response.json()))
else:
print('Error!', response.text)
def flavors_delete(self, args):
"""
Delete a node flavor
Usage: deis flavors:delete <id>
"""
flavor = args.get('<id>')
response = self._dispatch('delete', "/api/flavors/{}".format(flavor))
if response.status_code == requests.codes.no_content: # @UndefinedVariable
pass
else:
print('Error!', response.status_code, response.text)
def flavors_info(self, args):
"""
Print information about a node flavor
Usage: deis flavors:info <flavor>
"""
flavor = args.get('<flavor>')
response = self._dispatch('get', "/api/flavors/{}".format(flavor))
if response.status_code == requests.codes.ok: # @UndefinedVariable
print(json.dumps(response.json(), indent=2))
else:
print('Error!', response.text)
def flavors_list(self, args):
"""
List available node flavors
Usage: deis flavors:list
"""
response = self._dispatch('get', '/api/flavors')
if response.status_code == requests.codes.ok: # @UndefinedVariable
data = response.json()
if data['count'] == 0:
print 'No flavors found'
return
print("=== {owner} Flavors".format(**data['results'][0]))
for item in data['results']:
print("{id}: params => {params}".format(**item))
else:
print('Error!', response.text)
def formations(self, args):
"""
Valid commands for formations:
formations:create create a new container formation
formations:info print a represenation of the formation
formations:scale scale container types (web=2, worker=1)
formations:balance rebalance the container formation
formations:converge force-converge all nodes in the formation
formations:calculate recalculate and update the formation databag
formations:destroy destroy a container formation
Use `deis help [command]` to learn more
"""
return self.formations_list(args)
def formations_create(self, args):
"""
Create a new formation
If no ID is provided, one will be generated automatically.
Providing a flavor automatically create a default runtime
and proxy layer.
Usage: deis formations:create [--id=<id> --flavor=<flavor>]
"""
body = {}
try:
self._session.git_root() # check for a git repository
except EnvironmentError:
print 'No git repository found, use `git init` to create one.'
return
for opt in ('--id',):
o = args.get(opt)
if o:
body.update({opt.strip('-'): o})
# if a flavor was passed, make sure its valid
flavor = args.get('--flavor')
if flavor:
response = self._dispatch('get', '/api/flavors/{}'.format(flavor))
if response.status_code != 200:
print 'Flavor not found'
return
sys.stdout.write('Creating formation... ')
sys.stdout.flush()
response = self._dispatch('post', '/api/formations',
json.dumps(body))
if response.status_code == requests.codes.created: # @UndefinedVariable
data = response.json()
formation = data['id']
print("done, created {}".format(formation))
# add a git remote
hostname = urlparse.urlparse(self._settings['controller']).netloc
git_remote = "git@{hostname}:{formation}.git".format(**locals())
try:
subprocess.check_call(
['git', 'remote', 'add', '-f', 'deis', git_remote],
stdout=subprocess.PIPE)
except subprocess.CalledProcessError:
sys.exit(1)
print('Git remote deis added')
# create default layers if a flavor was provided
if flavor:
print
self.layers_create({'<id>': 'runtime', '<flavor>': flavor})
self.layers_create({'<id>': 'proxy', '<flavor>': flavor})
print('\nUse `deis layers:scale proxy=1 runtime=1` to scale a basic formation')
else:
print('Error!', response.text)
def formations_info(self, args):
"""
Print info about a formation
Usage: deis formations:info
"""
formation = args.get('<formation>')
if not formation:
formation = self._session.formation
response = self._dispatch('get', "/api/formations/{}".format(formation))
if response.status_code == requests.codes.ok: # @UndefinedVariable
data = response.json()
print("=== {} Formation".format(formation))
print
args = {'<formation>': data['id']}
self.layers_list(args)
print
self.nodes_list(args)
print
self.containers_list(args)
else:
print('Error!', response.text)
def formations_list(self, args):
"""
List available formations
Usage: deis formations:list
"""
response = self._dispatch('get', '/api/formations')
if response.status_code == requests.codes.ok: # @UndefinedVariable
data = response.json()
if data['count'] == 0:
print 'No formations found'
return
print("=== {owner} Formations".format(**data['results'][0]))
for item in data['results']:
formation = item['id']
layers = json.loads(item.get('layers', {}))
containers = json.loads(item.get('containers', {}))
print("{formation}: layers => {layers} containers => {containers}".format(
**locals()))
else:
print('Error!', response.text)
def formations_destroy(self, args):
"""
Destroy a formation
Usage: deis formations:destroy [<formation>] [--confirm=<confirm>]
"""
formation = args.get('<formation>')
if not formation:
formation = self._session.formation
confirm = args.get('--confirm')
if confirm == formation:
pass
else:
print """
! WARNING: Potentially Destructive Action
! This command will destroy: {formation}
! To proceed, type "{formation}" or re-run this command with --confirm={formation}
""".format(**locals())
confirm = raw_input('> ').strip('\n')
if confirm != formation:
print('Destroy aborted')
return
sys.stdout.write("Destroying {}... ".format(formation))
sys.stdout.flush()
before = time.time()
response = self._dispatch('delete', "/api/formations/{}".format(formation))
if response.status_code in (requests.codes.no_content, # @UndefinedVariable
requests.codes.not_found): # @UndefinedVariable
print('done in {}s'.format(int(time.time() - before)))
try:
subprocess.check_call(
['git', 'remote', 'rm', 'deis'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print('Git remote deis removed')
except subprocess.CalledProcessError:
pass # ignore error
else:
print('Error!', response.text)
def formations_calculate(self, args, quiet=False):
"""
Recalculate the formation's databag
This command will recalculate the databag, update the Chef server
and return the databag JSON.
Usage: deis formations:calculate
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
response = self._dispatch('post',
"/api/formations/{}/calculate".format(formation))
if response.status_code == requests.codes.ok: # @UndefinedVariable
databag = json.loads(response.content)
if quiet is False:
print(json.dumps(databag, indent=2))
return databag
else:
print('Error!', response.text)
def formations_converge(self, args):
"""
Force converge a formation
Converging a formation will force a Chef converge on
all nodes in the formation, ensuring the formation is
completely up-to-date.
Usage: deis formations:converge
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
sys.stdout.write('Converging {}... '.format(formation))
sys.stdout.flush()
before = time.time()
response = self._dispatch('post',
"/api/formations/{}/converge".format(formation))
if response.status_code == requests.codes.ok: # @UndefinedVariable
print('done in {}s'.format(int(time.time() - before)))
databag = json.loads(response.content)
print(json.dumps(databag, indent=2))
else:
print('Error!', response.text)
def keys(self, args):
"""
Valid commands for SSH keys:
keys:list list SSH keys for the logged in user
keys:add add an SSH key
keys:remove remove an SSH key
Use `deis help [command]` to learn more
"""
return self.keys_list(args)
def keys_add(self, args):
"""
Add SSH keys for the logged in user
Usage: deis keys:add [<key>]
"""
path = args.get('<key>')
if not path:
ssh_dir = os.path.expanduser('~/.ssh')
pubkeys = glob.glob(os.path.join(ssh_dir, '*.pub'))
print('Found the following SSH public keys:')
for i, k in enumerate(pubkeys):
key = k.split(os.path.sep)[-1]
print("{0}) {1}".format(i + 1, key))
inp = raw_input('Which would you like to use with Deis? ')
try:
path = pubkeys[int(inp) - 1]
key_id = path.split(os.path.sep)[-1].replace('.pub', '')
except:
print 'Aborting'
return
with open(path) as f:
data = f.read()
match = re.match(r'^(ssh-...) ([^ ]+) (.+)', data)
if not match:
print 'Could not parse public key material'
return
key_type, key_str, _key_comment = match.groups()
body = {'id': key_id, 'public': "{0} {1}".format(key_type, key_str)}
sys.stdout.write("Uploading {} to Deis... ".format(path))
sys.stdout.flush()
response = self._dispatch('post', '/api/keys', json.dumps(body))
if response.status_code == requests.codes.created: # @UndefinedVariable
print('done')
else:
print('Error!', response.text)
def keys_list(self, args):
"""
List SSH keys for the logged in user
Usage: deis keys:list
"""
response = self._dispatch('get', '/api/keys')
if response.status_code == requests.codes.ok: # @UndefinedVariable
data = response.json()
if data['count'] == 0:
print 'No keys found'
return
print("=== {owner} Keys".format(**data['results'][0]))
for key in data['results']:
public = key['public']
print("{0} {1}...{2}".format(
key['id'], public[0:16], public[-10:]))
else:
print('Error!', response.text)
def keys_remove(self, args):
"""
Remove an SSH key for the logged in user
Usage: deis keys:remove <key>
"""
key = args.get('<key>')
sys.stdout.write("Removing {} SSH Key... ".format(key))
sys.stdout.flush()
response = self._dispatch('delete', "/keys/{}".format(key))
if response.status_code == requests.codes.no_content: # @UndefinedVariable
print('done')
else:
print('Error!', response.text)
def layers(self, args):
"""
Valid commands for node layers:
layers:create create a layer of nodes for a formation
layers:scale scale nodes in a layer (e.g. proxy=1 runtime=2)
layers:list list layers in a formation
layers:destroy destroy a layer of nodes in a formation
Use `deis help [command]` to learn more
"""
return self.layers_list(args)
def layers_create(self, args):
"""
Create a layer of nodes
Usage: deis layers:create <id> <flavor> [options]
Chef Options:
--run_list=RUN_LIST run-list to use when bootstrapping nodes
--environment=ENVIRONMENT chef environment to place nodes [default: _default]
--attributes=INITIAL_ATTRS initial attributes for nodes
SSH Options:
--ssh_username=USERNAME username for ssh connections [default: ubuntu]
--ssh_private_key=PRIVATE_KEY private key for ssh comm (default: auto-gen)
--ssh_public_key=PUBLIC_KEY public key for ssh comm (default: auto-gen)
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
body = {'id': args['<id>'], 'flavor': args['<flavor>']}
for opt in ('--environment', '--initial_attributes', '--run_list',
'--ssh_username', '--ssh_private_key', '--ssh_public_key'):
o = args.get(opt)
if o:
body.update({opt.strip('-'): o})
# provide default run_list for runtime and proxy
if not 'run_list' in body:
if body['id'] == 'runtime':
body['run_list'] = 'recipe[deis],recipe[deis::runtime]'
elif body['id'] == 'proxy':
body['run_list'] = 'recipe[deis],recipe[deis::proxy]'
sys.stdout.write("Creating {} layer... ".format(args['<id>']))
sys.stdout.flush()
before = time.time()
response = self._dispatch('post', "/api/formations/{}/layers".format(formation),
json.dumps(body))
if response.status_code == requests.codes.created: # @UndefinedVariable
print('done in {}s'.format(int(time.time() - before)))
else:
print('Error!', response.text)
def layers_destroy(self, args):
"""
Destroy a layer of nodes
Usage: deis layers:destroy <id>
"""
formation = args.get('--formation')
if not formation:
formation = self._session.formation
layer = args['<id>'] # noqa
sys.stdout.write("Destroying {layer} layer... ".format(**locals()))
sys.stdout.flush()
before = time.time()
response = self._dispatch(
'delete', "/api/formations/{formation}/layers/{layer}".format(**locals()))
if response.status_code == requests.codes.no_content: # @UndefinedVariable
print('done in {}s'.format(int(time.time() - before)))
else:
print('Error!', response.text)
def layers_list(self, args):
"""
List layers for a formation