-
Notifications
You must be signed in to change notification settings - Fork 15
/
app.py
1207 lines (1050 loc) · 42.7 KB
/
app.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
# -*- coding: utf-8 -*-
"""
Copyright 2010 cloudControl UG (haftungsbeschraenkt)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __builtin__ import raw_input, str, filter, float, len
import exceptions
import os
import time
import re
import subprocess
import shlex
import webbrowser
import math
import sys
import urlparse
from settings import CONFIG_ADDON
from datetime import datetime, timedelta
from pycclib.cclib import GoneError, ForbiddenError, TokenRequiredError, \
BadRequestError, ConflictDuplicateError, UnauthorizedError, \
NotImplementedError, ThrottledError
from subprocess import check_call, CalledProcessError
from cctrl.error import InputErrorException, messages
from cctrl.oshelpers import check_installed_rcs, is_buildpack_url_valid, \
ssh_cmd, check_output
from cctrl.output import print_deployment_details, print_app_details,\
print_alias_details, print_log_entries, print_list_apps,\
print_addon_details, print_addons, print_addon_list, print_alias_list, \
print_worker_list, print_worker_details, print_cronjob_list, \
print_cronjob_details, print_addon_creds, print_config
from output import print_user_list_app, print_user_list_deployment
from cctrl.addonoptionhelpers import parse_additional_addon_options, \
parse_config_variables, extract_flag_from_variables
class AppsController():
"""
This controller handles the special case where you want to get a
list of applications.
"""
api = None
def __init__(self, api):
self.api = api
def list(self): # @ReservedAssignment
apps = self.api.read_apps()
print_list_apps(apps)
class CVSType():
"""
A simple class for both supported repository types.
"""
GIT = 'git'
BZR = 'bzr'
@staticmethod
def by_path(application_path):
"""
Provides the cvs (repo) type by checking if given directory
contains a ".git" or ".bzr" configuration directory.
"""
for (dirname, cvstype, msg) in [(".git", CVSType.GIT, 'GitConfigFound'),
(".bzr", CVSType.BZR, 'BazaarConfigFound')]:
if os.path.exists(os.path.join(application_path, dirname)):
return (cvstype, msg)
return (None, None)
@staticmethod
def by_env():
"""
Provides the cvs (repo) type by checking environment variable
PATH for existence of either Bazaar or Git.
"""
for (execname, cvstype, msg) in [('git', CVSType.GIT, 'GitExecutableFound'),
('bzr', CVSType.BZR, 'BazaarExecutableFound')]:
if check_installed_rcs(execname):
return (cvstype, msg)
return (None, None)
class AppController():
"""
After parsing the command line in parse_cmdline() the related
method of the ApplicationController gets called. Each method uses
pycclib to fire a request and handles the response showing it to the
user if needed.
"""
def __init__(self, api, settings):
self.api = api
self.settings = settings
def run_cmd(self, args):
try:
app_name, deployment_name = self.parse_app_deployment_name(args.name)
except ParseAppDeploymentName:
raise InputErrorException('InvalidApplicationName')
if not deployment_name:
deployment_name = 'default'
user_host = '{app}-{dep}@{host}'.format(app=app_name, dep=deployment_name, host=self.settings.ssh_forwarder)
# Refresh our token before sending it to the forwarder.
try:
self.api.read_deployment(app_name, deployment_name)
except GoneError:
raise InputErrorException('WrongApplication')
env = 'TOKEN={token}'.format(token=self.api.get_token()['token'])
if len(args.command) > 0:
command = '{env} {command}'.format(env=env, command=args.command)
else:
raise InputErrorException('NoRunCommandGiven')
sshopts = shlex.split(os.environ.get('CCTRL_SSHOPTS', ''))
ssh_command = ['ssh', '-t'] + sshopts + ['-p', self.settings.ssh_forwarder_port, '--', user_host, command]
subprocess.call(ssh_command)
def rollback_cmd(self, args):
"""
Rollback command
"""
try:
app_name, deployment_name = self.parse_app_deployment_name(args.name)
except ParseAppDeploymentName:
raise InputErrorException('InvalidApplicationName')
if not deployment_name:
deployment_name = 'default'
logEntries = []
try:
logEntries = self.api.read_log(
app_name,
deployment_name,
'deploy',
last_time=None)
except GoneError:
raise InputErrorException('WrongApplication')
deployments = [e['message'].split(':')[1].strip() for e in logEntries
if 'Deployed version' in e['message']]
try:
current_deployment = deployments.pop()
except IndexError:
raise InputErrorException('NoPreviousVersionFound')
previous_deployment = None
while not previous_deployment:
try:
deployment_version = deployments.pop()
if deployment_version != current_deployment:
previous_deployment = deployment_version
except IndexError:
raise InputErrorException('NoPreviousVersionFound')
try:
self.api.update_deployment(
app_name,
version=previous_deployment,
deployment_name=deployment_name)
except GoneError:
raise InputErrorException('WrongApplication')
except ForbiddenError:
raise InputErrorException('NotAllowed')
def create(self, args):
"""
Creates a new application.
"""
try:
app_name, deployment_name = self.parse_app_deployment_name(args.name)
except ParseAppDeploymentName:
raise InputErrorException('InvalidApplicationName')
if args.buildpack:
# Did the user choose a default app type and provided a buildpack url?
if not args.type == 'custom':
raise InputErrorException('NoCustomApp')
# Did the user provide a valid buildpack URL?
elif not is_buildpack_url_valid(args.buildpack):
raise InputErrorException('NoValidBuildpackURL')
# Did the user provide a buildpack url if app has a custom type?
elif args.type == 'custom':
raise InputErrorException('NoBuildpackURL')
# Did the user provide the repo type as argument?
if args.repo:
repo_type = args.repo
detection_method = None
else:
# No, he/she didn't! Then check if current directory is an app and already has a CVS type ...
(repo_type, detection_method) = CVSType.by_path(os.getcwd())
if repo_type is None:
# Hmm, current directory was nothing. Let's check if either 'bzr' or 'git' is installed ...
(repo_type, detection_method) = CVSType.by_env()
if repo_type is None:
# Hmm, also nothing installed! Ok, we give up and set default = GIT and hope for better times ...
detection_method = 'CreatingAppAsDefaultRepoType'
repo_type = CVSType.GIT
try:
self.api.create_app(app_name, args.type, repo_type, args.buildpack)
self.api.create_deployment(
app_name,
deployment_name=deployment_name)
if detection_method:
print messages[detection_method]
except GoneError:
raise InputErrorException('WrongApplication')
except ForbiddenError:
raise InputErrorException('NotAllowed')
else:
return True
def delete(self, args):
"""
Delete an application. If we wouldn't check the token here it could
happen that we ask the user for confirmation and then fire the api
request. If the token wasn't valid this would result in a
TokenRequiredError being raised and after getting the credentials
and creating a token this method would be called a second time.
This would result in asking the user two times if he really wants
to delete the app which is a rather bad user experience.
"""
if self.api.check_token():
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not self.does_app_exist(app_name):
raise InputErrorException('WrongApplication')
if deployment_name:
raise InputErrorException('DeleteOnlyApplication')
if not args.force_delete:
question = raw_input("Do you really want to delete application '{0}'? ".format(app_name) +
'Type "Yes" without the quotes to delete: ')
else:
question = 'Yes'
if question.lower() == 'yes':
try:
self.api.delete_app(app_name)
except ForbiddenError:
raise InputErrorException('NotAllowed')
except BadRequestError:
raise InputErrorException('CannotDeleteDeploymentExist')
except GoneError:
raise InputErrorException('WrongApplication')
else:
print messages['SecurityQuestionDenied']
else:
raise TokenRequiredError
def _details(self, app_or_deployment_name):
app_name, deployment_name = self.parse_app_deployment_name(app_or_deployment_name)
if deployment_name:
try:
deployment = self.api.read_deployment(
app_name,
deployment_name)
try:
app_users = self.api.read_app_users(app_name)
except (UnauthorizedError, ForbiddenError, NotImplementedError):
# ok since possibly I am not allowed to see users at all
pass
else:
deployment['users'] = [
dict(au, app=True)
for au in app_users
] + deployment['users']
except GoneError:
raise InputErrorException('WrongDeployment')
else:
return app_name, deployment_name, deployment
else:
try:
app = self.api.read_app(app_name)
# only get deployment-users if i can see app-users
if len(app['users']):
try:
for deployment in app['deployments']:
appname, depname = self.parse_app_deployment_name(deployment['name'])
depusers = self.api.read_deployment_users(appname, depname)
app['users'].extend(
dict(du, deployment=depname)
for du in depusers
)
except (NotImplementedError, BadRequestError): # for old api-servers
pass
except GoneError:
raise InputErrorException('WrongApplication')
else:
return app_name, deployment_name, app
def details(self, args):
"""
Print application or deployment details.
e.g.:
'cctrlapp APP_NAME details' prints application details
'cctrlapp APP_NAME/DEP_NAME details' prints deployment details
"""
app_name, deployment_name, obj = self._details(args.name)
if deployment_name:
print_deployment_details(obj)
else:
public_key_content = self._get_public_key(app_name, obj)
print_app_details(obj, public_key_content)
def _get_deployment_url(self, obj):
return "http://{0}".format(obj.get('default_subdomain'))
def _get_repository_url(self, obj):
return urlparse.urlsplit(obj.get('repository')).netloc
def get_deployment_from_app_deployment_name(self, app_or_deployment_name):
app_name, deployment_name = self.parse_app_deployment_name(app_or_deployment_name)
if not deployment_name:
deployment_name = 'default'
try:
deployment = self.api.read_deployment(
app_name,
deployment_name)
except GoneError:
raise InputErrorException('WrongDeployment')
else:
return app_name, deployment_name, deployment
def _open(self, url):
savout = os.dup(1)
os.close(1)
os.open(os.devnull, os.O_RDWR)
try:
webbrowser.open_new_tab(url)
finally:
os.dup2(savout, 1)
def open(self, args):
"""
Open deployment URL on the default browser.
e.g.:
'cctrlapp APP_NAME open' opens the default deployment's URL
'cctrlapp APP_NAME/DEP_NAME open' opens the deployment's URL
"""
app_name, deployment_name, obj = self.get_deployment_from_app_deployment_name(args.name)
url = self._get_deployment_url(obj)
self._open(url)
def _get_size_from_memory(self, memory):
res = re.match(r'(\d+)(.*)', memory.lower())
if not res:
raise InputErrorException('InvalidMemory')
if res.group(2) in ['mb', 'm', '']:
size = float(res.group(1)) / 128
elif res.group(2) in ['gb', 'g']:
size = float(res.group(1)) * 2 ** 10 / 128
else:
raise InputErrorException('InvalidMemory')
final_size = int(math.ceil(size))
if final_size != size:
print >> sys.stderr, 'Memory size has to be a multiple of 128MB and has been rounded up to {0}MB.'.format(final_size * 128)
return final_size
def deploy(self, args):
"""
Deploy a distinct version.
Since we want to make it as easy as possible we first try to update
the default deployment and start the newest version of that if no
other arguments were passed at the command line.
"""
try:
app_name, deployment_name = self.parse_app_deployment_name(args.name)
except ParseAppDeploymentName:
raise InputErrorException('InvalidApplicationName')
if not deployment_name:
deployment_name = 'default'
if args.size:
size = args.size
if args.memory:
raise InputErrorException('AmbiguousSize')
elif args.memory:
memory = args.memory
size = self._get_size_from_memory(memory)
else:
size = None
try:
try:
self.api.update_deployment(
app_name,
version=args.version,
deployment_name=deployment_name,
min_boxes=args.containers,
max_boxes=size,
stack=args.stack)
except GoneError:
try:
self.api.create_deployment(
app_name,
deployment_name=deployment_name,
stack=args.stack)
self.api.update_deployment(
app_name,
version=args.version,
deployment_name=deployment_name,
min_boxes=args.containers,
max_boxes=size,
stack=args.stack)
except GoneError:
raise InputErrorException('WrongApplication')
except ForbiddenError:
raise InputErrorException('NotAllowed')
except BadRequestError as e:
if 'max_boxes_over_max_process_limit' in e.msgs:
if args.memory:
raise InputErrorException('InvalidMemory')
if args.size:
raise InputErrorException('InvalidSize')
else:
raise
if args.restart_workers:
deployment = {'state': 'unknown'}
while deployment['state'] != 'deployed':
time.sleep(1)
deployment = self.api.read_deployment(app_name, deployment_name)
self._restartWorkers(app_name, deployment_name)
return True
def redeploy(self, deployment):
"""
Redeploy an existing application with same options and configuration.
"""
try:
app_name, deployment_name = self.parse_app_deployment_name(deployment['name'])
self.api.update_deployment(
app_name,
version=-1,
deployment_name=deployment_name,
min_boxes=deployment['min_boxes'],
max_boxes=deployment['max_boxes'],
stack=deployment['stack']['name'])
except (KeyError, GoneError, BadRequestError):
raise InputErrorException('DeploymentFailed')
def undeploy(self, args):
"""
Undeploys the deployment, deletes the database and files.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not self.does_app_exist(app_name):
raise InputErrorException('WrongApplication')
if not args.force_delete:
question = raw_input("Do you really want to delete deployment '{0}'? ".format(args.name) +
'This will delete everything including files and the database. Type "Yes" without the quotes to delete: ')
else:
question = 'Yes'
if question.lower() == 'yes':
args.force_delete = True
try:
self.api.delete_deployment(app_name, deployment_name)
except GoneError:
raise InputErrorException('WrongDeployment')
else:
print messages['SecurityQuestionDenied']
return True
def addAlias(self, args):
"""
Adds the given alias to the deployment.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.alias:
raise InputErrorException('NoAliasGiven')
self.api.create_alias(app_name, args.alias, deployment_name)
return True
def showAlias(self, args):
"""
Shows the details of an alias.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.alias:
aliases = self.api.read_aliases(app_name, deployment_name)
print_alias_list(aliases)
return True
else:
try:
alias = self.api.read_alias(
app_name,
args.alias,
deployment_name)
except GoneError:
raise InputErrorException('WrongAlias')
else:
print_alias_details(alias)
return True
def removeAlias(self, args):
"""
Removes an alias form a deployment.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.alias:
raise InputErrorException('NoAliasGiven')
try:
self.api.delete_alias(app_name, args.alias, deployment_name)
except GoneError:
raise InputErrorException('WrongAlias')
return True
def addWorker(self, args):
"""
Adds the given worker to the deployment.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if args.size:
size = args.size
if args.memory:
raise InputErrorException('AmbiguousSize')
elif args.memory:
memory = args.memory
size = self._get_size_from_memory(memory)
else:
size = None
if not deployment_name:
deployment_name = 'default'
if not args.command:
raise InputErrorException('NoWorkerCommandGiven')
try:
self.api.create_worker(
app_name,
deployment_name,
args.command,
params=args.params,
size=size)
except BadRequestError as e:
if 'size' in e.msgs:
if args.memory:
raise InputErrorException('InvalidMemory')
if args.size:
raise InputErrorException('InvalidSize')
else:
raise
return True
def showWorker(self, args):
"""
Shows the details of an worker.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.wrk_id:
workers = (self.api.read_worker(app_name, deployment_name, worker['wrk_id']) for worker in self.api.read_workers(app_name, deployment_name))
print_worker_list(workers)
return True
else:
try:
worker = self.api.read_worker(
app_name,
deployment_name,
args.wrk_id)
except GoneError:
raise InputErrorException('WrongWorker')
else:
print_worker_details(worker)
return True
def removeWorker(self, args):
"""
Removes an worker form a deployment.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
try:
self.api.delete_worker(app_name, deployment_name, args.wrk_id)
except GoneError:
raise InputErrorException('WrongWorker')
return True
def _restartWorker(self, app_name, deployment_name, wrk_id, command, params, size):
self.api.delete_worker(app_name, deployment_name, wrk_id)
self.api.create_worker(
app_name,
deployment_name,
command,
params,
size)
def _restartWorkers(self, app_name, deployment_name):
workers = (self.api.read_worker(app_name, deployment_name, worker['wrk_id']) for worker in self.api.read_workers(app_name, deployment_name))
for worker in workers:
self._restartWorker(app_name, deployment_name, worker['wrk_id'], worker['command'], worker['params'], worker['size'])
def restartWorker(self, args):
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if args.wrk_id:
try:
worker = self.api.read_worker(app_name, deployment_name, args.wrk_id)
except GoneError:
raise InputErrorException('WrongWorker')
self._restartWorker(app_name, deployment_name, worker['wrk_id'], worker['command'], worker['params'], worker['size'])
return
if args.all:
self._restartWorkers(app_name, deployment_name)
def addCron(self, args):
"""
Adds the given worker to the deployment.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.url:
raise InputErrorException('NoCronURLGiven')
self.api.create_cronjob(
app_name,
deployment_name,
args.url)
return True
def showCron(self, args):
"""
Shows the details of an worker.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.job_id:
cronjobs = self.api.read_cronjobs(app_name, deployment_name)
print_cronjob_list(cronjobs)
return True
else:
try:
cronjob = self.api.read_cronjob(
app_name,
deployment_name,
args.job_id)
except GoneError:
raise InputErrorException('NoSuchCronJob')
else:
print_cronjob_details(cronjob)
return True
def removeCron(self, args):
"""
Removes an worker form a deployment.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
try:
self.api.delete_cronjob(app_name, deployment_name, args.job_id)
except GoneError:
raise InputErrorException('NoSuchCronJob')
return True
def _get_config_vars(self, app_name, deployment_name):
try:
addon = self.api.read_addon(app_name, deployment_name, CONFIG_ADDON)
return addon['settings']['CONFIG_VARS']
except (KeyError, GoneError):
return {}
def showConfig(self, args):
"""
Shows the config variables
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
config = self._get_config_vars(app_name, deployment_name)
if config:
print_config(config, args.key)
else:
print '[ERROR] No configuration variables for this deployment.'
return True
def addConfig(self, args):
"""
Adds the given variable and value to the config addon.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.variables:
raise InputErrorException('NoVariablesGiven')
args_variables, force = extract_flag_from_variables(args.variables,
('-f', '--force'),
args.force_add)
variables = parse_config_variables(args_variables, 'add')
try:
self.api.update_addon(
app_name,
deployment_name,
CONFIG_ADDON,
CONFIG_ADDON,
settings=variables,
force=force)
except GoneError:
# Add addon if it didn't exist.
self.api.create_addon(app_name, deployment_name, CONFIG_ADDON, variables)
except ThrottledError as te:
# Overwrite the variable if didn't force, but type Yes
question = raw_input('{0} Do you really want to overwrite it? '
'Type "Yes" without the quotes to proceed: '.format(te.message))
if question.lower() == 'yes':
self.api.update_addon(
app_name,
deployment_name,
CONFIG_ADDON,
CONFIG_ADDON,
settings=variables,
force=True)
return True
def removeConfig(self, args):
"""
Remove the given variable if it exists.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.variables:
raise InputErrorException('NoVariablesGiven')
variables = parse_config_variables(args.variables, 'remove')
try:
self.api.update_addon(
app_name,
deployment_name,
CONFIG_ADDON,
CONFIG_ADDON,
settings=variables)
except GoneError:
raise InputErrorException('WrongAddon')
return True
def listAddons(self, args):
"""
Returns a list of all available addons
"""
addons = self.api.read_addons()
print_addons(addons)
return True
def addAddon(self, args):
"""
Adds the given addon to the deployment.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.addon:
raise InputErrorException('NoAddonGiven')
options = None
if args.options:
options = parse_additional_addon_options(args.options)
try:
self.api.create_addon(app_name, deployment_name, args.addon, options)
except ConflictDuplicateError:
raise InputErrorException('DuplicateAddon')
except BadRequestError as e:
if 'This is not a valid addon name' in str(e):
raise InputErrorException('InvalidAddon')
raise
except ForbiddenError:
raise InputErrorException('ForbiddenAddon')
return True
def showAddon(self, args):
"""
Shows the details of an addon.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.addon:
try:
addons = self.api.read_addons(app_name, deployment_name)
except:
raise
else:
print_addon_list(addons)
return True
else:
try:
addon = self.api.read_addon(
app_name,
deployment_name,
args.addon)
except GoneError:
raise InputErrorException('WrongAddon')
else:
print_addon_details(addon)
return True
def showAddonCreds(self, args):
"""
Print the creds.json of all Add-ons
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.addon:
try:
addons = self.api.read_addons(app_name, deployment_name)
except:
raise
else:
print_addon_creds(addons)
return True
else:
try:
addon = self.api.read_addon(
app_name,
deployment_name,
args.addon)
except GoneError:
raise InputErrorException('WrongAddon')
else:
print_addon_creds([addon])
return True
def updateAddon(self, args):
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
try:
self.api.update_addon(
app_name,
deployment_name,
args.addon_old,
args.addon_new)
except GoneError:
raise InputErrorException('WrongAddon')
else:
return True
def removeAddon(self, args):
"""
Removes an addon form a deployment.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
if not args.addon:
raise InputErrorException('NoAddonGiven')
try:
self.api.delete_addon(app_name, deployment_name, args.addon)
except GoneError:
raise InputErrorException('WrongAddon')
return True
def showUser(self, args):
"""
List users
"""
app_name, deployment_name, obj = self._details(args.name)
if deployment_name:
print_user_list_deployment(obj)
else:
print_user_list_app(obj)
return True
def addUser(self, args):
"""
Add a user specified by the e-mail address to an application or deployment.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if self.settings.prefix_project_name:
if len(args.email.split(':')) != 2:
prefix = self.api.read_users()[0]['email'].split(':')[0]
args.email = '{0}:{1}'.format(prefix, args.email)
try:
if deployment_name:
self.api.create_deployment_user(app_name, deployment_name, args.email, args.role)
else:
self.api.create_app_user(app_name, args.email, args.role)
except ConflictDuplicateError:
raise InputErrorException('UserBelongsToApp')
except NotImplementedError:
raise InputErrorException('CommandNotImplemented')
return True
def removeUser(self, args):
"""
Remove a user specified by the user name or email address from an application or deployment.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if '@' in args.username:
if deployment_name:
users = self.api.read_deployment_users(app_name, deployment_name)
else:
users = self.api.read_app(app_name)['users']
try:
username = [user['username'] for user in users
if user['email'] == args.username][0]
except IndexError:
raise InputErrorException('RemoveUserGoneError')
else:
username = args.username
try:
if deployment_name:
self.api.delete_deployment_user(app_name, deployment_name,
username)
else:
self.api.delete_app_user(app_name, username)
except GoneError:
raise InputErrorException('RemoveUserGoneError')
except NotImplementedError:
raise InputErrorException('CommandNotImplemented')
return True
def log(self, args):
"""
Show the log.
"""
app_name, deployment_name = self.parse_app_deployment_name(args.name)
if not deployment_name:
deployment_name = 'default'
last_time = None
while True:
logEntries = []
try:
logEntries = self.api.read_log(
app_name,
deployment_name,
args.type,