def delete(self, request, obj_id): try: api.muranoclient(request).categories.delete(obj_id) except exc.HTTPException: LOG.exception(_("Unable to delete category")) url = reverse("horizon:murano:categories:index") exceptions.handle(request, _("Unable to delete category."), redirect=url)
def delete(self, request, obj_id): try: api.muranoclient(request).categories.delete(obj_id) except exc.HTTPException: msg = _('Unable to delete category') LOG.exception(msg) url = reverse('horizon:murano:categories:index') exceptions.handle(request, msg, redirect=url)
def delete(self, request, obj_id): try: api.muranoclient(request).categories.delete(obj_id) except exc.HTTPException: LOG.exception(_('Unable to delete category')) exceptions.handle(request, _('Unable to remove package.'), redirect='horizon:murano:categories:index')
def action(self, request, obj_id): try: api.muranoclient(request).packages.toggle_active(obj_id) LOG.debug("Toggle Active for package {0}.".format(obj_id)) except exc.HTTPForbidden: msg = _("You are not allowed to perform this operation") LOG.exception(msg) messages.error(request, msg) exceptions.handle(request, msg, redirect=reverse("horizon:murano:packages:index"))
def services_list(request, environment_id, environment=None): if hasattr(request, 'services') and request.services.has_key(environment_id): return request.services[environment_id] """Get environment applications. This function collects data from Murano API and modifies it only for dashboard purposes. Those changes don't impact application deployment parameters. """ def strip(msg, to=100): return u'%s...' % msg[:to] if len(msg) > to else msg services = [] # need to create new session to see services deployed be other user session_id = Session.get(request, environment_id) if environment is None: get_environment = api.muranoclient(request).environments.get environment = get_environment(environment_id, session_id) try: client = api.muranoclient(request) reports = client.environments.last_status(environment_id, session_id) except exc.HTTPNotFound: LOG.exception(_('Could not retrieve latest status for ' 'the {0} environment').format(environment_id)) reports = {} for service_item in environment.services or []: service_data = service_item service_id = service_data['?']['id'] if service_id in reports and reports[service_id]: last_operation = strip(reports[service_id].text) time = reports[service_id].updated else: last_operation = 'Component draft created' \ if environment.version == 0 else '' try: time = service_data['updated'][:-7] except KeyError: time = None service_data['environment_id'] = environment_id service_data['environment_version'] = environment.version service_data['operation'] = last_operation service_data['operation_updated'] = time if service_data['?'].get('name'): service_data['name'] = service_data['?']['name'] services.append(service_data) LOG.debug('Service::List') svcs = [utils.Bunch(**service) for service in services] request.services = getattr(request, 'services', {}) request.services[environment_id] = svcs return svcs
def services_list(request, environment_id): """Get environment applications. This function collects data from Murano API and modifies it only for dashboard purposes. Those changes don't impact application deployment parameters. """ def strip(msg, to=100): return u'%s...' % msg[:to] if len(msg) > to else msg services = [] # need to create new session to see services deployed be other user session_id = Session.get(request, environment_id) get_environment = api.muranoclient(request).environments.get environment = get_environment(environment_id, session_id) try: client = api.muranoclient(request) reports = client.environments.last_status(environment_id, session_id) except exc.HTTPNotFound: LOG.exception( _('Could not retrieve latest status for ' 'the {0} environment').format(environment_id)) reports = {} for service_item in environment.services or []: service_data = service_item service_id = service_data['?']['id'] if service_id in reports and reports[service_id]: last_operation = strip(reports[service_id].text) time = reports[service_id].updated.replace('T', ' ') else: last_operation = 'Component draft created' \ if environment.version == 0 else '' try: time = service_data['updated'].replace('T', ' ')[:-7] except KeyError: time = None service_data['environment_id'] = environment_id service_data['environment_version'] = environment.version service_data['operation'] = last_operation service_data['operation_updated'] = time if service_data['?'].get('name'): service_data['name'] = service_data['?']['name'] services.append(service_data) LOG.debug('Service::List') return [utils.Bunch(**service) for service in services]
def action(self, request, obj_id): try: api.muranoclient(request).packages.toggle_public(obj_id) LOG.debug("Toggle Public for package {0}.".format(obj_id)) except exc.HTTPForbidden: msg = _("You are not allowed to perform this operation") LOG.exception(msg) messages.error(request, msg) exceptions.handle(request, msg, redirect=reverse("horizon:murano:packages:index")) except exc.HTTPConflict: msg = _("Package or Class with the same name is already made " "public") LOG.exception(msg) messages.error(request, msg) exceptions.handle(request, msg, redirect=reverse("horizon:murano:packages:index"))
def delete(self, request, obj_id): try: api.muranoclient(request).packages.delete(obj_id) except exc.HTTPNotFound: msg = _("Package with id {0} is not found").format(obj_id) LOG.exception(msg) exceptions.handle(self.request, msg, redirect=reverse("horizon:murano:packages:index")) except exc.HTTPForbidden: msg = _("You are not allowed to delete this package") LOG.exception(msg) exceptions.handle(request, msg, redirect=reverse("horizon:murano:packages:index")) except Exception: LOG.exception(_("Unable to delete package in murano-api server")) exceptions.handle(request, _("Unable to remove package."), redirect="horizon:murano:packages:index")
def handle(self, request, data): app_id = self.initial.get('app_id') LOG.debug('Updating package {0} with {1}'.format(app_id, data)) try: data['tags'] = [t.strip() for t in data['tags'].split(',')] result = api.muranoclient(request).packages.update(app_id, data) messages.success(request, _('Package modified.')) return result except exc.HTTPForbidden: msg = _("You are not allowed to perform this operation") LOG.exception(msg) exceptions.handle( request, msg, redirect=reverse('horizon:murano:packages:index')) except Exception as original_e: reason = '' exc_info = sys.exc_info() if hasattr(original_e, 'details'): try: error = json.loads(original_e.details).get('error') if error: reason = error.get('message') except ValueError: # Let horizon operate with original exception raise exc_info[0], exc_info[1], exc_info[2] msg = _('Failed to upload the package. {0}').format(reason) LOG.exception(msg) redirect = reverse('horizon:murano:packages:index') exceptions.handle(request, msg, redirect=redirect)
def cleaned_latest_apps(request): """Returns a list of recently used apps Verifies, that apps in the list are either public or belong to current project. """ cleaned_apps, cleaned_app_ids = [], [] for app_id in request.session.get('latest_apps', []): try: # TODO(kzaitsev): we have to update this to 1 request per list of # apps. Should be trivial and should remove the need to verify that # apps are available. bug/1559066 app = api.muranoclient(request).packages.get(app_id) except exc.HTTPNotFound: continue else: if app.type != 'Application': continue if (app.owner_id == request.session['token'].project['id'] or app.is_public): cleaned_apps.append(app) cleaned_app_ids.append(app_id) request.session['latest_apps'] = collections.deque(cleaned_app_ids) return cleaned_apps
def update_cell(self, request, datum, obj_id, cell_name, new_cell_value): try: if not new_cell_value or new_cell_value.isspace(): message = _("The environment name field cannot be empty.") messages.warning(request, message) raise ValueError(message) mc = api_utils.muranoclient(request) mc.environments.update(datum.id, name=new_cell_value) except exc.HTTPConflict: message = _("Couldn't update environment. Reason: This name is " "already taken.") messages.warning(request, message) LOG.warning(message) # FIXME(kzaitsev): There is a bug in horizon and inline error # icons are missing. This means, that if we return 400 here, by # raising django.core.exceptions.ValidationError(message) the UI # will break a little. Until the bug is fixed this will raise 500 # bug link: https://bugs.launchpad.net/horizon/+bug/1359399 # Alternatively this could somehow raise 409, which would result # in the same behaviour. raise ValueError(message) except Exception: exceptions.handle(request, ignore=True) return False return True
def get_context_data(self, form, **kwargs): context = super(Wizard, self).get_context_data(form=form, **kwargs) mc = api.muranoclient(self.request) app_id = self.kwargs.get('app_id') app = self.storage.extra_data.get('app') # Save extra data to prevent extra API calls if not app: app = mc.packages.get(app_id) self.storage.extra_data['app'] = app environment_id = self.kwargs.get('environment_id') environment_id = utils.ensure_python_obj(environment_id) if environment_id is not None: env_name = mc.environments.get(environment_id).name else: env_name = get_next_quick_environment_name(self.request) context['field_descriptions'] = services.get_app_field_descriptions( self.request, app_id, self.steps.index) context.update({'type': app.fully_qualified_name, 'service_name': app.name, 'app_id': app_id, 'environment_id': environment_id, 'environment_name': env_name, 'do_redirect': self.get_wizard_flag('do_redirect'), 'drop_wm_form': self.get_wizard_flag('drop_wm_form'), 'prefix': self.prefix, }) return context
def get_deployment_start(request, environment_id, deployment_id): deployments = api.muranoclient(request).deployments.list(environment_id) LOG.debug('Get deployment start time') for deployment in deployments: if deployment.id == deployment_id: return utils.adjust_datestr(request, deployment.started) return None
def done(self, form_list, **kwargs): data = self.get_all_cleaned_data() app_id = self.storage.get_step_data("upload")["package"].id # Remove package file from result data for key in ("package", "import_type", "url", "repo_version", "repo_name"): del data[key] dep_pkgs = self.storage.get_step_data("upload").get("dependencies", []) redirect = reverse("horizon:murano:packages:index") dep_data = {"enabled": data["enabled"], "is_public": data["is_public"]} murano_client = api.muranoclient(self.request) for dep_pkg in dep_pkgs: try: murano_client.packages.update(dep_pkg.id, dep_data) except Exception as e: msg = _("Couldn't update package {0} parameters. Error: {1}").format(dep_pkg.fully_qualified_name, e) LOG.warning(msg) messages.warning(self.request, msg) try: data["tags"] = [t.strip() for t in data["tags"].split(",")] murano_client.packages.update(app_id, data) except exc.HTTPForbidden: msg = _("You are not allowed to change" " this properties of the package") LOG.exception(msg) exceptions.handle(self.request, msg, redirect=reverse("horizon:murano:packages:index")) except (exc.HTTPException, Exception): LOG.exception(_("Modifying package failed")) exceptions.handle(self.request, _("Unable to modify package"), redirect=redirect) else: msg = _("Package parameters successfully updated.") LOG.info(msg) messages.success(self.request, msg) return http.HttpResponseRedirect(redirect)
def init_usages(self): stored_data = self.storage.extra_data step_usages = stored_data.get('step_usages') if step_usages is None: step_usages = [ collections.defaultdict(dict) for step in self.steps.all ] stored_data['step_usages'] = step_usages environment_id = self.kwargs.get('environment_id') environment_id = utils.ensure_python_obj(environment_id) if environment_id is not None: session_id = env_api.Session.get(self.request, environment_id) client = api.muranoclient(self.request) all_services = client.environments.get( environment_id, session_id).services env_usages = self.aggregate_usages(map( lambda svc: svc['?'].get('resourceUsages', {}), all_services)) else: env_usages = collections.defaultdict(dict) step_usages.insert(0, env_usages) return step_usages
def get_initial(self): app_id = self.kwargs['app_id'] package = api.muranoclient(self.request).packages.get(app_id) return { 'package': package, 'app_id': app_id, }
def get_context_data(self, form, **kwargs): context = super(Wizard, self).get_context_data(form=form, **kwargs) mc = api.muranoclient(self.request) app_id = self.kwargs.get('app_id') app = self.storage.extra_data.get('app') # Save extra data to prevent extra API calls if not app: app = mc.packages.get(app_id) self.storage.extra_data['app'] = app environment_id = self.kwargs.get('environment_id') environment_id = utils.ensure_python_obj(environment_id) if environment_id is not None: env_name = mc.environments.get(environment_id).name else: env_name = get_next_quick_environment_name(self.request) context['field_descriptions'] = services.get_app_field_descriptions( self.request, app_id, self.steps.index) context.update({ 'type': app.fully_qualified_name, 'service_name': app.name, 'app_id': app_id, 'environment_id': environment_id, 'environment_name': env_name, 'do_redirect': self.get_wizard_flag('do_redirect'), 'drop_wm_form': self.get_wizard_flag('drop_wm_form'), 'prefix': self.prefix, }) return context
def __init__(self, request, *args, **kwargs): super(ModifyPackageForm, self).__init__(request, *args, **kwargs) package = kwargs['initial']['package'] self.set_initial(request, package) if package.type == 'Application': self.fields['categories'] = forms.MultipleChoiceField( label=_('Application Category'), choices=[('', 'No categories available')], required=False) try: categories = api.muranoclient(request).categories.list() if categories: category_names = [(c.name, c.name) for c in categories] self.fields['categories'].choices = category_names if package.categories: self.fields['categories'].initial = dict( (key, True) for key in package.categories) except (exc.HTTPException, Exception): msg = _('Unable to get list of categories') LOG.exception(msg) redirect = reverse('horizon:app-catalog:packages:index') exceptions.handle(request, msg, redirect=redirect)
def get_deployment_start(request, environment_id, deployment_id): deployments = api.muranoclient(request).deployments.list(environment_id) LOG.debug('Get deployment start time') for deployment in deployments: if deployment.id == deployment_id: return deployment.started.replace('T', ' ') return None
def __init__(self, request, package, *args, **kwargs): super(UpdatePackageForm, self).__init__(*args, **kwargs) if package.type == 'Application': self.fields['categories'].choices = [('', 'No categories available')] try: categories = api.muranoclient(request).packages.categories() if categories: self.fields['categories'].choices = [(c, c) for c in categories] if package.categories: self.fields['categories'].initial = dict( (key, True) for key in package.categories) except (exc.HTTPException, Exception): msg = 'Unable to get list of categories' LOG.exception(msg) redirect = reverse('horizon:murano:packages:index') exceptions.handle(request, _(msg), redirect=redirect) else: del self.fields['categories'] self.fields['name'].initial = package.name self.fields['tags'].initial = ', '.join(package.tags) self.fields['is_public'].initial = package.is_public self.fields['enabled'].initial = package.enabled self.fields['description'].initial = package.description
def get_deployment_descr(request, environment_id, deployment_id): deployments = api.muranoclient(request).deployments.list(environment_id) LOG.debug('Get deployment description') for deployment in deployments: if deployment.id == deployment_id: return deployment.description return None
def get(self, request, environment, component): """Get a metadata object for a component in a given environment Example GET: http://localhost/api/app-catalog/environments/123/components/456/metadata The following get parameters may be passed in the GET request: :param environment: identifier of the environment :param component: identifier of the component Any additionally a "session" parameter should be passed through the API as a keyword. """ filters, keywords = rest_utils.parse_filters_kwargs(request, ['session']) session = keywords.get('session') if not session: session = env_api.Session.get_or_create_or_delete(request, environment) component = api.muranoclient(request).services.get( environment, '/' + component, session) if component: return component.to_dict()['?'].get('metadata', {}) return {}
def post(self, request, environment, component): """Set a metadata object for a component in a given environment Example POST: http://localhost/api/app-catalog/environments/123/components/456/metadata The following get parameters may be passed in the GET request: :param environment: identifier of the environment :param component: identifier of the component Any additionally a "session" parameter should be passed through the API as a keyword. Request body should contain 'updated' keyword, contain all the updated metadata attributes. If it is empty, the metadata is considered to be deleted. """ client = api.muranoclient(request) filters, keywords = rest_utils.parse_filters_kwargs(request, ['session']) session = keywords.get('session') if not session: session = env_api.Session.get_or_create_or_delete(request, environment) updated = request.DATA.get('updated', {}) path = '/{0}/%3F/metadata'.format(component) if updated: client.services.put(environment, path, updated, session) else: client.services.delete(environment, path, session)
def post(self, request, environment): """Set a metadata object for a given environment Example POST: http://localhost/api/app-catalog/environments/123/metadata The following get parameters may be passed in the GET request: :param environment: identifier of the environment Any additionally a "session" parameter should be passed through the API as a keyword. Request body should contain 'updated' keyword, contain all the updated metadata attributes. If it is empty, the metadata is considered to be deleted. """ client = api.muranoclient(request) filters, keywords = rest_utils.parse_filters_kwargs(request, ['session']) session = keywords.get('session') if not session: session = env_api.Session.get_or_create_or_delete(request, environment) updated = request.DATA.get('updated', {}) patch = { "op": "replace", "path": "/?/metadata", "value": updated } client.environments.update_model(environment, [patch], session)
def handle(self, request, data): app_id = self.initial.get('app_id') LOG.debug('Updating package {0} with {1}'.format(app_id, data)) try: data['tags'] = [t.strip() for t in data['tags'].split(',')] result = api.muranoclient(request).packages.update(app_id, data) messages.success(request, _('Package modified.')) return result except exc.HTTPForbidden: msg = _("You are not allowed to perform this operation") LOG.exception(msg) exceptions.handle( request, msg, redirect=reverse('horizon:murano:packages:index')) except Exception as original_e: reason = '' exc_info = sys.exc_info() if hasattr(original_e, 'details'): try: error = json.loads(original_e.details).get('error') if error: reason = error.get('message') except ValueError: # Let horizon operate with original exception raise exc_info[0], exc_info[1], exc_info[2] msg = _('Failed to upload the package. {0}').format(reason) LOG.exception(msg) redirect = reverse('horizon:murano:packages:index') exceptions.handle(request, _(msg), redirect=redirect)
def package_list(request, marker=None, filters=None, paginate=False, page_size=20, sort_dir=None, limit=None): limit = limit or getattr(settings, 'PACKAGES_LIMIT', 100) filters = filters or {} if paginate: request_size = page_size + 1 else: request_size = limit if marker: filters['marker'] = marker if sort_dir: filters['sort_dir'] = sort_dir client = api.muranoclient(request) packages_iter = client.packages.filter(limit=request_size, **filters) has_more_data = False if paginate: packages = list(itertools.islice(packages_iter, request_size)) if len(packages) > page_size: packages.pop() has_more_data = True else: packages = list(packages_iter) return packages, has_more_data
def update_cell(self, request, datum, obj_id, cell_name, new_cell_value): try: if not new_cell_value or new_cell_value.isspace(): message = _("The environment name field cannot be empty.") messages.warning(request, message) raise ValueError(message) mc = api_utils.muranoclient(request) mc.environments.update(datum.id, name=new_cell_value) except exc.HTTPConflict: message = _("This name is already taken.") messages.warning(request, message) LOG.warning(_("Couldn't update environment. Reason: ") + message) # FIXME(kzaitsev): There is a bug in horizon and inline error # icons are missing. This means, that if we return 400 here, by # raising django.core.exceptions.ValidationError(message) the UI # will break a little. Until the bug is fixed this will raise 500 # bug link: https://bugs.launchpad.net/horizon/+bug/1359399 # Alternatively this could somehow raise 409, which would result # in the same behaviour. raise ValueError(message) except Exception: exceptions.handle(request, ignore=True) return False return True
def get_context_data(self, form, **kwargs): context = super(Wizard, self).get_context_data(form=form, **kwargs) app_id = self.kwargs.get('app_id') app = self.storage.extra_data.get('app') # Save extra data to prevent extra API calls mc = api_utils.muranoclient(self.request) if not app: app = mc.packages.get(app_id) self.storage.extra_data['app'] = app env_name = mc.environments.get(self.environment_id).name context['field_descriptions'] = services.get_app_field_descriptions(self.request, app_id, self.steps.index) context.update({'type': app.fully_qualified_name, 'service_name': app.name, 'app_id': app_id, 'environment_id': self.environment_id, 'environment_name': env_name, 'do_redirect': self.get_wizard_flag('do_redirect'), 'drop_wm_form': self.get_wizard_flag('drop_wm_form'), 'prefix': self.prefix, 'got_picture': app.supplier.has_key('Logo'), }) return context
def handle(self, request, data): if data: with api.handled_exceptions(self.request): category = api.muranoclient(self.request).categories.add(data) messages.success(request, _('Category {0} created.').format(data['name'])) return category
def allowed(self, request, package): _allowed = False with api.handled_exceptions(request): client = api.muranoclient(request) if client.categories.list(): _allowed = True return _allowed
def environment_deploy(request, environment_id): session_id = Session.get_or_create_or_delete(request, environment_id) LOG.debug('Session::Get <Id: {0}>'.format(session_id)) env = api.muranoclient(request).sessions.deploy(environment_id, session_id) LOG.debug('Environment::Deploy <EnvId: {0}, SessionId: {1}>' ''.format(environment_id, session_id)) return env
def handle(self, request, data): if data: with api.handled_exceptions(self.request): category = api.muranoclient(self.request).categories.add(data) messages.success(request, _('Category {0} created.') .format(data['name'])) return category
def get_categories_list(request): categories = [] with api.handled_exceptions(request): client = api.muranoclient(request) categories = client.packages.categories() if ALL_CATEGORY_NAME not in categories: categories.insert(0, ALL_CATEGORY_NAME) return categories
def environment_create(request, parameters): # name is required param body = {'name': parameters['name']} if 'defaultNetworks' in parameters: body['defaultNetworks'] = parameters['defaultNetworks'] env = api.muranoclient(request).environments.create(body) LOG.debug('Environment::Create {0}'.format(env)) return env
def service_create(request, environment_id, parameters): # We should be able to delete session if we want to add new services to # this environment. session_id = Session.get_or_create_or_delete(request, environment_id) LOG.debug('Service::Create {0}'.format(parameters['?']['type'])) return api.muranoclient(request).services.post(environment_id, path='/', data=parameters, session_id=session_id)
def service_create(request, environment_id, parameters): # we should be able to delete session # if we what add new services to this environment session_id = Session.get_or_create_or_delete(request, environment_id) LOG.debug('Service::Create {0}'.format(parameters['?']['type'])) return api.muranoclient(request).services.post(environment_id, path='/', data=parameters, session_id=session_id)
def get_data(self): try: app_id = self.kwargs['app_id'] app = api.muranoclient(self.request).packages.get(app_id) except Exception: INDEX_URL = 'horizon:murano:packages:index' exceptions.handle(self.request, _('Unable to retrieve package details.'), redirect=reverse(INDEX_URL)) return app
def environment_get(request, environment_id): session_id = Session.get(request, environment_id) LOG.debug('Environment::Get <Id: {0}, SessionId: {1}>'.format( environment_id, session_id)) client = api.muranoclient(request) env = client.environments.get(environment_id, session_id) env = _update_env(env) LOG.debug('Environment::Get {0}'.format(env)) return env
def environments_list(request): environments = [] client = api.muranoclient(request) with api.handled_exceptions(request): environments = client.environments.list() LOG.debug('Environment::List {0}'.format(environments)) for index, env in enumerate(environments): environments[index] = environment_get(request, env.id) return environments
def app_by_fqn(request, fqn, catalog=True, version=None): kwargs = {'fqn': fqn, 'catalog': catalog} glare = getattr(settings, 'MURANO_USE_GLARE', False) if glare and version: kwargs['version'] = version apps = api.muranoclient(request).packages.filter(**kwargs) try: return apps.next() except StopIteration: return None
def deployments_list(request, environment_id): LOG.debug('Deployments::List') deployments = api.muranoclient(request).deployments.list(environment_id) for deployment in deployments: if deployment.started: deployment.started = deployment.started.replace('T', ' ') if deployment.finished: deployment.finished = deployment.finished.replace('T', ' ') LOG.debug('Environment::List {0}'.format(deployments)) return deployments
def action(self, request, obj_id): try: api.muranoclient(request).packages.toggle_public(obj_id) LOG.debug('Toggle Public for package {0}.'.format(obj_id)) except exc.HTTPForbidden: msg = _("You are not allowed to perform this operation") LOG.exception(msg) messages.error(request, msg) exceptions.handle( request, msg, redirect=reverse('horizon:app-catalog:packages:index')) except exc.HTTPConflict: msg = _('Package or Class with the same name is already made ' 'public') LOG.exception(msg) messages.error(request, msg) exceptions.handle( request, msg, redirect=reverse('horizon:app-catalog:packages:index'))
def cleaned_latest_apps(request): """Returns a list of recently used apps Verifies, that apps in the list are either public or belong to current project. """ id_param = "in:" + ",".join(request.session.get('latest_apps', [])) query_params = {'type': 'Application', 'catalog': True, 'id': id_param} user_apps = list(api.muranoclient(request).packages.filter(**query_params)) request.session['latest_apps'] = collections.deque( [app.id for app in user_apps]) return user_apps
def deployment_history(request): LOG.debug('Deployment::History') deployment_history = api.muranoclient(request).deployments.list( None, all_environments=True) for deployment in deployment_history: reports = deployment_reports(request, deployment.environment_id, deployment.id) deployment.reports = reports LOG.debug('Deployment::History {0}'.format(deployment_history)) return deployment_history
def delete(self, request, obj_id): try: api.muranoclient(request).packages.delete(obj_id) except exc.HTTPNotFound: msg = _("Package with id {0} is not found").format(obj_id) LOG.exception(msg) exceptions.handle( self.request, msg, redirect=reverse('horizon:murano:packages:index')) except exc.HTTPForbidden: msg = _("You are not allowed to delete this package") LOG.exception(msg) exceptions.handle( request, msg, redirect=reverse('horizon:murano:packages:index')) except Exception: LOG.exception(_('Unable to delete package in murano-api server')) url = reverse('horizon:murano:packages:index') exceptions.handle(request, _('Unable to remove package.'), redirect=url)
def clean_latest_apps(request): cleaned_apps, cleaned_app_ids = [], [] for app_id in request.session.get('latest_apps', []): try: app = api.muranoclient(request).packages.get(app_id) except exc.HTTPNotFound: pass else: if app.type == 'Application': cleaned_apps.append(app) cleaned_app_ids.append(app_id) request.session['latest_apps'] = collections.deque(cleaned_app_ids) return cleaned_apps
def __init__(self, *args, **kwargs): request = kwargs.pop('request') super(SelectCategories, self).__init__(*args, **kwargs) try: categories = api.muranoclient(request).categories.list() if categories: category_names = [(c.name, c.name) for c in categories] self.fields['categories'].choices = category_names except (exc.HTTPException, Exception): msg = _('Unable to get list of categories') LOG.exception(msg) redirect = reverse('horizon:app-catalog:packages:index') exceptions.handle(request, msg, redirect=redirect)
def get(self, request, environment_id, task_id, optional): mc = api_utils.muranoclient(request) result = mc.actions.get_result(environment_id, task_id) if result: if result and optional == 'poll': if result['result'] is not None: # Remove content from response on first successful poll del result['result'] return JSONResponse(result) return self.compose_response(result['result'], self.is_file_returned(result), result['isException']) # Polling hasn't returned content yet return JSONResponse()
def service_delete(request, environment_id, service_id): LOG.debug('Service::Delete <SrvId: {0}>'.format(service_id)) service = service_get(request, environment_id, service_id) srv_name = service.__getitem__('name') image = service.__getitem__('url') session_id = Session.get_or_create_or_delete(request, environment_id) client = api.muranoclient(request) env = client.environments.get(environment_id, session_id) acquired = getattr(env, 'acquired_by', None) if acquired and acquired != session_id: env = client.environments.get(environment_id, acquired) Session.set(request, environment_id, acquired) env = _update_env(env) branch = env.name LOG.debug('Environment::Get in service_delete {0}'.format(env)) api.muranoclient(request).services.delete(environment_id, '/' + service_id, session_id) app = {} app['vnf_name'] = srv_name app['branch_name'] = branch app['url'] = image app['tenant_name'] = "T-Labs:Mtn-Vw" return flo_api.deleteApp(app)
def single(self, data_table, request, app_id): try: body = api.muranoclient(request).packages.download(app_id) content_type = 'application/octet-stream' response = http.HttpResponse(body, content_type=content_type) response['Content-Disposition'] = 'filename={name}.zip'.format( name=self.get_package_name(data_table, app_id)) return response except exc.HTTPException: LOG.exception(_('Something went wrong during package downloading')) redirect = reverse('horizon:murano:packages:index') exceptions.handle(request, _('Unable to download package.'), redirect=redirect)
def environment_get(request, environment_id): session_id = Session.get(request, environment_id) LOG.debug('Environment::Get <Id: {0}, SessionId: {1}>'.format( environment_id, session_id)) client = api.muranoclient(request) env = client.environments.get(environment_id, session_id) acquired = getattr(env, 'acquired_by', None) if acquired and acquired != session_id: env = client.environments.get(environment_id, acquired) Session.set(request, environment_id, acquired) env = _update_env(env, request) LOG.debug('Environment::Get {0}'.format(env)) return env