Esempio n. 1
0
 async def get(self):
     """
     Devuelve la lista de Switches
     """
     try:
         entities = await SwitchService.get_all()
         return ApiResponse(interfaces.many_schema.dump(entities).data)
     except JobTemplateNotFound:
         raise ApiException(
             'No existe un playbook para obtener la infrmación de las interfaces'
         )
     except PlaybookTimeout:
         raise ApiException(
             'La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Esempio n. 2
0
 async def post(self, switch_id: int):
     """
     Resetea la interface indicada
     """
     try:
         nic_name = request.args.get('nic_name')
         result = await NicsService.reset_switch_nic(switch_id, nic_name)
         return ApiResponse(result)
     except SwitchNotFound:
         raise ApiException(f'No se encuentra un switch con el id:{switch_id}')
     except JobTemplateNotFound:
         raise ApiException('No existe un playbook para obtener la infrmación de las interfaces')
     except PlaybookTimeout:
         raise ApiException('La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Esempio n. 3
0
 def authorize_handler(*args, **kwargs):
     public_key = current_app.config['PUBLIC_KEY']
     audience = current_app.config['AUDIENCE']
     token = request.headers.get('X-API-Key')
     if not public_key:
         raise ApiException(f'Public key is undefined',
                            code='NotAuthorized')
     if not audience:
         raise ApiException(f'Audience is undefined', code='NotAuthorized')
     if not token:
         raise ApiException(f'Authorization not found',
                            code='NotAuthorized')
     try:
         jwt.decode(token,
                    public_key,
                    algorithms=['RS256'],
                    audience=audience)
     except JWTClaimsError as error:
         raise ApiException(error)
     except ExpiredSignatureError as error:
         raise ApiException(error)
     except JWTError as error:
         raise ApiException(error)
     except JWKError as error:
         raise ApiException(error)
     return func(*args, **kwargs)
Esempio n. 4
0
 async def get(self, id: int):
     """
     Obtiene un único Switch por ID.
     """
     try:
         switch = await SwitchService.get_by_id(id)
         return ApiResponse(interfaces.single_schema.dump(switch).data)
     except SwitchNotFound:
         raise ApiException(f'No se encuentra un switch con el id:{id}')
     except JobTemplateNotFound:
         raise ApiException(
             'No existe un playbook para obtener la infrmación de las interfaces'
         )
     except PlaybookTimeout:
         raise ApiException(
             'La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Esempio n. 5
0
 async def cancel_find_by_mac(switches_ids):
     for sw_id in switches_ids:
         switch = await SwitchService.get_by_id(sw_id)
         if switch == None:
             raise ApiException(
                 f'No se encuentra el switch con el id {sw_id}', 404)
         await JobService.cancel_jobs_by_template_name_and_host_name(
             f'{ENV}-show-mac-address-table', switch.name)
     return True
Esempio n. 6
0
 async def get(switch_id):
     switch = await SwitchService.get_by_id(switch_id)
     if switch == None:
         raise ApiException(
             f'No se encuentra el switch con el id {switch_id}', 404)
     extra_vars = dict()
     body = dict(limit=switch.name, extra_vars=extra_vars)
     return await JobService.run_job_template_by_name(
         'show-mac-address-table', body)
Esempio n. 7
0
 async def get(self, switch_id: int):
     """
     Devuelve la lista de Interfaces obtenidas desde el CISCO PRIME
     """
     try:
         result = await NicsService.get_from_prime_by_switch_id(switch_id)
         return ApiResponse(result)        
     except SwitchNotFound:
         raise ApiException(f'En el Cisco Prime no se encuentra un switch con el id:{switch_id}')
Esempio n. 8
0
 async def get(self, switch_id: int):
     """
     Devuelve la lista de Interfaces
     """
     # List jobs templates
     # '/api/v2/job_templates/'
     try:
         result = await NicsService.get_by_switch_id(switch_id)
         return ApiResponse(result)
         #return ApiResponse(RESULT)
     except SwitchNotFound:
         raise ApiException(f'No se encuentra un switch con el id:{switch_id}')
     except JobTemplateNotFound:
         raise ApiException('No existe un playbook para obtener la información de las interfaces')
     except PlaybookTimeout:
         raise ApiException('La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Esempio n. 9
0
 def post(self):
     """
     Crea un nuevo Job.
     """
     json_data = request.get_json()
     if json_data is None:
         raise ApiException('JSON body is undefined')
     body = interfaces.single_schema.load(json_data).data
     Job = JobService.create(body)
     return ApiResponse(interfaces.single_schema.dump(Job).data)
Esempio n. 10
0
 async def get(self, switch_id: int):
     """
     Devuelve la lista de todaslas macs del switch
     """
     try:
         resp = await MacService.get(switch_id)
         return ApiResponse(resp)
     except SwitchNotFound:
         raise ApiException(
             f'No se encuentra un switch con el id:{switch_id}')
     except JobTemplateNotFound:
         raise ApiException(
             'No existe un playbook para obtener la infrmación de las interfaces'
         )
     except PlaybookTimeout:
         raise ApiException(
             'La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Esempio n. 11
0
 def put(self, id: int):
     """
     Actualiza un único Switch por ID.
     """
     try:
         body = interfaces.single_schema.load(request.json).data
         Switch = SwitchService.update(id, body)
         return ApiResponse(interfaces.single_schema.dump(Switch).data)
     except SwitchNotFound:
         raise ApiException(f'No se encuentra un switch con el id:{id}')
Esempio n. 12
0
    def log_handler(*args, **kwargs):
        token = request.headers.get('Token')
        if not token:
            return ApiResponse({"Error": "Token not found"}, 400)
        http_method = request.method
        http_url = request.url
        payload = json.dumps(request.get_json())

        token_dec = jwt.decode(token,
                               PUBLIC_KEY,
                               algorithms=['RS256'],
                               audience='dashboard',
                               options={
                                   "verify_signature": False,
                                   "verify_aud": False,
                                   "verify_iat": False,
                                   "verify_exp": False,
                                   "verify_nbf": False,
                                   "verify_iss": False,
                                   "verify_sub": False,
                                   "verify_jti": False,
                                   "verify_at_hash": False
                               })
        user_name = token_dec["name"]
        user_email = token_dec["email"]
        date_start = datetime.datetime.utcnow()
        try:
            response = func(*args, **kwargs)
        except ApiException as err:
            response = err
        except Exception as err:
            response = ApiException('Internal server error', 500, str(err))

        if isinstance(response, ApiResponse):
            response_status_code = response.status
            message = str(response.value or "")[0:250] + "..."
        elif isinstance(response, ApiException):
            message = response.message
            response_status_code = response.status
            response = ApiResponse(message, response_status_code)
        date_end = datetime.datetime.utcnow()
        LogService.create({
            "http_method": http_method,
            "http_url": http_url,
            "payload": payload,
            "user_name": user_name,
            "user_email": user_email,
            "date_start": date_start,
            "response_status_code": response_status_code,
            "message": message,
            "date_end": date_end
        })
        return response
Esempio n. 13
0
 def authorize_handler(*args, **kwargs):
     token = request.headers.get('Token')
     if not token:
         return ApiResponse({"Error": "Token not found"}, 400)
     try:
         jwt.decode(token,
                    PUBLIC_KEY,
                    algorithms=['RS256'],
                    audience='dashboard',
                    options={
                        "leeway": 120,
                        "verify_exp": False
                    })
     except JWTError as error:
         raise ApiException(error)
     except JWTClaimsError as error:
         raise ApiException(error)
     except ExpiredSignatureError as error:
         raise ApiException(error)
     except JWKError as error:
         raise ApiException(error)
     return func(*args, **kwargs)
Esempio n. 14
0
 async def get(self):
     """
     Devuelve la lista de Switches
     """
     try:
         entities = await SwitchService.get_all()
         ansible_switches_vars = {}
         for x in entities:
             ansible_switches_vars[x.name] = {
                 "ansible_host": x.ip,
                 "ansible_become": True,
                 "ansible_become_method": "enable",
                 "ansible_connection": "network_cli",
                 "ansible_network_os": "ios",
                 "ansible_port": x.ansible_ssh_port or 22,
                 "ansible_user": decode(x.ansible_user),
                 "ansible_ssh_pass": decode(x.ansible_ssh_pass)
             }
         ansible_switches_hostnames = map(lambda x: x.name, entities)
         sw_inv = {
             'group': {
                 'hosts': list(ansible_switches_hostnames),
             },
             '_meta': {
                 'hostvars': ansible_switches_vars
             }
         }
         return ApiResponse(sw_inv)
     except JobTemplateNotFound:
         raise ApiException(
             'No existe un playbook para obtener la infrmación de las interfaces'
         )
     except PlaybookTimeout:
         raise ApiException(
             'La ejecución de la tarea supero el tiempo del timeout')
     except PlaybookFailure:
         raise ApiException('Fallo la ejecución de la tarea')
Esempio n. 15
0
 async def find_by_mac(switches_ids):
     macs_results = []
     switches = []
     # Carga las macs de todos los switches pasados en switches_ids
     for sw_id in switches_ids:
         switch = await SwitchService.get_by_id(sw_id)
         if switch == None:
             raise ApiException(
                 f'No se encuentra el switch con el id {sw_id}', 404)
         else:
             switches.append({"id": sw_id, "name": switch.name})
     await asyncio.gather(*[
         MacService.show_mac_addr_table(sw, macs_results) for sw in switches
     ])
     return macs_results
Esempio n. 16
0
    async def get_from_prime_by_switch_id(switch_id):
        """
        Devuelve la información de todas las interfaces a través
        del la api del Cisco Prime, quien consulta directamente al switch.

        Args:
        switch_id (int): Identidad del switch
        """
        result = dict()
        try:
            from_prime = await prime_fetch(
                f'/webacs/api/v4/data/InventoryDetails/{switch_id}.json')
            for interface in from_prime['queryResponse']["entity"][0][
                    "inventoryDetailsDTO"]["ethernetInterfaces"][
                        "ethernetInterface"]:
                result[interface["name"]] = interface
            return result
        except Exception as err:
            print("Error in get_from_prime: " + str(err), flush=True)
            raise ApiException(
                "Error al cargar nics del Cisco Prime. Error: " + str(err))