def on_delete(self, req, resp, tenant_id): """ Method to delete a Tenant. This endpoint is only accessible to the Super Admin. Before deleting the tenant the method ensures the tenant is disabled. :param tenant_id: The tenant id to delete :return: 204 No Content - When the tenant is successfully deleted """ # Configure correct endpoint endpoint = TenantAPI.KS_ENDPOINT + '/' + tenant_id # Ensure the tenant is disabled ks_domain = dict(enabled=False) request_post_patch(endpoint, 'PATCH', headers={ 'Content-Type': 'application/json', 'X-Auth-Token': req.headers['X-AUTH-TOKEN'] }, json=dict(domain=ks_domain), service_name=TenantAPI.SERVICE_NAME) request(endpoint, method='DELETE', headers={ 'Content-Type': 'application/json', 'X-Auth-Token': req.headers['X-AUTH-TOKEN'] }, service_name=TenantAPI.SERVICE_NAME) resp.status = HTTP_204
def on_delete(self, req, resp, **kwargs): if len(kwargs) != 1 or 'package_id' not in kwargs: raise HTTPNotFound() endpoint = '{}{}'.format(ConfReader().get('APP_CATALOGUE', 'url'), kwargs.get('package_id')) request(endpoint, method='DELETE') resp.status = HTTP_204
def on_delete(self, req, resp, tal_id): """ :param req: :param resp: :param tal_id: :return: """ request(ConfReader().get('TAL_SERVICE', 'url') + tal_id, method='DELETE') resp.status = HTTP_204
def on_post(self, req, resp, tenant_id, parsed): """ Method to create new user. This endpoint is accessible to Super Admin and tenant admin. The name of each user must be unique within a tenant. :return: 201 Created - When the user is successfully created """ data = parsed.get('user') # Validate Role ID role_endpoint = RoleAPI.KS_ENDPOINT + '/' + data.get('role').get('id') request(role_endpoint, headers={ 'Content-Type': 'application/json', 'X-Auth-Token': req.headers['X-AUTH-TOKEN'] }, service_name=UserAPI.SERVICE_NAME) # Build KS object ks_user = dict() ks_user['description'] = data.get('description', None) ks_user['name'] = data.get('username') ks_user['password'] = data.get('password') ks_user['enabled'] = data.get('enabled', True) ks_user['domain_id'] = tenant_id # Request user creation r = request_post_patch(UserAPI.KS_ENDPOINT, method='POST', headers={ 'Content-Type': 'application/json', 'X-Auth-Token': req.headers['X-AUTH-TOKEN'] }, json=dict(user=ks_user), service_name=UserAPI.SERVICE_NAME) # Get user object user = UserAPI.convert_ks_user_user(req, r=r) # Add specified role endpoint = "{}/{}/users/{}/roles/{}".format(TenantAPI.KS_ENDPOINT, tenant_id, user.get('id'), data.get('role').get('id')) request_post_patch( endpoint, method='PUT', headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, service_name=UserAPI.SERVICE_NAME) user['role'] = dict(id=data.get('role').get('id')) resp.status = HTTP_201 resp.body = self.format_body(dict(user=user))
def on_delete(self, req, resp, tenant_id, user_id): """ Method to delete a user. This endpoint is only accessible to the Super Admin and tenant admin. The user is only deleted if disabled before. :param tenant_id: The tenant id where the user belongs to :return: 204 No Content - When the tenant is successfully deleted """ endpoint = UserAPI.KS_ENDPOINT + '/' + user_id request(endpoint, method='DELETE', headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, service_name=UserAPI.SERVICE_NAME) resp.status = HTTP_204
def on_delete(self, req, resp, role_id): """ Deletes a given role :param role_id: The role id to be deleted :return: 204 NO CONTENT: Role deleted with success """ endpoint = RoleAPI.KS_ENDPOINT + '/' + role_id request(endpoint, method='DELETE', headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}) resp.status = HTTP_204
def on_get(self, req, resp, source, **kwargs): """ Retrieve the list of flow metrics collected on a given SourceIP. Additionally it can be provided the DestinationIP and DestinationPort. This method accepts also the start_time and end_time as query parameters :param source: SourceIP of the flow. :param kwargs: It can be: only DestinationIP or DestinationIP and DestinationPort :return: List with flow metrics """ dimensions_query = 'FlowID:' + source if kwargs: dimensions_query += ',' + ','.join( ['{}:{}'.format(key, value) for key, value in kwargs.items()]) req.context['query_parameters']['dimensions'] = dimensions_query headers = Authenticate.get_header() # Insert the auth header r = request(ConfReader().get('MONASCA', 'url') + FlowMetrics.ENDPOINT, headers=headers, params=req.context['query_parameters']) req.context['query_parameters'].pop('dimensions') resp.body = self.format_body(FlowMetrics.__convert_result__( r.json(), req.uri, req), from_dict=True) resp.status = str(r.status_code)
def __get_user_role__(req, tenant_id, user): """ Internal method to query the identity service for the role of a specific user. This method converts the array roles into a single role object, since the user will only have a single role. :param req: WSGI request object to get the headers :param tenant_id: The tenant id to check user's role :param user: user object to request the role :return: User object with role key updated. """ endpoint = "{}/{}/users/{}/roles/".format(TenantAPI.KS_ENDPOINT, tenant_id, user) r = request(endpoint, headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, ignore_exception=True, service_name=UserAPI.SERVICE_NAME) if r.status_code != 200: return None # If user requires himself without being admin can't see it's roles data = json.loads(r.text) data = data['roles'] if data: # The user will only have a role in a tenant return dict(id=data[0]['id'], name=data[0]['name'])
def get_all_alarms(self, req, resp): if 'limit' not in req.context.get('query_parameters'): req.context.get('query_parameters')['limit'] = 5 headers = Authenticate.get_header() # Insert the auth header r = request(ConfReader().get('MONASCA', 'url') + Alarm.ENDPOINT, params=req.context['query_parameters'], headers=headers) resp.body = self.format_body(Alarm.__convert_result__(r.json(), req.uri, req), from_dict=True) resp.status = str(r.status_code)
def get_all(self, req, resp, **kwargs): r = request(ConfReader().get('SERVICE_INVENTORY', 'url'), service_name=SERVICE_NAME) services = [] for service in r.json(): services.append( InventoryRepresentation.build_from_dict(service).__dict__) resp.status = HTTP_200 resp.body = self.format_body(services)
def _get_tal_list_(self, req, resp, value): _tal_ = list( map(lambda _value_: _value_.get('reaction')[0].get('diagnosis').get('symptom').get('oid'), value)) # Collect symptom status status = request(ConfReader().get('TAL_WP4_ENGINE', 'url')).json() tal_list = [] for symptom in _tal_: symptom_status = status.get(symptom, 'disabled') tal_list.append(dict(symptom=symptom, status=symptom_status)) return tal_list
def __get_all_packages__(self, req, resp): if 'app-class' in req.context.get( 'query_parameters', {}).keys() and req.context['query_parameters'].get( 'app-class').upper() not in PackageAPI.APP_CLASS_TYPES: logger.info('User is requesting an invalid app type, {}'.format( req.context['query_parameters'].get('app-class').upper())) raise HTTPNotFound() endpoint = ConfReader().get('APP_CATALOGUE', 'url') + 'ids' r = request(endpoint, params=req.context.get('query_parameters', {})) resp.body = self.format_body(dict(app=json.loads(r.text)), from_dict=True)
def on_get(self, req, resp, metric_name): req.context['query_parameters']['name'] = metric_name headers = Authenticate.get_header() # Insert the auth header r = request(ConfReader().get('MONASCA', 'url') + MetricMeasurement.ENDPOINT, headers=headers, params=req.context['query_parameters']) resp.body = self.format_body(MetricMeasurement.__convert_result__( r.json(), req.uri, req), from_dict=True) resp.status = str(r.status_code)
def get_single_alarm(self, req, resp, alarm_id): headers = Authenticate.get_header() # Insert the auth header r = request(ConfReader().get('MONASCA', 'url') + Alarm.ENDPOINT + '/' + alarm_id, params=req.context['query_parameters'], headers=headers) alarm = r.json() alarm.pop('links') alarm.pop('link') alarm.get('alarm_definition').pop('links') resp.body = self.format_body(alarm, from_dict=True) resp.status = str(r.status_code)
def __get_metric__(dimensions_query): """ Collect all the metrics in a given flow. :param dimensions_query: Dictionary with all Source and Destination information. :return: List with metrics collected on a given flow """ headers = Authenticate.get_header() # Insert the auth header r = request(ConfReader().get('MONASCA', 'url') + FlowMetrics.ENDPOINT, params=dimensions_query, headers=headers) metrics = FlowMetrics.__convert_result__(r.json(), None, None).get('metrics') if len(metrics) == 0: raise HTTPNotFound return metrics
def __get_by_filter__(self, req, resp, package_id, endpoint): if endpoint.lower() not in PackageAPI.PACKAGE_ENDPOINTS: raise HTTPNotFound() __endpoint__ = "{}{}/{}".format( ConfReader().get('APP_CATALOGUE', 'url'), package_id, endpoint) r = request(__endpoint__) if r.text: resp.body = self.format_body( {endpoint.lower()[len('app-'):]: json.loads(r.text)}, from_dict=True) else: resp.body = self.format_body({endpoint.lower()[len('app-'):]: {}}, from_dict=True) resp.status = HTTP_200
def __query_measurements__(self, req, resp, query_parameters): """ Method to construct the query string and retrieve the measurements from Monasca :param query_parameters: The InstanceID/FlowID and MetricID of the request """ if 'query_parameters' in req.context: query_parameters.update(req.context['query_parameters']) headers = Authenticate.get_header() r = request(ConfReader().get('MONASCA', 'url') + MeasurementAPI.ENDPOINT, params=query_parameters, headers=headers) resp.body = self.format_body(MeasurementAPI.__convert_result__( r.json(), req.uri, req), from_dict=True) resp.status = str(r.status_code)
def get_specific_tenant(self, req, resp, tenant_id): """ Method to retrieve a single tenant. This endpoint is accessible to a Tenant Admin, that can only query it's tenant and Super Admin. :param tenant_id: Tenant ID to retrieve :return: 200 OK - When the tenant is found and successfully retrieved """ # Configure correct endpoint endpoint = TenantAPI.KS_ENDPOINT + '/' + tenant_id # Request the tenant r = request(endpoint, headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, service_name=TenantAPI.SERVICE_NAME) tenant = TenantAPI.convert_domain_tenant(req, r=r) resp.body = self.format_body(dict(tenant=tenant), from_dict=True) resp.status = HTTP_200
def get_specific_role(self, req, resp, role_id): """ Method to retrieve a single role based on its id :param role_id: The role id to search for. :return: 200 OK - When all roles are retrieved with success 404 Not Found - When the provided id don't exist on the identity service Role Process Errors """ endpoint = RoleAPI.KS_ENDPOINT + '/' + role_id r = request(endpoint, headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, service_name=RoleAPI.SERVICE_NAME) data = json.loads(r.text) role = data.get('role') role = RoleAPI.convert_ks_role_role(role) resp.body = self.format_body(dict(role=role), from_dict=True) resp.status = HTTP_200
def get_specific_user(self, req, resp, tenant_id, user_id): """ Method to retrieve a single user. This endpoint is accessible to a Super ADMIN and Tenant Admin. :param tenant_id: The tenant the user belong to :param user_id: The user id to retrieve :return: 200 OK - When the user is found and successfully retrieved """ endpoint = UserAPI.KS_ENDPOINT + '/' + user_id # Request the User r = request(endpoint, headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, service_name=UserAPI.SERVICE_NAME) # Converts keystone user and update the role user = UserAPI.convert_ks_user_user(req, r=r) resp.body = self.format_body(dict(user=user)) resp.status = HTTP_200
def get_all_roles(self, req, resp): """ Method to retrieve all roles from the identity service. This endpoint is only accessible to Super ADMIN users or tenant admin users. Only cross domain roles are shown, since there's no intention in creating special roles for each tenant. :return: 200 OK - When all roles are retrieved with success Role Process Errors """ r = request(RoleAPI.KS_ENDPOINT, headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, service_name=RoleAPI.SERVICE_NAME) data = json.loads(r.text) data = data['roles'] # Filter cross domain roles only data = list(filter(lambda role: not role.get('domain_id'), data)) # Convert objects data = list(map(lambda role: RoleAPI.convert_ks_role_role(role), data)) resp.body = self.format_body(dict(roles=data), from_dict=True) resp.status = HTTP_200
def on_get(self, req, resp, instance_id): """ Retrieve the list of metrics collected for a specific VM :param req: Request WSGI object :param resp: Response WSGI object :param instance_id: VM ID to search for the metrics. """ dimensions_query = 'InstanceID:' + instance_id headers = Authenticate.get_header() # Insert the auth header req.context['query_parameters']['dimensions'] = dimensions_query r = request(ConfReader().get('MONASCA', 'url') + VMMetricsAPI.ENDPOINT, params=req.context['query_parameters'], headers=headers) req.context['query_parameters'].pop('dimensions') resp.body = self.format_body(VMMetricsAPI.__convert_result__( r.json(), req.uri, req), from_dict=True) resp.status = str(r.status_code)
def get_all_tenants(self, req, resp): """ Method to retrieve all tenants from the identity service. This endpoint is only accessible to Super ADMIN users. :return: 200 OK - When all tenants are retrieved with success """ r = request(TenantAPI.KS_ENDPOINT, headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, service_name=TenantAPI.SERVICE_NAME) data = json.loads(r.text) # Convert object tenants = data.get('domains', None) tenants = list( map( lambda domain: self.convert_domain_tenant( req, specific=False, domain=domain), tenants)) links = data.get('links', None) links["self"] = req.uri resp.body = self.format_body(dict(tenants=tenants, links=links), from_dict=True)
def get_all_tenant_users(self, req, resp, tenant_id): """ Method to retrieve all users from the identity service. This endpoint is only accessible to Super ADMIN users or tenant admin users. :param tenant_id: The tenant the users belong to :return: 200 OK - When all users within a tenant are retrieved with success """ r = request(UserAPI.KS_ENDPOINT, headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, params=dict(domain_id=tenant_id), service_name=UserAPI.SERVICE_NAME) data = json.loads(r.text) users = data['users'] # Converts keystone user and update the role users = list( map( lambda user: UserAPI.convert_ks_user_user( req, specific=False, user=user), users)) #users = list(map(lambda user: UserAPI.__get_user_role__(req, tenant_id, user), users)) resp.body = self.format_body(dict(users=users), from_dict=True) resp.status = HTTP_200
def on_get(self, req, resp, source, **kwargs): """ Retrieve the list of flows collected on a given SourceIP. Additionally it can be provided the DestinationIP and DestinationPort. This method accepts also the start_time and end_time as query parameters :param source: SourceIP of the flow. :param kwargs: It can be: only DestinationIP or DestinationIP and DestinationPort :return: List with flows """ dimensions_query = 'SourceIP:' + source if kwargs: dimensions_query += ',' + ','.join(['{}:{}'.format(key, value) for key, value in kwargs.items()]) req.context['query_parameters']['dimensions'] = dimensions_query if 'metric' not in req.context['query_parameters']: raise HTTPBadRequest(title='Missing Metric', description='Missing metric name to collect metrics', code='300') req.context['query_parameters']['name'] = req.context['query_parameters'].get('metric') req.context['query_parameters']['group_by'] = 'SourceIP,DestinationIP,DestinationPort,FlowID' req.context['query_parameters']['merge_metrics'] = 'true' if 'start_time' not in req.context['query_parameters']: d = datetime.now() - timedelta(days=1) req.context['query_parameters']['start_time'] = d.isoformat() headers = Authenticate.get_header() # Insert the auth header r = request(ConfReader().get('MONASCA', 'url') + Flows.ENDPOINT, params=req.context['query_parameters'], headers=headers) req.context['query_parameters'].pop('group_by') req.context['query_parameters'].pop('merge_metrics') req.context['query_parameters'].pop('name') resp.body = self.format_body(Flows.__convert_result__(r.json(), req.uri, req), from_dict=True) resp.status = str(r.status_code)
def on_patch(self, req, resp, parsed, tenant_id, user_id): """ Method to update a User. This endpoint is only accessible to the Super Admin and tenant admin. It's not required the full object only the updated fields. :return: 200 OK - When the user is edited successfully """ print('Im patching') # Validate incoming data data = parsed.get('user') # Build KS object based on user's role ks_user = dict() ks_user['description'] = data.get('description', None) ks_user['name'] = data.get('username', None) ks_user['enabled'] = data.get('enabled', None) ks_user['password'] = data.get('password', None) ks_user = {k: v for k, v in ks_user.items() if v is not None} # Generator to clear None value keys # Patch or get user when only role is updated endpoint = UserAPI.KS_ENDPOINT + '/' + user_id r = request_post_patch( endpoint, method='PATCH', headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, json=dict(user=ks_user), service_name=UserAPI.SERVICE_NAME) # Converts keystone user and update the role user = UserAPI.convert_ks_user_user(req, r=r) if 'role' not in data: resp.status = HTTP_200 resp.body = self.format_body(dict(user=user)) return # Update role # Validate Role ID role_endpoint = RoleAPI.KS_ENDPOINT + '/' + data.get('role').get('id') request(role_endpoint, headers={ 'Content-Type': 'application/json', 'X-Auth-Token': req.headers['X-AUTH-TOKEN'] }, service_name=RoleAPI.SERVICE_NAME) # Disable current role role_id = user.get('role').get('id') endpoint = "{}/{}/users/{}/roles/{}".format(TenantAPI.KS_ENDPOINT, tenant_id, user_id, role_id) request(endpoint, method='DELETE', headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, service_name=UserAPI.SERVICE_NAME) # Set new role endpoint = "{}/{}/users/{}/roles/{}".format(TenantAPI.KS_ENDPOINT, tenant_id, user_id, data.get('role').get('id')) request_post_patch( endpoint, method='PUT', headers={'X-Auth-Token': req.headers['X-AUTH-TOKEN']}, service_name=RoleAPI.SERVICE_NAME) user['role'] = dict(id=data.get('role').get('id')) resp.status = HTTP_200 resp.body = self.format_body(dict(user=user))
def __get_single_app__(self, req, resp, package_id): endpoint = "{}/{}".format(ConfReader().get('APP_CATALOGUE', 'url'), package_id) r = request(endpoint) resp.body = self.format_body(dict(app=json.loads(r.text)), from_dict=True)
def __request_service__(s_id): endpoint = '{}/{}'.format(ConfReader().get('SERVICE_INVENTORY', 'url'), s_id) r = request(endpoint, service_name=SERVICE_NAME) return Service.build_from_dict(r.json())