-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathdeis.py
More file actions
executable file
·2115 lines (1851 loc) · 71 KB
/
deis.py
File metadata and controls
executable file
·2115 lines (1851 loc) · 71 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
"""
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::
apps manage applications used to provide services
ps manage processes inside an app container
config manage environment variables that define app config
domains manage and assign domain names to your applications
builds manage builds created using `git push`
limits manage resource limits for your application
tags manage tags for application containers
releases manage releases of an application
keys manage ssh keys used for `git push` deployments
perms manage permissions for applications
Shortcut commands, use ``deis shortcuts`` to see all::
create create a new application
scale scale processes 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
pull imports an image and deploys as a new release
Use ``git push deis master`` to deploy to an application.
"""
from __future__ import print_function
from collections import namedtuple
from collections import OrderedDict
from datetime import datetime
from getpass import getpass
from itertools import cycle
from threading import Event
from threading import Thread
import base64
import glob
import json
import locale
import logging
import os.path
import re
import subprocess
import sys
import time
import urlparse
import webbrowser
import yaml
from dateutil import parser
from dateutil import relativedelta
from dateutil import tz
from docopt import docopt
from docopt import DocoptExit
import requests
from termcolor import colored
__version__ = '1.2.0-dev'
# what version of the API is this client compatible with?
__api_version__ = '1.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
config_dir = os.path.expanduser('~/.deis')
self.proxies = {
"http": os.getenv("http_proxy"),
"https": os.getenv("https_proxy")
}
# Create the $HOME/.deis dir if it doesn't exist
if not os.path.isdir(config_dir):
os.mkdir(config_dir, 0700)
@property
def app(self):
"""Retrieve the application's name."""
try:
return self._get_name_from_git_remote(self.git_root()).lower()
except EnvironmentError:
return os.path.basename(os.getcwd()).lower()
def is_git_app(self):
"""Determines if this app is a git repository. This is important in special cases
where we need to know whether or not we should use Deis' automatic app name
generator, for example.
"""
try:
self.git_root()
return True
except EnvironmentError:
return False
def git_root(self):
"""
Returns the absolute path from the git repository root.
If no git repository exists, raises 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_name_from_git_remote(self, git_root):
"""
Retrieves the application name from a git repository root.
The application is determined by parsing `git remote -v` output.
If no application is found, raises an EnvironmentError.
"""
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']
def request(self, *args, **kwargs):
"""
Issue an HTTP request
"""
url = args[1]
if 'headers' in kwargs:
kwargs['headers']['Referer'] = url
else:
kwargs['headers'] = {'Referer': url}
response = super(Session, self).request(*args, **kwargs)
return response
class Settings(dict):
"""
Settings backed by a file in the user's home directory
On init, settings are loaded from ~/.deis/client.json
"""
def __init__(self):
path = os.path.expanduser('~/.deis')
# Create the $HOME/.deis dir if it doesn't exist
if not os.path.isdir(path):
os.mkdir(path, 0700)
self._path = os.path.join(path, 'client.json')
if not os.path.exists(self._path):
settings = {}
# try once to convert the old settings file if it exists
# FIXME: this code can be removed in November 2014 or thereabouts, that's long enough.
old_path = os.path.join(path, 'client.yaml')
if os.path.exists(old_path):
try:
with open(old_path, 'r') as f:
txt = f.read().replace('{', '{"', 1).replace(':', '":', 1).replace("'", '"')
settings = json.loads(txt)
os.remove(old_path)
except:
pass # ignore errors, at least we tried to convert it
with open(self._path, 'w') as f:
json.dump(settings, f)
# 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 = json.loads(data)
self.update(settings)
return settings
def save(self):
"""
Serialize and save settings to the filesystem
"""
data = json.dumps(dict(self))
try:
with open(self._path, 'w') as f:
f.write(data)
except IOError:
logging.getLogger(__name__).error("Could not write to settings file at \
'~/.deis/client.json' Do you have the right file permissions?")
sys.exit(1)
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 encode(obj):
"""Return UTF-8 encoding for string objects."""
if isinstance(obj, basestring):
return obj.encode('utf-8')
else:
return obj
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()
self._logger = logging.getLogger(__name__)
def _dispatch(self, method, path, body=None, **kwargs):
"""
Dispatch an API request to the active Deis controller
"""
func = getattr(self._session, method.lower())
controller = self._settings.get('controller')
token = self._settings.get('token')
if not token:
raise EnvironmentError(
'Could not find token. Use `deis login` or `deis register` to get started.')
url = urlparse.urljoin(controller, path, **kwargs)
headers = {
'content-type': 'application/json',
'X-Deis-Version': __api_version__.rsplit('.', 1)[0],
'Authorization': 'token {}'.format(token)
}
response = func(url, data=body, headers=headers)
# check for version mismatch
server_api_version = response.headers.get('X_DEIS_API_VERSION')
if server_api_version is not None and server_api_version != __api_version__:
self._logger.warning("""
! WARNING: Client and server API versions do not match. Please consider upgrading.
! Client version: {}
! Server version: {}
""".format(__api_version__, server_api_version))
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.
"""
sys.argv[1] = 'apps:list'
args = docopt(self.apps_list.__doc__)
return self.apps_list(args)
def apps_create(self, args):
"""
Creates a new application.
- if no <id> is provided, one will be generated automatically.
Usage: deis apps:create [<id>] [options]
Arguments:
<id>
a uniquely identifiable name for the application. No other app can already
exist with this name.
Options:
--no-remote
do not create a `deis` git remote.
-b --buildpack BUILDPACK
a buildpack url to use for this app
"""
body = {}
app_name = None
if not self._session.is_git_app():
app_name = self._session.app
# prevent app name from being reset to None
if args.get('<id>'):
app_name = args.get('<id>')
if app_name:
body.update({'id': app_name})
sys.stdout.write('Creating application... ')
sys.stdout.flush()
try:
progress = TextProgress()
progress.start()
response = self._dispatch('post', '/v1/apps',
json.dumps(body))
finally:
progress.cancel()
progress.join()
if response.status_code != requests.codes.created:
raise ResponseError(response)
data = response.json()
app_id = data['id']
self._logger.info("done, created {}".format(app_id))
buildpack = args.get('--buildpack')
if buildpack:
self._config_set(app_id, {'BUILDPACK_URL': buildpack})
# set a git remote if necessary
try:
self._session.git_root()
except EnvironmentError:
return
hostname = urlparse.urlparse(self._settings['controller']).netloc.split(':')[0]
git_remote = "ssh://git@{hostname}:2222/{app_id}.git".format(**locals())
if args.get('--no-remote'):
self._logger.info('remote available at {}'.format(git_remote))
else:
try:
subprocess.check_call(
['git', 'remote', 'add', '-f', 'deis', git_remote],
stdout=subprocess.PIPE)
self._logger.info('Git remote deis added')
except subprocess.CalledProcessError:
self._logger.error('Could not create Deis remote')
sys.exit(1)
def apps_destroy(self, args):
"""
Destroys an application.
Usage: deis apps:destroy [options]
Options:
-a --app=<app>
the uniquely identifiable name for the application.
--confirm=<app>
skips the prompt for the application name. <app> is the uniquely identifiable
name for the application.
"""
app = args.get('--app')
delete_remote = False
if not app:
app = self._session.app
delete_remote = True
confirm = args.get('--confirm')
if confirm == app:
pass
else:
self._logger.warning("""
! 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:
self._logger.info('Destroy aborted')
return
self._logger.info("Destroying {}... ".format(app))
try:
progress = TextProgress()
progress.start()
before = time.time()
response = self._dispatch('delete', "/v1/apps/{}".format(app))
finally:
progress.cancel()
progress.join()
if response.status_code in (requests.codes.no_content,
requests.codes.not_found):
self._logger.info('done in {}s'.format(int(time.time() - before)))
try:
# If the requested app is a heroku app and the app
# was inferred from session, delete the git remote
if self._session.is_git_app() and delete_remote:
subprocess.check_call(
['git', 'remote', 'rm', 'deis'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self._logger.info('Git remote deis removed')
except (EnvironmentError, subprocess.CalledProcessError):
pass # ignore error
else:
raise ResponseError(response)
def apps_list(self, args):
"""
Lists applications visible to the current user.
Usage: deis apps:list
"""
response = self._dispatch('get', '/v1/apps')
if response.status_code == requests.codes.ok:
data = response.json()
self._logger.info('=== Apps')
for item in data['results']:
self._logger.info('{id}'.format(**item))
else:
raise ResponseError(response)
def apps_info(self, args):
"""
Prints info about the current application.
Usage: deis apps:info [options]
Options:
-a --app=<app>
the uniquely identifiable name for the application.
"""
app = args.get('--app')
if not app:
app = self._session.app
response = self._dispatch('get', "/v1/apps/{}".format(app))
if response.status_code == requests.codes.ok:
self._logger.info("=== {} Application".format(app))
self._logger.info(json.dumps(response.json(), indent=2) + '\n')
self.ps_list(args)
self.domains_list(args)
self._logger.info('')
else:
raise ResponseError(response)
def apps_open(self, args):
"""
Opens a URL to the application in the default browser.
Usage: deis apps:open [options]
Options:
-a --app=<app>
the uniquely identifiable name for the application.
"""
app = args.get('--app')
if not app:
app = self._session.app
# TODO: replace with a single API call to apps endpoint
response = self._dispatch('get', "/v1/apps/{}".format(app))
if response.status_code == requests.codes.ok:
url = response.json()['url']
# use the OS's default handler to open this URL
webbrowser.open('http://{}/'.format(url))
return url
else:
raise ResponseError(response)
def apps_logs(self, args):
"""
Retrieves the most recent log events.
Usage: deis apps:logs [options]
Options:
-a --app=<app>
the uniquely identifiable name for the application.
"""
app = args.get('--app')
if not app:
app = self._session.app
response = self._dispatch('get',
"/v1/apps/{}/logs".format(app))
if response.status_code == requests.codes.ok:
# strip the last newline character
for line in response.json().split('\n')[:-1]:
# get the tag from the log
try:
log_tag = line.split(': ')[0].split(' ')[1]
# colorize the log based on the tag
color = sum([ord(ch) for ch in log_tag]) % 6
def f(x):
return {
0: 'green',
1: 'cyan',
2: 'red',
3: 'yellow',
4: 'blue',
5: 'magenta',
}.get(x, 'magenta')
self._logger.info(colored(line, f(color)))
except IndexError:
self._logger.info(line)
else:
raise ResponseError(response)
def apps_run(self, args):
"""
Runs a command inside an ephemeral app container. Default environment is
/bin/bash.
Usage: deis apps:run [options] [--] <command>...
Arguments:
<command>
the shell command to run inside the container.
Options:
-a --app=<app>
the uniquely identifiable name for the application.
"""
command = ' '.join(args.get('<command>'))
self._logger.info('Running `{}`...'.format(command))
app = args.get('--app')
if not app:
app = self._session.app
body = {'command': command}
response = self._dispatch('post',
"/v1/apps/{}/run".format(app),
json.dumps(body))
if response.status_code == requests.codes.ok:
rc, output = json.loads(response.content)
sys.stdout.write(encode(output))
sys.stdout.flush()
sys.exit(rc)
else:
raise ResponseError(response)
def auth(self, args):
"""
Valid commands for auth:
auth:register register a new user
auth:login authenticate against a controller
auth:logout clear the current user session
auth:passwd change the password for the current user
auth:whoami display the current user
auth:cancel remove the current user account
Use `deis help [command]` to learn more.
"""
return
def auth_register(self, args):
"""
Registers a new user with a Deis controller.
Usage: deis auth:register <controller> [options]
Arguments:
<controller>
fully-qualified controller URI, e.g. `http://deis.local.deisapp.com/`
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:
self._logger.error('Password mismatch, aborting registration.')
sys.exit(1)
email = args.get('--email')
if not email:
email = raw_input('email: ')
url = urlparse.urljoin(controller, '/v1/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:
self._settings['controller'] = controller
self._settings.save()
self._logger.info("Registered {}".format(username))
login_args = {'--username': username, '--password': password,
'<controller>': controller}
if self.auth_login(login_args) is False:
self._logger.info('Login failed')
else:
self._logger.info('Registration failed: ' + response.content)
sys.exit(1)
return True
def auth_cancel(self, args):
"""
Cancels and removes the current account.
Usage: deis auth:cancel
"""
controller = self._settings.get('controller')
if not controller:
self._logger.error('Not logged in to a Deis controller')
sys.exit(1)
self._logger.info('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', '/v1/auth/cancel')
self._settings['controller'] = None
self._settings['token'] = None
self._settings.save()
self._logger.info('Account cancelled')
else:
self._logger.info('Account not changed')
def auth_login(self, args):
"""
Logs in by authenticating against a controller.
Usage: deis auth:login <controller> [options]
Arguments:
<controller>
a fully-qualified controller URI, e.g. `http://deis.local.deisapp.com/`.
Options:
--username=<username>
provide a username for the account.
--password=<password>
provide a password for the account.
"""
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, '/v1/auth/login/')
payload = {'username': username, 'password': password}
# post credentials to the login URL
response = self._session.post(url, data=payload, allow_redirects=False)
if response.status_code == requests.codes.ok:
# retrieve and save the API token for future requests
self._settings['controller'] = controller
self._settings['username'] = username
self._settings['token'] = response.json()['token']
self._settings.save()
self._logger.info("Logged in as {}".format(username))
return username
else:
raise ResponseError(response)
def auth_logout(self, args):
"""
Logs out from a controller and clears the user session.
Usage: deis auth:logout
"""
self._settings['controller'] = None
self._settings['username'] = None
self._settings['token'] = None
self._settings.save()
self._logger.info('Logged out')
def auth_passwd(self, args):
"""
Changes the password for the current user.
Usage: deis auth:passwd [options]
Options:
--password=<password>
provide the current password for the account.
--new-password=<new-password>
provide a new password for the account.
"""
if not self._settings.get('token'):
raise EnvironmentError(
'Could not find token. Use `deis login` or `deis register` to get started.')
password = args.get('--password')
if not password:
password = getpass('current password: ')
new_password = args.get('--new-password')
if not new_password:
new_password = getpass('new password: ')
confirm = getpass('new password (confirm): ')
if new_password != confirm:
self._logger.error('Password mismatch, not changing.')
sys.exit(1)
payload = {'password': password, 'new_password': new_password}
response = self._dispatch('post', "/v1/auth/passwd", json.dumps(payload))
if response.status_code == requests.codes.ok:
self._logger.info('Password change succeeded.')
else:
self._logger.info("Password change failed: {}".format(response.text))
sys.exit(1)
return True
def auth_whoami(self, args):
"""
Displays the currently logged in user.
Usage: deis auth:whoami
"""
user = self._settings.get('username')
if user:
self._logger.info(user)
else:
self._logger.info(
'Not logged in. Use `deis login` or `deis register` to get started.')
def builds(self, args):
"""
Valid commands for builds:
builds:list list build history for an application
builds:create imports an image and deploys as a new release
Use `deis help [command]` to learn more.
"""
sys.argv[1] = 'builds:list'
args = docopt(self.builds_list.__doc__)
return self.builds_list(args)
def builds_create(self, args):
"""
Creates a new build of an application. Imports an <image> and deploys it to Deis
as a new release. If a Procfile is present in the current directory, it will be used
as the default process types for this application.
Usage: deis builds:create <image> [options]
Arguments:
<image>
A fully-qualified docker image, either from Docker Hub (e.g. deis/example-go)
or from an in-house registry (e.g. myregistry.example.com:5000/example-go).
Options:
-a --app=<app>
The uniquely identifiable name for the application.
-p --procfile=<procfile>
A YAML string used to supply a Procfile to the application.
"""
app = args.get('--app')
if not app:
app = self._session.app
body = {'image': args['<image>']}
procfile = args.get('--procfile')
if procfile:
try:
body['procfile'] = yaml.load(procfile)
except yaml.YAMLError:
self._logger.error('could not parse --procfile')
sys.exit(1)
else:
# read in Procfile for default process types
if os.path.exists('Procfile'):
try:
body['procfile'] = yaml.load(open('Procfile'))
except yaml.YAMLError:
self._logger.error('could not parse Procfile')
sys.exit(1)
sys.stdout.write('Creating build... ')
sys.stdout.flush()
try:
progress = TextProgress()
progress.start()
response = self._dispatch('post', "/v1/apps/{}/builds".format(app), json.dumps(body))
finally:
progress.cancel()
progress.join()
if response.status_code == requests.codes.created:
version = response.headers['x-deis-release']
self._logger.info("done, v{}".format(version))
else:
raise ResponseError(response)
def builds_list(self, args):
"""
Lists build history for an application.
Usage: deis builds:list [options]
Options:
-a --app=<app>
the uniquely identifiable name for the application.
"""
app = args.get('--app')
if not app:
app = self._session.app
response = self._dispatch('get', "/v1/apps/{}/builds".format(app))
if response.status_code == requests.codes.ok:
self._logger.info("=== {} Builds".format(app))
data = response.json()
for item in data['results']:
self._logger.info("{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
config:pull extract environment variables to .env
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):
"""
Lists environment variables for an application.
Usage: deis config:list [options]
Options:
--oneline
print output on one line.
-a --app=<app>
the uniquely identifiable name of the application.
"""
app = args.get('--app')
if not app:
app = self._session.app
oneline = args.get('--oneline')
response = self._dispatch('get', "/v1/apps/{}/config".format(app))
if response.status_code == requests.codes.ok:
config = response.json()