This repository has been archived by the owner on Nov 30, 2021. It is now read-only.
/
deis.py
executable file
·2138 lines (1892 loc) · 75.5 KB
/
deis.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
"""
The Deis command-line client issues API calls to a Deis controller.
Usage: deis <command> [<args>...]
Auth commands::
register register a new user with a controller
login login to a controller
logout logout from the current controller
Subcommands, use ``deis help [subcommand]`` to learn more::
formations manage formations used to host applications
layers manage layers used for node configuration
nodes manage nodes used to host containers and proxies
apps manage applications used to provide services
containers manage containers used to handle requests and jobs
config manage environment variables that define app config
builds manage builds created using `git push`
releases manage releases of an application
providers manage credentials used to access cloud providers
flavors manage flavors of nodes including size and location
keys manage ssh keys used for `git push` deployments
perms manage permissions for shared apps and formations
Developer shortcut commands::
create create a new application
scale scale containers by type (web=2, worker=1)
info view information about the current app
open open a URL to the app in a browser
logs view aggregated log info for the app
run run a command in an ephemeral app container
destroy destroy an application
Use ``git push deis master`` to deploy to an application.
"""
from __future__ import print_function
from collections import namedtuple
from cookielib import MozillaCookieJar
from datetime import datetime
from getpass import getpass
from itertools import cycle
from threading import Event
from threading import Thread
import glob
import json
import locale
import os.path
import random
import re
import subprocess
import sys
import tempfile
import time
import urlparse
import webbrowser
from dateutil import parser
from dateutil import relativedelta
from dateutil import tz
from docopt import docopt
from docopt import DocoptExit
import requests
import yaml
__version__ = '0.5.1'
locale.setlocale(locale.LC_ALL, '')
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_app(self):
"""
Return the application name for the current directory
The application is determined by parsing `git remote -v` output.
If no application 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.search(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<app>[a-z0-9-]+)(.git)?$', url)
if not m:
raise EnvironmentError("Could not parse: {url}".format(**locals()))
return m.groupdict()['app']
app = property(get_app)
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
_counter = 0
def _newname(template="Thread-{}"):
"""Generate a new thread name."""
global _counter
_counter += 1
return template.format(_counter)
FRAMES = {
'arrow': ['^', '>', 'v', '<'],
'dots': ['...', 'o..', '.o.', '..o'],
'ligatures': ['bq', 'dp', 'qb', 'pd'],
'lines': [' ', '-', '=', '#', '=', '-'],
'slash': ['-', '\\', '|', '/'],
}
class TextProgress(Thread):
"""Show progress for a long-running operation on the command-line."""
def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
name = name or _newname("TextProgress-Thread-{}")
style = kwargs.get('style', 'dots')
super(TextProgress, self).__init__(
group, target, name, args, kwargs)
self.daemon = True
self.cancelled = Event()
self.frames = cycle(FRAMES[style])
def run(self):
"""Write ASCII progress animation frames to stdout."""
if not os.environ.get('DEIS_HIDE_PROGRESS'):
time.sleep(0.5)
self._write_frame(self.frames.next(), erase=False)
while not self.cancelled.is_set():
time.sleep(0.4)
self._write_frame(self.frames.next())
# clear the animation
sys.stdout.write('\b' * (len(self.frames.next()) + 2))
sys.stdout.flush()
def cancel(self):
"""Set the animation thread as cancelled."""
self.cancelled.set()
def _write_frame(self, frame, erase=True):
if erase:
backspaces = '\b' * (len(frame) + 2)
else:
backspaces = ''
sys.stdout.write("{} {} ".format(backspaces, frame))
# flush stdout or we won't see the frame
sys.stdout.flush()
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('=', 1)
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 get_provider_creds(provider, raise_error=False):
"""Query environment variables and return a provider's creds if found.
"""
cred_types = {
'ec2': [[('AWS_ACCESS_KEY_ID', 'access_key', None),
('AWS_SECRET_ACCESS_KEY', 'secret_key', None)],
[('AWS_ACCESS_KEY', 'access_key', None),
('AWS_SECRET_KEY', 'secret_key', None)]],
'rackspace': [[('RACKSPACE_USERNAME', 'username', None),
('RACKSPACE_API_KEY', 'api_key', None),
('CLOUD_ID_TYPE', 'identity_type', 'rackspace')]],
'digitalocean': [[('DIGITALOCEAN_CLIENT_ID', 'client_id', None),
('DIGITALOCEAN_API_KEY', 'api_key', None)]]
}
missing = None
for cred_set in cred_types[provider]:
creds = {}
for envvar, key, default in cred_set:
val = os.environ.get(envvar, default)
if not val:
missing = envvar
break
else:
creds[key] = val
if creds:
return creds
if raise_error:
raise EnvironmentError(
"Missing environment variable: {}".format(missing))
def readable_datetime(datetime_str):
"""
Return a human-readable datetime string from an ECMA-262 (JavaScript)
datetime string.
"""
timezone = tz.tzlocal()
dt = parser.parse(datetime_str).astimezone(timezone)
now = datetime.now(timezone)
delta = relativedelta.relativedelta(now, dt)
# if it happened today, say "2 hours and 1 minute ago"
if delta.days <= 1 and dt.day == now.day:
if delta.hours == 0:
hour_str = ''
elif delta.hours == 1:
hour_str = '1 hour '
else:
hour_str = "{} hours ".format(delta.hours)
if delta.minutes == 0:
min_str = ''
elif delta.minutes == 1:
min_str = '1 minute '
else:
min_str = "{} minutes ".format(delta.minutes)
if not any((hour_str, min_str)):
return 'Just now'
else:
return "{}{}ago".format(hour_str, min_str)
# if it happened yesterday, say "yesterday at 3:23 pm"
yesterday = now + relativedelta.relativedelta(days=-1)
if delta.days <= 2 and dt.day == yesterday.day:
return dt.strftime("Yesterday at %X")
# otherwise return locale-specific date/time format
else:
return dt.strftime('%c %Z')
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 ResponseError(Exception):
pass
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 apps(self, args):
"""
Valid commands for apps:
apps:create create a new application
apps:list list accessible applications
apps:info view info about an application
apps:open open the application in a browser
apps:logs view aggregated application logs
apps:run run a command in an ephemeral app container
apps:destroy destroy an application
Use `deis help [command]` to learn more
"""
return self.apps_list(args)
def apps_calculate(self, args, quiet=False):
"""
Calculate the application's JSON representation
Usage: deis apps:calculate [--app=<app>]
"""
app = args.get('--app')
if not app:
app = self._session.app
response = self._dispatch('post',
"/api/apps/{}/calculate".format(app))
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:
raise ResponseError(response)
def apps_create(self, args):
"""
Create a new application
If no ID is provided, one will be generated automatically.
If no formation is provided, the first available will be used.
Usage: deis apps:create [--id=<id> --formation=<formation>]
"""
body = {}
try:
self._session.git_root() # check for a git repository
except EnvironmentError:
print('No git repository found, use `git init` to create one')
sys.exit(1)
try:
self._session.get_app()
print('Deis remote already exists')
sys.exit(1)
except EnvironmentError:
pass
for opt in ('--id', '--formation'):
o = args.get(opt)
if o:
body.update({opt.strip('-'): o})
sys.stdout.write('Creating application... ')
sys.stdout.flush()
try:
progress = TextProgress()
progress.start()
response = self._dispatch('post', '/api/apps',
json.dumps(body))
finally:
progress.cancel()
progress.join()
if response.status_code == requests.codes.created: # @UndefinedVariable
data = response.json()
app_id = data['id']
print("done, created {}".format(app_id))
# add a git remote
hostname = urlparse.urlparse(self._settings['controller']).netloc.split(':')[0]
git_remote = "ssh://git@{hostname}:2222/{app_id}.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')
else:
raise ResponseError(response)
def apps_destroy(self, args):
"""
Destroy an application
Usage: deis apps:destroy [--app=<id> --confirm=<confirm>]
"""
app = args.get('--app')
if not app:
app = self._session.app
confirm = args.get('--confirm')
if confirm == app:
pass
else:
print("""
! WARNING: Potentially Destructive Action
! This command will destroy the application: {app}
! To proceed, type "{app}" or re-run this command with --confirm={app}
""".format(**locals()))
confirm = raw_input('> ').strip('\n')
if confirm != app:
print('Destroy aborted')
return
sys.stdout.write("Destroying {}... ".format(app))
sys.stdout.flush()
try:
progress = TextProgress()
progress.start()
before = time.time()
response = self._dispatch('delete', "/api/apps/{}".format(app))
finally:
progress.cancel()
progress.join()
if response.status_code in (requests.codes.no_content, # @UndefinedVariable
requests.codes.not_found): # @UndefinedVariable
print('done in {}s'.format(int(time.time() - before)))
# If the requested app is in the current dir, delete the git remote
try:
if app == self._session.app:
subprocess.check_call(
['git', 'remote', 'rm', 'deis'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print('Git remote deis removed')
except (EnvironmentError, subprocess.CalledProcessError):
pass # ignore error
else:
raise ResponseError(response)
def apps_list(self, args):
"""
List applications visible to the current user
Usage: deis apps:list
"""
response = self._dispatch('get', '/api/apps')
if response.status_code == requests.codes.ok: # @UndefinedVariable
data = response.json()
print('=== Apps')
for item in data['results']:
print('{id} {containers}'.format(**item))
else:
raise ResponseError(response)
def apps_info(self, args):
"""
Print info about the current application
Usage: deis apps:info [--app=<app>]
"""
app = args.get('--app')
if not app:
app = self._session.app
response = self._dispatch('get', "/api/apps/{}".format(app))
if response.status_code == requests.codes.ok: # @UndefinedVariable
print("=== {} Application".format(app))
print(json.dumps(response.json(), indent=2))
print()
self.containers_list(args)
print()
else:
raise ResponseError(response)
def apps_open(self, args):
"""
Open a URL to the application in a browser
Usage: deis apps:open [--app=<app>]
"""
app = args.get('--app')
if not app:
app = self._session.app
# TODO: replace with a proxy lookup that doesn't have any side effects
# this currently recalculates and updates the databag
response = self._dispatch('post',
"/api/apps/{}/calculate".format(app))
if response.status_code == requests.codes.ok: # @UndefinedVariable
databag = json.loads(response.content)
domains = databag.get('domains', [])
if domains:
domain = random.choice(domains)
# use the OS's default handler to open this URL
webbrowser.open('http://{}/'.format(domain))
return domain
else:
print('No proxies found. Use `deis nodes:scale myformation proxy=1` to scale up.')
else:
raise ResponseError(response)
def apps_logs(self, args):
"""
Retrieve the most recent log events
Usage: deis apps:logs [--app=<app>]
"""
app = args.get('--app')
if not app:
app = self._session.app
response = self._dispatch('post',
"/api/apps/{}/logs".format(app))
if response.status_code == requests.codes.ok: # @UndefinedVariable
print(response.json())
else:
raise ResponseError(response)
def apps_run(self, args):
"""
Run a command inside an ephemeral app container
Usage: deis apps:run <command>...
"""
app = self._session.app
body = {'command': ' '.join(sys.argv[2:])}
response = self._dispatch('post',
"/api/apps/{}/run".format(app),
json.dumps(body))
if response.status_code == requests.codes.ok: # @UndefinedVariable
output, rc = json.loads(response.content)
if rc != 0:
print('Warning: non-zero return code {}'.format(rc))
sys.stdout.write(output)
sys.stdout.flush()
else:
raise ResponseError(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>']
if not urlparse.urlparse(controller).scheme:
controller = "http://{}".format(controller)
username = args.get('--username')
if not username:
username = raw_input('username: ')
password = args.get('--password')
if not password:
password = getpass('password: ')
confirm = getpass('password (confirm): ')
if password != confirm:
print('Password mismatch, aborting registration.')
return False
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')
else:
print('Registration failed', response.content)
return False
return True
def auth_cancel(self, args):
"""
Cancel and remove the current account.
Usage: deis auth:cancel
"""
controller = self._settings.get('controller')
if not controller:
print('Not logged in to a Deis controller')
return False
print('Please log in again in order to cancel this account')
username = self.auth_login({'<controller>': controller})
if username:
confirm = raw_input("Cancel account \"{}\" at {}? (y/n) ".format(username, controller))
if confirm == 'y':
self._dispatch('delete', '/api/auth/cancel')
self._session.cookies.clear()
self._session.cookies.save()
self._settings['controller'] = None
self._settings.save()
print('Account cancelled')
else:
print('Accont not changed')
def auth_login(self, args):
"""
Login by authenticating against a controller
Usage: deis auth:login <controller> [--username=<username> --password=<password>]
"""
controller = args['<controller>']
if not urlparse.urlparse(controller).scheme:
controller = "http://{}".format(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 username
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_list(self, args):
"""
List build history for a formation
Usage: deis builds:list [--app=<app>]
"""
app = args.get('--app')
if not app:
app = self._session.app
response = self._dispatch('get', "/api/apps/{}/builds".format(app))
if response.status_code == requests.codes.ok: # @UndefinedVariable
print("=== {} Builds".format(app))
data = response.json()
for item in data['results']:
print("{0[uuid]:<23} {0[created]}".format(item))
else:
raise ResponseError(response)
def config(self, args):
"""
Valid commands for config:
config:list list environment variables for an app
config:set set environment variables for an app
config:unset unset environment variables for an app
Use `deis help [command]` to learn more
"""
sys.argv[1] = 'config:list'
args = docopt(self.config_list.__doc__)
return self.config_list(args)
def config_list(self, args):
"""
List environment variables for an application
Usage: deis config:list [--oneline] [--app=<app>]
"""
app = args.get('--app')
if not app:
app = self._session.app
oneline = args.get('--oneline')
response = self._dispatch('get', "/api/apps/{}/config".format(app))
if response.status_code == requests.codes.ok: # @UndefinedVariable
config = response.json()
values = json.loads(config['values'])
print("=== {} Config".format(app))
items = values.items()
if len(items) == 0:
print('No configuration')
return
keys = sorted(values)
if not oneline:
width = max(map(len, keys)) + 5
for k in keys:
v = values[k]
print(("{k:<" + str(width) + "} {v}").format(**locals()))
else:
output = []
for k in keys:
v = values[k]
output.append("{k}={v}".format(**locals()))
print(' '.join(output))
else:
raise ResponseError(response)
def config_set(self, args):
"""
Set environment variables for an application
Usage: deis config:set <var>=<value>... [--app=<app>]
"""
app = args.get('--app')
if not app:
app = self._session.app
body = {'values': json.dumps(dictify(args['<var>=<value>']))}
response = self._dispatch('post',
"/api/apps/{}/config".format(app),
json.dumps(body))
if response.status_code == requests.codes.created: # @UndefinedVariable
config = response.json()
values = json.loads(config['values'])
print("=== {}".format(app))
items = values.items()
if len(items) == 0:
print('No configuration')
return
for k, v in values.items():
print("{k}: {v}".format(**locals()))
else:
raise ResponseError(response)
def config_unset(self, args):
"""
Unset an environment variable for an application
Usage: deis config:unset <key>... [--app=<app>]
"""
app = args.get('--app')
if not app:
app = self._session.app
values = {}
for k in args.get('<key>'):
values[k] = None
body = {'values': json.dumps(values)}
response = self._dispatch('post',
"/api/apps/{}/config".format(app),
json.dumps(body))
if response.status_code == requests.codes.created: # @UndefinedVariable
config = response.json()
values = json.loads(config['values'])
print("=== {}".format(app))
items = values.items()
if len(items) == 0:
print('No configuration')
return
for k, v in values.items():
print("{k}: {v}".format(**locals()))
else:
raise ResponseError(response)
def containers(self, args):
"""
Valid commands for containers:
containers:list list application containers
containers:scale scale app containers (e.g. web=4 worker=2)
Use `deis help [command]` to learn more
"""
sys.argv[1] = 'containers:list'
args = docopt(self.containers_list.__doc__)
return self.containers_list(args)
def containers_list(self, args, app=None):
"""
List containers servicing an application
Usage: deis containers:list [--app=<app>]
"""
if not app:
app = args.get('--app')
if not app:
app = self._session.get_app()
response = self._dispatch('get',
"/api/apps/{}/containers".format(app))
if response.status_code != requests.codes.ok: # @UndefinedVariable
raise ResponseError(response)
containers = response.json()
response = self._dispatch('get', "/api/apps/{}/builds".format(app))
if response.status_code != requests.codes.ok: # @UndefinedVariable
raise ResponseError(response)
txt = response.json()['results'][0]['procfile']
procfile = json.loads(txt) if txt else {}
print("=== {} Containers".format(app))
c_map = {}
for item in containers['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()
def containers_scale(self, args):
"""
Scale an application's containers by type
Example: deis containers:scale web=4 worker=2
Usage: deis containers:scale <type=num>... [--app=<app>]
"""
app = args.get('--app')
if not app:
app = self._session.get_app()
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!')
try:
progress = TextProgress()
progress.start()
before = time.time()
response = self._dispatch('post',
"/api/apps/{}/scale".format(app),
json.dumps(body))
finally:
progress.cancel()
progress.join()
if response.status_code == requests.codes.ok: # @UndefinedVariable
print('done in {}s\n'.format(int(time.time() - before)))
self.containers_list({}, app)
else:
raise ResponseError(response)
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:update update an existing node flavor
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> --provider=<provider> --params=<params>
"""
body = {'id': args.get('<id>'), 'provider': args.get('--provider'),
'params': args.get('--params', json.dumps({}))}
response = self._dispatch('post', '/api/flavors', json.dumps(body))
if response.status_code == requests.codes.created: # @UndefinedVariable
print("{0[id]}".format(response.json()))
else:
raise ResponseError(response)
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)