Skip to content

Commit 1e717e5

Browse files
author
Matthew Fisher
committed
Merge pull request #898 from deis/client-cleanup
refactor(client): client cleanup; return non-zero on errors
2 parents 92c4f0b + b2e2b78 commit 1e717e5

1 file changed

Lines changed: 18 additions & 182 deletions

File tree

client/deis.py

Lines changed: 18 additions & 182 deletions
Original file line numberDiff line numberDiff line change
@@ -268,37 +268,6 @@ def dictify(args):
268268
return data
269269

270270

271-
def get_provider_creds(provider, raise_error=False):
272-
"""Query environment variables and return a provider's creds if found.
273-
"""
274-
cred_types = {
275-
'ec2': [[('AWS_ACCESS_KEY_ID', 'access_key', None),
276-
('AWS_SECRET_ACCESS_KEY', 'secret_key', None)],
277-
[('AWS_ACCESS_KEY', 'access_key', None),
278-
('AWS_SECRET_KEY', 'secret_key', None)]],
279-
'rackspace': [[('RACKSPACE_USERNAME', 'username', None),
280-
('RACKSPACE_API_KEY', 'api_key', None),
281-
('CLOUD_ID_TYPE', 'identity_type', 'rackspace')]],
282-
'digitalocean': [[('DIGITALOCEAN_CLIENT_ID', 'client_id', None),
283-
('DIGITALOCEAN_API_KEY', 'api_key', None)]]
284-
}
285-
missing = None
286-
for cred_set in cred_types[provider]:
287-
creds = {}
288-
for envvar, key, default in cred_set:
289-
val = os.environ.get(envvar, default)
290-
if not val:
291-
missing = envvar
292-
break
293-
else:
294-
creds[key] = val
295-
if creds:
296-
return creds
297-
if raise_error:
298-
raise EnvironmentError(
299-
"Missing environment variable: {}".format(missing))
300-
301-
302271
def readable_datetime(datetime_str):
303272
"""
304273
Return a human-readable datetime string from an ECMA-262 (JavaScript)
@@ -469,6 +438,7 @@ def apps_create(self, args):
469438
stdout=subprocess.PIPE)
470439
print('Git remote deis added')
471440
except subprocess.CalledProcessError:
441+
print('Could not create Deis remote')
472442
sys.exit(1)
473443
else:
474444
raise ResponseError(response)
@@ -609,13 +579,25 @@ def apps_run(self, args):
609579
json.dumps(body))
610580
if response.status_code == requests.codes.ok: # @UndefinedVariable
611581
rc, output = json.loads(response.content)
612-
if rc != 0:
613-
print('Warning: non-zero return code {}'.format(rc))
614582
sys.stdout.write(output)
615583
sys.stdout.flush()
584+
sys.exit(rc)
616585
else:
617586
raise ResponseError(response)
618587

588+
def auth(self, args):
589+
"""
590+
Valid commands for auth:
591+
592+
auth:register register a new user
593+
auth:cancel remove the current account
594+
auth:login authenticate against a controller
595+
auth:logout clear the current user session
596+
597+
Use `deis help [command]` to learn more
598+
"""
599+
return
600+
619601
def auth_register(self, args):
620602
"""
621603
Register a new user with a Deis controller
@@ -640,7 +622,7 @@ def auth_register(self, args):
640622
confirm = getpass('password (confirm): ')
641623
if password != confirm:
642624
print('Password mismatch, aborting registration.')
643-
return False
625+
sys.exit(1)
644626
email = args.get('--email')
645627
if not email:
646628
email = raw_input('email: ')
@@ -714,10 +696,9 @@ def auth_login(self, args):
714696
print("Logged in as {}".format(username))
715697
return username
716698
else:
717-
print('Login failed')
718699
self._session.cookies.clear()
719700
self._session.cookies.save()
720-
return False
701+
raise ResponseError(response)
721702

722703
def auth_logout(self, args):
723704
"""
@@ -1178,7 +1159,7 @@ def _parse_key(self, path):
11781159
match = re.match(r'^(ssh-...) ([^ ]+) ?(.*)', data)
11791160
if not match:
11801161
print("Could not parse SSH public key {0}".format(name))
1181-
return
1162+
sys.exit(1)
11821163
key_type, key_str, key_comment = match.groups()
11831164
if key_comment:
11841165
key_id = key_comment
@@ -1329,151 +1310,6 @@ def _parse_perms_args(self, args):
13291310
url = "/api/apps/{}/perms".format(app)
13301311
return app, url
13311312

1332-
def providers(self, args):
1333-
"""
1334-
Valid commands for providers:
1335-
1336-
providers:list list available providers for the logged in user
1337-
providers:discover discover provider credentials using envvars
1338-
providers:create create a new provider for use by deis
1339-
providers:info print information about a specific provider
1340-
1341-
Use `deis help [command]` to learn more
1342-
"""
1343-
return self.providers_list(args)
1344-
1345-
def providers_create(self, args): # noqa
1346-
"""
1347-
Create a provider for use by Deis
1348-
1349-
This command is only necessary when adding a duplicate set of
1350-
credentials for a provider. User accounts start with empty providers,
1351-
EC2, Rackspace, and DigitalOcean by default, which should be updated
1352-
in place.
1353-
1354-
Use `providers:discover` to update the credentials for the default
1355-
providers created with your account.
1356-
1357-
Usage: deis providers:create <id> <type> <creds>
1358-
"""
1359-
type = args.get('<type>') # @ReservedAssignment
1360-
if type in ['ec2', 'rackspace', 'digitalocean']:
1361-
creds = get_provider_creds(type, raise_error=True)
1362-
else:
1363-
creds = json.loads(args.get('<creds>'))
1364-
id = args.get('<id>') # @ReservedAssignment
1365-
if not id:
1366-
id = type # @ReservedAssignment
1367-
body = {'id': id, 'type': type, 'creds': json.dumps(creds)}
1368-
response = self._dispatch('post', '/api/providers',
1369-
json.dumps(body))
1370-
if response.status_code == requests.codes.created: # @UndefinedVariable
1371-
print("{0[id]}".format(response.json()))
1372-
else:
1373-
raise ResponseError(response)
1374-
1375-
def providers_discover(self, args): # noqa
1376-
"""
1377-
Discover and update provider credentials
1378-
1379-
This command will discover provider credentials using
1380-
standard environment variables like AWS_ACCESS_KEY and
1381-
AWS_SECRET_KEY. It will use those credentials to update
1382-
the existing provider record, allowing you to use
1383-
pre-installed node flavors.
1384-
1385-
Usage: deis providers:discover
1386-
"""
1387-
provider_data = [
1388-
# Provider, human-redable provider name, sample field to display
1389-
('ec2', 'EC2', 'access_key'),
1390-
('rackspace', 'Rackspace', 'api_key'),
1391-
('digitalocean', 'DigitalOcean', 'api_key'),
1392-
]
1393-
for provider, name, field in provider_data:
1394-
creds = get_provider_creds(provider)
1395-
if creds:
1396-
print ("Discovered {} credentials: {}".format(name, creds[field]))
1397-
inp = raw_input("Import {} credentials? (y/n) : ".format(name))
1398-
if inp.lower().strip('\n') != 'y':
1399-
print('Aborting.')
1400-
else:
1401-
body = {'creds': json.dumps(creds)}
1402-
sys.stdout.write("Uploading {} credentials... ".format(name))
1403-
sys.stdout.flush()
1404-
endpoint = "/api/providers/{}".format(provider)
1405-
response = self._dispatch('patch', endpoint, json.dumps(body))
1406-
if response.status_code == requests.codes.ok: # @UndefinedVariable
1407-
print('done')
1408-
else:
1409-
raise ResponseError(response)
1410-
else:
1411-
print("No {} credentials discovered.".format(name))
1412-
1413-
# Check for locally booted Deis Controller VM
1414-
if '//deis-controller.local' in self._settings['controller']:
1415-
print("Discovered locally running Deis Controller VM")
1416-
# In order for the Controller to be able to boot Vagrant VMs it needs to run commands
1417-
# on the host machine. It does this via an SSH server. In order to access that server
1418-
# we need to send the current user's name and host.
1419-
try:
1420-
user = subprocess.check_output(
1421-
"whoami",
1422-
stderr=subprocess.PIPE
1423-
).strip()
1424-
except subprocess.CalledProcessError:
1425-
print("Error detecting username.")
1426-
sys.exit(1)
1427-
creds = {
1428-
'user': user,
1429-
'host': '192.168.61.1'
1430-
}
1431-
body = {'creds': json.dumps(creds)}
1432-
sys.stdout.write('Activating Vagrant as a provider... ')
1433-
sys.stdout.flush()
1434-
response = self._dispatch('patch', '/api/providers/vagrant',
1435-
json.dumps(body))
1436-
if response.status_code == requests.codes.ok: # @UndefinedVariable
1437-
print('done')
1438-
else:
1439-
raise ResponseError(response)
1440-
else:
1441-
print("No Vagrant Deis Controller discovered.")
1442-
1443-
def providers_info(self, args):
1444-
"""
1445-
Print information about a specific provider
1446-
1447-
Usage: deis providers:info <provider>
1448-
"""
1449-
provider = args.get('<provider>')
1450-
response = self._dispatch('get', "/api/providers/{}".format(provider))
1451-
if response.status_code == requests.codes.ok: # @UndefinedVariable
1452-
print(json.dumps(response.json(), indent=2))
1453-
else:
1454-
raise ResponseError(response)
1455-
1456-
def providers_list(self, args):
1457-
"""
1458-
List providers for the logged in user
1459-
1460-
Usage: deis providers:list
1461-
"""
1462-
response = self._dispatch('get', '/api/providers')
1463-
if response.status_code == requests.codes.ok: # @UndefinedVariable
1464-
data = response.json()
1465-
if data['count'] == 0:
1466-
print('No providers found')
1467-
return
1468-
print("=== {owner} Providers".format(**data['results'][0]))
1469-
for item in data['results']:
1470-
creds = json.loads(item['creds'])
1471-
if 'secret_key' in creds:
1472-
creds.pop('secret_key')
1473-
print("{} => {}".format(item['id'], creds))
1474-
else:
1475-
raise ResponseError(response)
1476-
14771313
def releases(self, args):
14781314
"""
14791315
Valid commands for releases:

0 commit comments

Comments
 (0)