def update_user_settings(request): """try free plan, by communicating to the mist.core service""" params = params_from_request(request) action = params.get('action', '').lower() plan = params.get('plan', '') name = params.get('name', '') company_name = params.get('company_name', '') country = params.get('country', '') number_of_servers = params.get('number_of_servers', '') number_of_people = params.get('number_of_people', '') user = user_from_request(request) payload = {'action': action, 'plan': plan, 'name': name, 'company_name': company_name, 'country': country, 'number_of_servers': number_of_servers, 'number_of_people': number_of_people} try: ret = requests.post(config.CORE_URI + '/account', params=payload, headers={'Authorization': get_auth_header(user)}, verify=config.SSL_VERIFY) except requests.exceptions.SSLError as exc: log.error("%r", exc) raise SSLError() if ret.status_code == 200: ret = json.loads(ret.content) return ret else: raise UnauthorizedError()
def star_image(request): """Toggle image as starred.""" cloud_id = request.matchdict['cloud'] image_id = request.matchdict['image'] user = user_from_request(request) return methods.star_image(user, cloud_id, image_id)
def associate_key(request): key_id = request.matchdict['key'] cloud_id = request.matchdict['cloud'] machine_id = request.matchdict['machine'] params = params_from_request(request) ssh_user = params.get('user', None) try: ssh_port = int(request.json_body.get('port', 22)) except: ssh_port = 22 try: host = request.json_body.get('host') except: host = None if not host: raise RequiredParameterMissingError('host') user = user_from_request(request) methods.associate_key(user, key_id, cloud_id, machine_id, host, username=ssh_user, port=ssh_port) return user.keypairs[key_id].machines
def check_monitoring(request): """Ask the mist.io service if monitoring is enabled for this machine. """ user = user_from_request(request) ret = methods.check_monitoring(user) return ret
def machine_actions(request): # TODO: We shouldn't return list_machines, just 200. Save the API! cloud_id = request.matchdict['cloud'] machine_id = request.matchdict['machine'] user = user_from_request(request) params = params_from_request(request) action = params.get('action', '') plan_id = params.get('plan_id', '') # plan_id is the id of the plan to resize name = params.get('name', '') if action in ('start', 'stop', 'reboot', 'destroy', 'resize', 'rename', 'undefine', 'suspend', 'resume'): if action == 'start': methods.start_machine(user, cloud_id, machine_id) elif action == 'stop': methods.stop_machine(user, cloud_id, machine_id) elif action == 'reboot': methods.reboot_machine(user, cloud_id, machine_id) elif action == 'destroy': methods.destroy_machine(user, cloud_id, machine_id) elif action == 'resize': methods.resize_machine(user, cloud_id, machine_id, plan_id) elif action == 'rename': methods.rename_machine(user, cloud_id, machine_id, name) elif action == 'undefine': methods.undefine_machine(user, cloud_id, machine_id) elif action == 'resume': methods.resume_machine(user, cloud_id, machine_id) elif action == 'suspend': methods.suspend_machine(user, cloud_id, machine_id) # return OK return methods.list_machines(user, cloud_id) raise BadRequestError()
def deploy_plugin(request): user = user_from_request(request) cloud_id = request.matchdict['cloud'] machine_id = request.matchdict['machine'] plugin_id = request.matchdict['plugin'] params = params_from_request(request) plugin_type = params.get('plugin_type') host = params.get('host') if plugin_type == 'python': ret = methods.deploy_python_plugin( user, cloud_id, machine_id, plugin_id, value_type=params.get('value_type', 'gauge'), read_function=params.get('read_function'), host=host, ) methods.update_metric( user, metric_id=ret['metric_id'], name=params.get('name'), unit=params.get('unit'), cloud_id=cloud_id, machine_id=machine_id, ) return ret else: raise BadRequestError("Invalid plugin_type: '%s'" % plugin_type)
def check_auth(request): """Check on the mist.core service if authenticated""" params = params_from_request(request) email = params.get('email', '').lower() password = params.get('password', '') payload = {'email': email, 'password': password} try: ret = requests.post(config.CORE_URI + '/auth', params=payload, verify=config.SSL_VERIFY) except requests.exceptions.SSLError as exc: log.error("%r", exc) raise SSLError() if ret.status_code == 200: ret_dict = json.loads(ret.content) user = user_from_request(request) with user.lock_n_load(): user.email = email user.mist_api_token = ret_dict.pop('token', '') user.save() log.info("succesfully check_authed") return ret_dict else: log.error("Couldn't check_auth to mist.io: %r", ret) raise UnauthorizedError()
def check_auth(request): """Check on the mist.core service if authenticated""" params = params_from_request(request) email = params.get('email', '').lower() password = params.get('password', '') payload = {'email': email, 'password': password} try: ret = requests.post(config.CORE_URI + '/auth', params=payload, verify=config.SSL_VERIFY) except requests.exceptions.SSLError as exc: log.error("%r", exc) raise SSLError() if ret.status_code == 200: ret_dict = json.loads(ret.content) user = user_from_request(request) with user.lock_n_load(): user.email = email user.mist_api_token = ret_dict.pop('mist_api_token', '') user.save() log.info("succesfully check_authed") return ret_dict else: log.error("Couldn't check_auth to mist.io: %r", ret) raise UnauthorizedError()
def get_public_key(request): user = user_from_request(request) key_id = request.matchdict['key'] if not key_id: raise RequiredParameterMissingError("key_id") if key_id not in user.keypairs: raise KeypairNotFoundError(key_id) return user.keypairs[key_id].public
def list_keys(request): """List keys. List all key pairs that are configured on this server. Only the public keys are returned. """ user = user_from_request(request) return methods.list_keys(user)
def update_monitoring(request): """Enable/disable monitoring for this machine using the hosted mist.io service. """ user = user_from_request(request) cloud_id = request.matchdict['cloud'] machine_id = request.matchdict['machine'] params = params_from_request(request) if not user.mist_api_token: log.info("trying to authenticate to service first") email = params.get('email') password = params.get('password') if not email or not password: raise UnauthorizedError("You need to authenticate to mist.io.") payload = {'email': email, 'password': password} try: ret = requests.post(config.CORE_URI + '/auth', params=payload, verify=config.SSL_VERIFY) except requests.exceptions.SSLError as exc: log.error("%r", exc) raise SSLError() if ret.status_code == 200: ret_dict = json.loads(ret.content) with user.lock_n_load(): user.email = email user.mist_api_token = ret_dict.pop('token', '') user.save() log.info("succesfully check_authed") elif ret.status_code in [400, 401]: with user.lock_n_load(): user.email = "" user.mist_api_token = "" user.save() raise UnauthorizedError("You need to authenticate to mist.io.") else: raise UnauthorizedError("You need to authenticate to mist.io.") action = params.get('action') or 'enable' name = params.get('name', '') public_ips = params.get('public_ips', []) dns_name = params.get('dns_name', '') no_ssh = bool(params.get('no_ssh', False)) dry = bool(params.get('dry', False)) if action == 'enable': ret_dict = methods.enable_monitoring( user, cloud_id, machine_id, name, dns_name, public_ips, no_ssh=no_ssh, dry=dry ) elif action == 'disable': methods.disable_monitoring(user, cloud_id, machine_id, no_ssh=no_ssh) ret_dict = {} else: raise BadRequestError() return ret_dict
def list_clouds(request): """Gets the available clouds. .. note:: Currently, this is only used by the cloud controller in js. """ user = user_from_request(request) return methods.list_clouds(user)
def update_monitoring(request): """Enable/disable monitoring for this machine using the hosted mist.io service. """ user = user_from_request(request) cloud_id = request.matchdict['cloud'] machine_id = request.matchdict['machine'] params = params_from_request(request) if not user.mist_api_token: log.info("trying to authenticate to service first") email = params.get('email') password = params.get('password') if not email or not password: raise UnauthorizedError("You need to authenticate to mist.io.") payload = {'email': email, 'password': password} try: ret = requests.post(config.CORE_URI + '/auth', params=payload, verify=config.SSL_VERIFY) except requests.exceptions.SSLError as exc: log.error("%r", exc) raise SSLError() if ret.status_code == 200: ret_dict = json.loads(ret.content) with user.lock_n_load(): user.email = email user.mist_api_token = ret_dict.pop('mist_api_token', '') user.save() log.info("succesfully check_authed") else: raise UnauthorizedError("You need to authenticate to mist.io.") action = params.get('action') or 'enable' name = params.get('name', '') public_ips = params.get('public_ips', []) dns_name = params.get('dns_name', '') no_ssh = bool(params.get('no_ssh', False)) dry = bool(params.get('dry', False)) if action == 'enable': ret_dict = methods.enable_monitoring(user, cloud_id, machine_id, name, dns_name, public_ips, no_ssh=no_ssh, dry=dry) elif action == 'disable': methods.disable_monitoring(user, cloud_id, machine_id, no_ssh=no_ssh) ret_dict = {} else: raise BadRequestError() return ret_dict
def disassoc_metric(request): user = user_from_request(request) cloud_id = request.matchdict['cloud'] machine_id = request.matchdict['machine'] params = params_from_request(request) metric_id = params.get('metric_id') if not metric_id: raise RequiredParameterMissingError('metric_id') methods.disassoc_metric(user, cloud_id, machine_id, metric_id) return {}
def get_stats(request): data = methods.get_stats(user_from_request(request), request.matchdict['cloud'], request.matchdict['machine'], request.params.get('start'), request.params.get('stop'), request.params.get('step'), request.params.get('metrics')) data['request_id'] = request.params.get('request_id') return data
def delete_machine_tag(request): """Deletes tag for a machine, given the machine id and the tag to be deleted. """ cloud_id = request.matchdict['cloud'] machine_id = request.matchdict['machine'] tag = request.matchdict['tag'] user = user_from_request(request) methods.delete_machine_tag(user, cloud_id, machine_id, tag) return OK
def delete_network(request): """ Deletes a network. Currently working only with OPENSTACK cloud """ cloud_id = request.matchdict['cloud'] network_id = request.matchdict['network'] user = user_from_request(request) methods.delete_network(user, cloud_id, network_id) return OK
def edit_key(request): old_id = request.matchdict['key'] params = params_from_request(request) new_id = params.get('new_id') if not new_id: raise RequiredParameterMissingError("new_id") user = user_from_request(request) methods.edit_key(user, new_id, old_id) return {'new_id': new_id}
def disassociate_key(request): key_id = request.matchdict['key'] cloud_id = request.matchdict['cloud'] machine_id = request.matchdict['machine'] try: host = request.json_body.get('host') except: host = None user = user_from_request(request) methods.disassociate_key(user, key_id, cloud_id, machine_id, host) return user.keypairs[key_id].machines
def delete_cloud(request): """Deletes a cloud. .. note:: It assumes the user may re-add it later so it does not remove any key associations. """ cloud_id = request.matchdict['cloud'] user = user_from_request(request) methods.delete_cloud(user, cloud_id) return OK
def rename_cloud(request): """Renames a cloud.""" cloud_id = request.matchdict['cloud'] params = params_from_request(request) new_name = params.get('new_name', '') if not new_name: raise RequiredParameterMissingError('new_name') user = user_from_request(request) methods.rename_cloud(user, cloud_id, new_name) return OK
def get_stats(request): data = methods.get_stats( user_from_request(request), request.matchdict['cloud'], request.matchdict['machine'], request.params.get('start'), request.params.get('stop'), request.params.get('step'), request.params.get('metrics') ) data['request_id'] = request.params.get('request_id') return data
def list_images(request): """List images from each cloud. Furthermore if a search_term is provided, we loop through each cloud and search for that term in the ids and the names of the community images""" cloud_id = request.matchdict['cloud'] try: term = request.json_body.get('search_term', '').lower() except: term = None user = user_from_request(request) return methods.list_images(user, cloud_id, term)
def add_key(request): params = params_from_request(request) key_id = params.get('id', '') private_key = params.get('priv', '') user = user_from_request(request) key_id = methods.add_key(user, key_id, private_key) keypair = user.keypairs[key_id] return {'id': key_id, 'machines': keypair.machines, 'isDefault': keypair.default}
def update_metric(request): user = user_from_request(request) metric_id = request.matchdict['metric'] params = params_from_request(request) methods.update_metric( user, metric_id, name=params.get('name'), unit=params.get('unit'), cloud_id=params.get('cloud_id'), machine_id=params.get('machine_id'), ) return {}
def undeploy_plugin(request): user = user_from_request(request) cloud_id = request.matchdict['cloud'] machine_id = request.matchdict['machine'] plugin_id = request.matchdict['plugin'] params = params_from_request(request) plugin_type = params.get('plugin_type') host = params.get('host') if plugin_type == 'python': ret = methods.undeploy_python_plugin(user, cloud_id, machine_id, plugin_id, host) return ret else: raise BadRequestError("Invalid plugin_type: '%s'" % plugin_type)
def set_machine_tags(request): """Sets metadata for a machine, given the cloud and machine id.""" cloud_id = request.matchdict['cloud'] machine_id = request.matchdict['machine'] try: tags = request.json_body['tags'] except: raise BadRequestError('tags should be list of tags') if type(tags) != list: raise BadRequestError('tags should be list of tags') user = user_from_request(request) methods.set_machine_tags(user, cloud_id, machine_id, tags) return OK
def associate_ip(request): cloud_id = request.matchdict['cloud'] network_id = request.matchdict['network'] params = params_from_request(request) ip = params.get('ip') machine = params.get('machine') assign = params.get('assign', True) user = user_from_request(request) ret = methods.associate_ip(user, cloud_id, network_id, ip, machine, assign) if ret: return OK else: return Response("Bad Request", 400)
def get_private_key(request): """Gets private key from keypair name. It is used in single key view when the user clicks the display private key button. """ user = user_from_request(request) key_id = request.matchdict['key'] if not key_id: raise RequiredParameterMissingError("key_id") if key_id not in user.keypairs: raise KeypairNotFoundError(key_id) return user.keypairs[key_id].private
def create_network(request): """ Creates a new network. Currently working only with OPENSTACK cloud """ cloud_id = request.matchdict['cloud'] try: network = request.json_body.get('network') except Exception as e: raise RequiredParameterMissingError(e) subnet = request.json_body.get('subnet', None) router = request.json_body.get('router', None) user = user_from_request(request) return methods.create_network(user, cloud_id, network, subnet, router)
def add_key(request): params = params_from_request(request) key_id = params.get('id', '') private_key = params.get('priv', '') user = user_from_request(request) key_id = methods.add_key(user, key_id, private_key) keypair = user.keypairs[key_id] return { 'id': key_id, 'machines': keypair.machines, 'isDefault': keypair.default }
def delete_rule(request): """Deletes a rule. """ user = user_from_request(request) try: ret = requests.delete(config.CORE_URI + request.path, headers={'Authorization': get_auth_header(user)}, verify=config.SSL_VERIFY) except requests.exceptions.SSLError as exc: log.error("%r", exc) raise SSLError() if ret.status_code != 200: log.error("Error deleting rule %d:%s", ret.status_code, ret.text) raise ServiceUnavailableError() trigger_session_update(user.email, ['monitoring']) return OK
def toggle_cloud(request): cloud_id = request.matchdict['cloud'] params = params_from_request(request) new_state = params.get('new_state', '') if not new_state: raise RequiredParameterMissingError('new_state') if new_state != "1" and new_state != "0": raise BadRequestError('Invalid cloud state') user = user_from_request(request) if cloud_id not in user.clouds: raise CloudNotFoundError() with user.lock_n_load(): user.clouds[cloud_id].enabled = bool(int(new_state)) user.save() trigger_session_update(user.email, ['clouds']) return OK
def probe(request): """Probes a machine using ping and ssh to collect metrics. .. note:: Used for getting uptime and a list of deployed keys. """ machine_id = request.matchdict['machine'] cloud_id = request.matchdict['cloud'] params = params_from_request(request) host = params.get('host', None) key_id = params.get('key', None) ssh_user = params.get('ssh_user', '') # FIXME: simply don't pass a key parameter if key_id == 'undefined': key_id = '' user = user_from_request(request) ret = methods.probe(user, cloud_id, machine_id, host, key_id, ssh_user) return ret
def delete_rule(request): """Deletes a rule. """ user = user_from_request(request) try: ret = requests.delete( config.CORE_URI + request.path, headers={'Authorization': get_auth_header(user)}, verify=config.SSL_VERIFY ) except requests.exceptions.SSLError as exc: log.error("%r", exc) raise SSLError() if ret.status_code != 200: log.error("Error deleting rule %d:%s", ret.status_code, ret.text) raise ServiceUnavailableError() trigger_session_update(user.email, ['monitoring']) return OK
def delete_key(request): """Delete key. When a keypair gets deleted, it takes its asociations with it so just need to remove from the server too. If the default key gets deleted, it sets the next one as default, provided that at least another key exists. It returns the list of all keys after the deletion, excluding the private keys (check also list_keys). """ key_id = request.matchdict.get('key') if not key_id: raise KeypairParameterMissingError() user = user_from_request(request) methods.delete_key(user, key_id) return list_keys(request)