def delete_network(network, cloud): # noqa: E501 """Delete network Delete target network # noqa: E501 :param network: :type network: str :param cloud: Cloud the target network belongs to :type cloud: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [cloud], total = list_resources( auth_context, 'cloud', search=cloud, limit=1) except ValueError: return 'Cloud does not exist', 404 try: [network], total = list_resources( auth_context, 'network', search=network, limit=1) except ValueError: return 'Network does not exist', 404 try: auth_context.check_perm("cloud", "read", cloud.id) auth_context.check_perm('network', 'read', network.id) auth_context.check_perm('network', 'remove', network.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 network.ctl.delete() return 'Network deleted succesfully', 200
def list_keys(search=None, sort=None, start=None, limit=100, only=None, deref=None): # noqa: E501 """List keys List keys owned by the active org. READ permission required on key. # noqa: E501 :param search: Only return results matching search filter :type search: str :param sort: Order results by :type sort: str :param start: Start results from index or id :type start: str :param limit: Limit number of results, 1000 max :type limit: int :param only: Only return these fields :type only: str :param deref: Dereference foreign keys :type deref: str :rtype: ListKeysResponse """ try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 result = list_resources( auth_context, 'key', search=search, only=only, sort=sort, start=start, limit=limit, deref=deref) return ListKeysResponse(data=result['data'], meta=result['meta'])
def get_rule(rule): # noqa: E501 """Get rule Get details about target rule # noqa: E501 :param rule: :type rule: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [rule], total = list_resources(auth_context, 'rule', search=rule, limit=1) except ValueError: return 'Rule does not exist', 404 meta = { 'total_matching': total, 'total_returned': 1, } return {'data': rule.as_dict(), 'meta': meta}
def delete_rule(rule): # noqa: E501 """Delete rule Delete a rule given its UUID. # noqa: E501 :param rule: :type rule: str :rtype: None """ from mist.api.methods import list_resources from mist.api.notifications.models import Notification try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [rule], total = list_resources(auth_context, 'rule', search=rule, limit=1) except ValueError: return 'Rule does not exist', 404 try: auth_context.check_perm('rule', 'delete', rule.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 rule.ctl.set_auth_context(auth_context) rule.ctl.delete() Notification.objects(owner=auth_context.owner, rtype='rule', rid=rule.id).delete() return 'Rule deleted succesfully', 200
def list_rules(search=None, sort=None, start=0, limit=100): # noqa: E501 """Get rules Return a filtered list of rules # noqa: E501 :param search: Only return results matching search filter :type search: str :param sort: Order results by :type sort: str :rtype: ListRulesResponse """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 rules, total = list_resources(auth_context, 'rule', search=search, sort=sort, limit=limit) meta = { 'total_matching': total, 'total_returned': rules.count(), 'sort': sort, 'start': start } return {'data': [c.as_dict() for c in rules], 'meta': meta}
def list_snapshots(machine): # noqa: E501 """List snapshots List snapshots of target machine # noqa: E501 :param machine: :type machine: str :rtype: ListSnapshotsResponse """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [machine], total = list_resources(auth_context, 'machine', search=machine, limit=1) except ValueError: return 'Machine does not exist', 404 try: auth_context.check_perm('machine', 'read', machine.id) auth_context.check_perm('machine', 'list_snapshots', machine.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 return machine.ctl.list_snapshots()
def edit_volume(volume, name=None): # noqa: E501 """Edit volume Edit target volume # noqa: E501 :param volume: :type volume: str :param name: New volume name :type name: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [volume], total = list_resources(auth_context, 'volume', search=volume, limit=1) except ValueError: return 'Volume does not exist', 404 try: auth_context.check_perm('volume', 'edit', volume.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 volume.ctl.rename(name) return 'Volume succesfully updated'
def delete_volume(volume): # noqa: E501 """Delete volume Delete target volume # noqa: E501 :param volume: :type volume: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [volume], _ = list_resources(auth_context, 'volume', search=volume, limit=1) except ValueError: return 'Volume does not exist', 404 cloud = volume.cloud # SEC try: auth_context.check_perm('cloud', 'read', cloud.id) auth_context.check_perm('volume', 'remove', volume.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 volume.ctl.delete() return 'Destroyed volume `%s`' % volume.name, 200
def delete_zone(zone): # noqa: E501 """Delete zone Delete target zone # noqa: E501 :param zone: :type zone: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [zone], _ = list_resources(auth_context, 'zone', search=zone, limit=1) except ValueError: return 'Zone does not exist', 404 try: # SEC auth_context.check_perm('cloud', 'read', zone.cloud.id) auth_context.check_perm('zone', 'read', zone.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 try: zone.ctl.delete_zone() except ZoneNotFoundError: return 'Zone not found', 404 except CloudUnavailableError as e: return str(e), 503 return 'Deleted zone `%s`' % zone.domain, 200
def edit_zone(zone): # noqa: E501 """Edit zone Edit target zone # noqa: E501 :param zone: :type zone: str :param name: New zone name :type name: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [zone], total = list_resources( auth_context, 'zone', search=zone, limit=1) except ValueError: return 'Zone does not exist', 404 try: auth_context.check_perm("zone", "edit", zone.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 return 'Zone successfully updated'
def edit_script(script, name=None, description=None): # noqa: E501 """Edit script Edit target script # noqa: E501 :param script: :type script: str :param name: New script name :type name: str :param description: New script description :type description: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [script], total = list_resources(auth_context, 'script', search=script, limit=1) except ValueError: return 'Script does not exist', 404 try: auth_context.check_perm('script', 'edit', script.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 script.ctl.edit(name, description) return 'Updated script `%s`' % script.name, 200
def stop_machine(machine): # noqa: E501 """Stop machine Stop target machine # noqa: E501 :param machine: :type machine: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 from mist.api.logs.methods import log_event try: [machine], total = list_resources(auth_context, 'machine', search=machine, limit=1) except ValueError: return 'Machine does not exist', 404 try: auth_context.check_perm('machine', 'stop', machine.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 log_event( auth_context.owner.id, 'request', 'stop_machine', machine_id=machine.id, user_id=auth_context.user.id, ) try: machine.ctl.stop() except ForbiddenError: return 'Action not supported on target machine', 422 return 'Stopped machine `%s`' % machine.name, 200
def edit_network(network, name=None): # noqa: E501 """Edit network Edit target network # noqa: E501 :param network: :type network: str :param name: New network name :type name: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [network], total = list_resources( auth_context, 'network', search=network, limit=1) except ValueError: return 'Network does not exist', 404 try: auth_context.check_perm('network', 'edit', network.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 network.ctl.rename(name) return 'Network succesfully updated'
def toggle_rule(rule, action): # noqa: E501 """Toggle rule Enable or disable a rule # noqa: E501 :param rule: :type rule: str :param action: :type action: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [rule], total = list_resources(auth_context, 'rule', search=rule, limit=1) except ValueError: return 'Rule does not exist', 404 try: auth_context.check_perm('rule', 'write', rule.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 if not auth_context.is_owner(): return 'You are not authorized to perform this action', 403 getattr(rule.ctl, action)() return 'Rule toggled succesfully'
def get_resource(auth_context, resource_type, cloud=None, search='', only='', sort='', deref='auto'): """ Get a single resource of any type and prepare the HTTP response """ result = list_resources(auth_context, resource_type, cloud=cloud, search=search, only=only, sort=sort, limit=1, deref=deref) if result['data']: result['data'] = result['data'][0] else: result['data'] = {} return result
def ssh(machine): # noqa: E501 """Open secure shell Open secure shell on target machine # noqa: E501 :param machine: :type machine: str :rtype: None """ from mist.api.methods import list_resources from mist.api.machines.methods import prepare_ssh_uri try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 search = f'{machine} state=running' try: [machine], total = list_resources(auth_context, 'machine', search=search, limit=1) except ValueError: return 'Machine does not exist', 404 try: auth_context.check_perm("cloud", "read", machine.cloud.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 try: ssh_uri = prepare_ssh_uri(auth_context, machine) except ForbiddenError: return 'You are not authorized to perform this action', 403 return 'Found', 302, {'Location': ssh_uri}
def associate_key(machine, key_machine_association=None): # noqa: E501 """Associate a key with a machine Associate a key with a machine. # noqa: E501 :param machine: :type machine: str :param key_machine_association: :type key_machine_association: dict | bytes :rtype: None """ if connexion.request.is_json: key_machine_association = KeyMachineAssociation.from_dict(connexion.request.get_json()) # noqa: E501 ssh_user = key_machine_association.user or 'root' ssh_port = key_machine_association.port or 22 from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except Exception: return 'Authentication failed', 401 try: [machine], _ = list_resources(auth_context, 'machine', search=machine, limit=1) except ValueError: return 'Machine does not exist', 404 try: [key], _ = list_resources(auth_context, 'key', search=key_machine_association.key, limit=1) except Key.DoesNotExist: return 'Key id does not exist', 404 try: auth_context.check_perm('machine', 'associate_key', machine.id) auth_context.check_perm('cloud', 'read', machine.cloud.id) auth_context.check_perm('key', 'read', key.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 try: key.ctl.associate(machine, username=ssh_user, port=ssh_port) except BadRequestError as e: return str(e), 400 except (MachineUnauthorizedError, ServiceUnavailableError): return 'Could not connect to target machine', 503 return 'Association successful', 200
def get_key(key, private=False, sort=None, only=None, deref=None): # noqa: E501 """Get key Get details about target key # noqa: E501 :param key: :type key: str :param private: Return the private key. Requires READ_PRIVATE permission on key. :type private: bool :param sort: Order results by :type sort: str :param only: Only return these fields :type only: str :param deref: Dereference foreign keys :type deref: str :rtype: GetKeyResponse """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 from mist.api.logs.methods import log_event try: [key], total = list_resources(auth_context, 'key', search=key, limit=1) except ValueError: return 'Key does not exist', 404 meta = { 'total': total, 'returned': 1, } result = { 'data': key.as_dict(), 'meta': meta } if private: try: auth_context.check_perm('key', 'read_private', key.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 log_event( auth_context.owner.id, 'request', 'read_private', key_id=key.id, user_id=auth_context.user.id, ) result['data']['private'] = key.private return GetKeyResponse(data=result['data'], meta=result['meta'])
def create_network(create_network_request=None): # noqa: E501 """Create network Creates one or more networks on the specified cloud. If async is true, a jobId will be returned. READ permission required on cloud. CREATE_RESOURCES permission required on cloud. CREATE permission required on network. # noqa: E501 :param create_network_request: :type create_network_request: dict | bytes :rtype: CreateNetworkResponse """ from mist.api.methods import list_resources if connexion.request.is_json: create_network_request = CreateNetworkRequest.from_dict(connexion.request.get_json()) # noqa: E501 try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 params = delete_none(create_network_request.to_dict()) try: tags, _ = auth_context.check_perm("network", "add", None) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 try: [cloud], total = list_resources( auth_context, 'cloud', search=params.pop('cloud'), limit=1) except ValueError: return 'Cloud does not exist', 404 try: auth_context.check_perm('cloud', 'read', cloud.id) auth_context.check_perm('cloud', 'create_resources', cloud.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 if not hasattr(cloud.ctl, 'network'): return 'Network support is not available', 501 # Create the new network network_params = {'name': params['name']} if 'extra' in params: network_params.update(params['extra']) try: network = NETWORKS[cloud.ctl.provider].add( cloud=cloud, **network_params) except BadRequestError as e: return str(e), 400 except NetworkListingError as e: return str(e), 503 network.assign_to(auth_context.user) if tags: add_tags_to_resource(auth_context.owner, network, tags) return network.as_dict()
def create_zone(create_zone_request=None): # noqa: E501 """Create zone Creates one or more zones on the specified cloud. If async is true, a jobId will be returned. READ permission required on cloud. CREATE_RESOURCES permission required on cloud. CREATE permission required on zone. # noqa: E501 :param create_zone_request: :type create_zone_request: dict | bytes :rtype: CreateZoneResponse """ from mist.api.methods import list_resources if connexion.request.is_json: create_zone_request = CreateZoneRequest.from_dict(connexion.request.get_json()) # noqa: E501 try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 params = delete_none(create_zone_request.to_dict()) try: [cloud], total = list_resources( auth_context, 'cloud', search=params.pop('cloud'), limit=1) except ValueError: return 'Cloud does not exist', 404 try: auth_context.check_perm("cloud", "read", cloud.id) auth_context.check_perm("cloud", "create_resources", cloud.id) tags, _ = auth_context.check_perm("zone", "add", None) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 params['domain'] = params.pop('name') try: new_zone = Zone.add(owner=cloud.owner, cloud=cloud, **params) except BadRequestError as e: return str(e), 400 except CloudUnauthorizedError: return 'You are not authorized to perform this action', 403 except ZoneCreationError as e: return str(e), 503 except ZoneListingError as e: return str(e), 503 except CloudUnavailableError as e: return str(e), 503 new_zone.assign_to(auth_context.user) if tags: resolve_id_and_set_tags(auth_context.owner, 'zone', new_zone.id, tags, cloud_id=cloud.id) return new_zone.as_dict()
def clone_machine(machine, name, run_async=True): # noqa: E501 """Clone machine Clone target machine # noqa: E501 :param machine: :type machine: str :param name: :type name: str :param run_async: :type run_async: bool :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 from mist.api.logs.methods import log_event try: [machine], total = list_resources(auth_context, 'machine', search=machine, limit=1) except ValueError: return 'Machine does not exist', 404 try: auth_context.check_perm('machine', 'clone', machine.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 log_event( auth_context.owner.id, 'request', 'clone_machine', machine_id=machine.id, user_id=auth_context.user.id, ) job = 'clone_machine' job_id = uuid.uuid4().hex if run_async: # noqa: W606 args = (auth_context.serialize(), machine.id, name) kwargs = {'job': job, 'job_id': job_id} clone_machine_async.send_with_options( args=args, kwargs=kwargs, delay=1_000) else: try: machine.ctl.clone(name) except ForbiddenError as e: return str(e), 403 return 'Machine clone issued successfully'
def edit_key(key, name=None, default=None): # noqa: E501 """Edit key Edit target key # noqa: E501 :param key: :type key: str :param name: New key name :type name: str :param default: Set as default :type default: bool :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 from mist.api.logs.methods import log_event try: [key], total = list_resources(auth_context, 'key', search=key, limit=1) except ValueError: return 'Key does not exist', 404 try: auth_context.check_perm('key', 'edit', key.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 log_event( auth_context.owner.id, 'request', 'edit_key', key_id=key.id, user_id=auth_context.user.id, key_name=key.name, key_default=key.default, new_name=name, new_default=default ) key_updated = False if name: key.name = name key_updated = True if default: key.ctl.set_default() key_updated = True if key_updated: key.save() return 'Updated key `%s`' % key.name, 200
def edit_machine(machine, edit_machine_request=None): # noqa: E501 """Edit machine Edit target machine # noqa: E501 :param machine: :type machine: str :param edit_machine_request: :type edit_machine_request: dict | bytes :rtype: None """ from mist.api.methods import list_resources if connexion.request.is_json: edit_machine_request = EditMachineRequest.from_dict(connexion.request.get_json()) # noqa: E501 params = delete_none(edit_machine_request.to_dict()) try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 from mist.api.logs.methods import log_event try: [machine], total = list_resources(auth_context, 'machine', search=machine, limit=1) except ValueError: return 'Machine does not exist', 404 if machine.cloud.owner != auth_context.owner: return 'Machine does not exist', 404 # VMs in libvirt can be started no matter if they are terminated if machine.state == 'terminated' and not isinstance(machine.cloud, LibvirtCloud): return 'Machine does not exist', 404 log_event( auth_context.owner.id, 'request', 'edit_machine', machine_id=machine.id, user_id=auth_context.user.id, ) try: auth_context.check_perm('machine', 'edit', machine.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 machine.ctl.update(auth_context, params) return 'Machine successfully updated'
def edit_rule(rule, edit_rule_request=None): # noqa: E501 """Update rule Edit a rule given its UUID, EDIT permission required on rule # noqa: E501 :param rule: :type rule: str :param edit_rule_request: :type edit_rule_request: dict | bytes :rtype: Rule """ from mist.api.methods import list_resources from mist.api.notifications.models import Notification if connexion.request.is_json: edit_rule_request = EditRuleRequest.from_dict( connexion.request.get_json()) # noqa: E501 try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [rule], total = list_resources(auth_context, 'rule', search=rule, limit=1) except ValueError: return 'Rule does not exist', 404 try: auth_context.check_perm('rule', 'edit', rule.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 rule.ctl.set_auth_context(auth_context) kwargs = delete_none(edit_rule_request.to_dict()) try: rule.ctl.update(**kwargs) except (BadRequestError, ValidationError) as e: return str(e), 400 Notification.objects(owner=auth_context.owner, rtype='rule', rid=rule.id).delete() return rule.as_dict()
def console(machine): # noqa: E501 """Open console Open VNC console on target machine # noqa: E501 :param machine: :type machine: str :rtype: None """ from mist.api.methods import list_resources from mist.api.methods import get_console_proxy_uri try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [machine], total = list_resources( auth_context, 'machine', search=f'{machine} state!=terminated', limit=1) except ValueError: return 'Machine does not exist', 404 cloud_id = machine.cloud.id try: auth_context.check_perm("cloud", "read", cloud_id) auth_context.check_perm("machine", "read", machine.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 if not machine.cloud.ctl.has_feature('console'): return 'Action not supported', 501 proxy_uri = get_console_proxy_uri(machine) if proxy_uri is None: console_url = machine.cloud.ctl.compute.connection.ex_open_console( machine.machine_id ) headers = {'Location': console_url} else: headers = {'Location': proxy_uri} return '', 302, headers
def list_resources(auth_context, resource_type, cloud=None, tags='', search='', only='', sort='', start=0, limit=100, deref='auto'): """ List resources of any type and prepare the HTTP response """ from mist.api.methods import list_resources if not limit: limit = 100 try: start = int(start) except (ValueError, TypeError): start = 0 items, total = list_resources(auth_context, resource_type, cloud=cloud, tags=tags, search=search, only=only, sort=sort, limit=limit, start=start) meta = { 'total': total, 'returned': len(items), 'sort': sort, 'start': start } return { 'data': [i.as_dict_v2(deref or '', only or '') for i in items], 'meta': meta }
def rename_machine(machine, name): # noqa: E501 """Rename machine Rename target machine # noqa: E501 :param machine: :type machine: str :param name: New machine name :type name: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 from mist.api.logs.methods import log_event try: [machine], total = list_resources(auth_context, 'machine', search=machine, limit=1) except ValueError: return 'Machine does not exist', 404 if not methods.run_pre_action_hooks(machine, 'rename', auth_context.user): return 'OK', 200 # webhook requires stopping action propagation log_event( auth_context.owner.id, 'request', 'rename_machine', machine_id=machine.id, user_id=auth_context.user.id, ) try: auth_context.check_perm('machine', 'rename', machine.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 try: result = machine.ctl.rename(name) except ForbiddenError: return 'Action not supported on target machine', 422 methods.run_post_action_hooks(machine, 'rename', auth_context.user, result) return 'Machine renamed successfully'
def create_snapshot(machine, name): # noqa: E501 """Create snapshot Create snapshots of target machine # noqa: E501 :param machine: :type machine: str :param name: :type name: str :rtype: object """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [machine], total = list_resources(auth_context, 'machine', search=machine, limit=1) except ValueError: return 'Machine does not exist', 404 try: auth_context.check_perm('machine', 'read', machine.id) auth_context.check_perm('machine', 'list_snapshots', machine.id) auth_context.check_perm('machine', 'create_snapshots', machine.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 try: result = machine.ctl.create_snapshot(name) except ForbiddenError: return 'Action not supported on target machine', 422 except BadRequestError as e: return str(e), 400 methods.run_post_action_hooks(machine, 'create_snapshot', auth_context.user, result) return {'name': name}
def revert_to_snapshot(machine, snapshot): # noqa: E501 """Revert to snapshot Revert machine to snapshot # noqa: E501 :param machine: :type machine: str :param snapshot: :type snapshot: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 try: [machine], total = list_resources(auth_context, 'machine', search=machine, limit=1) except ValueError: return 'Machine does not exist', 404 try: auth_context.check_perm('machine', 'read', machine.id) auth_context.check_perm('machine', 'list_snapshots', machine.id) auth_context.check_perm('machine', 'revert_to_snapshots', machine.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 try: result = machine.ctl.revert_to_snapshot(snapshot) except BadRequestError as e: return str(e), 400 methods.run_post_action_hooks(machine, 'revert_to_snapshot', auth_context.user, result) return 'Revert machine to snapshot issued successfully'
def resize_machine(machine, size): # noqa: E501 """Resize machine Resize target machine # noqa: E501 :param machine: :type machine: str :param size: :type size: str :rtype: None """ from mist.api.methods import list_resources try: auth_context = connexion.context['token_info']['auth_context'] except KeyError: return 'Authentication failed', 401 from mist.api.logs.methods import log_event try: [machine], total = list_resources(auth_context, 'machine', search=machine, limit=1) except ValueError: return 'Machine does not exist', 404 if not methods.run_pre_action_hooks(machine, 'resize', auth_context.user): return 'OK', 200 # webhook requires stopping action propagation try: [size], total = list_resources(auth_context, 'size', cloud=machine.cloud.id, search=size, limit=1) except ValueError: return 'Size does not exist', 404 try: _, constraints = auth_context.check_perm( 'machine', 'resize', machine.id) except PolicyUnauthorizedError: return 'You are not authorized to perform this action', 403 # check cost constraint cost_constraint = constraints.get('cost', {}) if cost_constraint: try: from mist.rbac.methods import check_cost check_cost(auth_context.org, cost_constraint) except ImportError: pass # check size constraint size_constraint = constraints.get('size', {}) if size_constraint: try: from mist.rbac.methods import check_size check_size(machine.cloud.id, size_constraint, size) except ImportError: pass log_event( auth_context.owner.id, 'request', 'resize_machine', machine_id=machine.id, user_id=auth_context.user.id, ) try: result = machine.ctl.resize(size.id, {}) except ForbiddenError: return 'Action not supported on target machine', 422 except BadRequestError as e: return str(e), 400 methods.run_post_action_hooks(machine, 'resize', auth_context.user, result) return 'Machine resize issued successfully'