def post(self, *args, **kwargs): try: log.info('RACK deploy.') rack_id = kwargs.get('rack_id') rack = facade.get_by_pk(rack_id) try: PATH_TO_ADD_CONFIG = get_variable('path_to_add_config') REL_PATH_TO_ADD_CONFIG = get_variable('rel_path_to_add_config') except ObjectDoesNotExist: raise var_exceptions.VariableDoesNotExistException("Erro buscando a variável PATH_TO_ADD_CONFIG ou " "REL_PATH_TO_ADD_CONFIG.") path_config = PATH_TO_ADD_CONFIG + '*' + rack.nome + '*' arquivos = glob.glob(path_config) # Get all files and search for equipments of the rack for var in arquivos: filename_equipments = var.split('/')[-1] rel_filename = REL_PATH_TO_ADD_CONFIG + filename_equipments log.debug("rel_filename: %s" % rel_filename) # Check if file is config relative to this rack if rack.nome in filename_equipments: # Apply config only in spines. Leaves already have all necessary config in startup if "ADD" in filename_equipments: # Check if equipment in under maintenance. If so, does not aplly on it equipment_name = filename_equipments.split('-ADD-')[0] log.debug("equipment_name: %s" % equipment_name) try: equip = Equipamento.get_by_name(equipment_name) if not equip.maintenance: lockvar = LOCK_EQUIPMENT_DEPLOY_CONFIG_USERSCRIPT % (equip.id) output = deploy_facade.deploy_config_in_equipment_synchronous(rel_filename, equip, lockvar) log.debug("equipment output: %s" % (output)) except Exception as e: log.exception(e) raise exceptions.RackAplError(e) # SEPARAR AQUI! datas = dict() success_map = dict() success_map['rack_conf'] = True datas['sucesso'] = success_map return Response(datas, status=status.HTTP_201_CREATED) except exceptions.RackNumberNotFoundError as e: log.exception(e) raise exceptions.NetworkAPIException(e) except var_exceptions.VariableDoesNotExistException as e: log.error(e) raise api_exceptions.NetworkAPIException( 'Erro buscando a variável PATH_TO_ADD_CONFIG ou REL_PATH_TO_ADD_CONFIG. Erro: %s' % e) except Exception as e: log.exception(e) raise api_exceptions.NetworkAPIException(e)
def delete_neighbor_v6(obj_ids): """Delete NeighborV6.""" for obj_id in obj_ids: try: obj_to_delete = get_neighbor_v6_by_id(obj_id) obj_to_delete.delete_v4() except exceptions.NeighborV6DoesNotExistException as e: raise api_rest_exceptions.ObjectDoesNotExistException(str(e)) except exceptions.NeighborV6IsDeployed as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.NeighborV6Error as e: raise api_rest_exceptions.NetworkAPIException(str(e)) except Exception as e: raise api_rest_exceptions.NetworkAPIException(str(e))
def get(self, request, *args, **kwargs): """ Method to return option vip list by environment id Param environment_vip_id: environment id Return option vip object list """ try: environment_vip_id = kwargs['environment_vip_id'] options_vip = facade.get_option_vip_by_environment_vip_ids( [environment_vip_id]) if options_vip: options_vip = options_vip[0] serializer_options = serializers.OptionVipEnvironmentVipV3Serializer( options_vip, many=True, fields=self.fields, include=self.include, exclude=self.exclude, kind=self.kind) return CustomResponse(serializer_options.data, status=status.HTTP_200_OK, request=request) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException()
def delete_variable(user, variable_id): try: variable = get_by_id(variable_id) variable.delete(user) except Exception, exception: log.exception(exception) raise api_exceptions.NetworkAPIException()
def create_neighbor_v6(obj, user): """Create NeighborV6.""" try: obj_to_create = NeighborV6() obj_to_create.create_v4(obj, user) except exceptions.NeighborV6Error as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.DontHavePermissionForPeerGroupException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.LocalIpAndRemoteIpAreInDifferentVrfsException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.LocalIpAndLocalAsnAtDifferentEquipmentsException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.RemoteIpAndRemoteAsnAtDifferentEquipmentsException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.LocalIpAndPeerGroupAtDifferentEnvironmentsException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.NeighborDuplicatedException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except api_rest_exceptions.ValidationAPIException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except Exception as e: raise api_rest_exceptions.NetworkAPIException(str(e)) return obj_to_create
def get(self, *args, **kwargs): """ Lists DHCP relay ipv4 and filter by network or IP parameters. """ try: networkipv4_id = '' ipv4_id = '' if self.request.QUERY_PARAMS.get('networkipv4'): networkipv4_id = int(self.request.QUERY_PARAMS['networkipv4']) if self.request.QUERY_PARAMS.get('ipv4'): ipv4_id = int(self.request.QUERY_PARAMS['ipv4']) dhcprelayipv4_obj = DHCPRelayIPv4.objects.all() if networkipv4_id is not '': dhcprelayipv4_obj = dhcprelayipv4_obj.filter( networkipv4__id=networkipv4_id) if ipv4_id is not '': dhcprelayipv4_obj = dhcprelayipv4_obj.filter(ipv4__id=ipv4_id) serializer_options = DHCPRelayIPv4Serializer(dhcprelayipv4_obj, many=True) return Response(serializer_options.data) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException()
def networksIPv6(request): """ Lists network ipv6 and filter by url parameters. """ try: environment_vip = '' vlan_environment = '' if request.QUERY_PARAMS.get('environment_vip'): environment_vip = str(request.QUERY_PARAMS['environment_vip']) if request.QUERY_PARAMS.get('vlan_environment'): vlan_environment = str(request.QUERY_PARAMS['vlan_environment']) networkipv6_obj = NetworkIPv6.objects.all() if environment_vip: networkipv6_obj = networkipv6_obj.filter( ambient_vip__id=environment_vip) if vlan_environment: networkipv6_obj = networkipv6_obj.filter( vlan__ambiente=vlan_environment) serializer_options = NetworkIPv6Serializer(networkipv6_obj, many=True) return Response(serializer_options.data) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException()
def undeploy_neighbor_v6(neighbor_id): neighbor = NeighborV6.objects.get(id=neighbor_id) if not neighbor.created: raise exceptions.NeighborV6IsUndeployed(neighbor) locks_list = lock_resources_used_by_neighbor_v6(neighbor) try: get_created_neighbors_v4_shares_same_eqpt_and_peer(neighbor) get_created_neighbors_v6_shares_same_eqpt_and_peer(neighbor) eqpt = get_v6_equipment(neighbor) plugin = PluginFactory.factory(eqpt) plugin.bgp().undeploy_neighbor(neighbor) neighbor.deploy() except Exception as e: raise api_rest_exceptions.NetworkAPIException(str(e)) finally: destroy_lock(locks_list)
def update_neighbor_v4(obj, user): """Update NeighborV4.""" try: obj_to_update = get_neighbor_v4_by_id(obj.get('id')) obj_to_update.update_v4(obj, user) except exceptions.NeighborV4Error as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.DontHavePermissionForPeerGroupException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.LocalIpAndRemoteIpAreInDifferentVrfsException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.LocalIpAndLocalAsnAtDifferentEquipmentsException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.RemoteIpAndRemoteAsnAtDifferentEquipmentsException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.LocalIpAndPeerGroupAtDifferentEnvironmentsException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.NeighborDuplicatedException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.NeighborV4IsDeployed as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except api_rest_exceptions.ValidationAPIException as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except exceptions.NeighborV4DoesNotExistException as e: raise api_rest_exceptions.ObjectDoesNotExistException(str(e)) except Exception as e: raise api_rest_exceptions.NetworkAPIException(str(e)) return obj_to_update
def get(self, request, *args, **kwargs): """ Returns list of pool by environment vip """ try: environment_vip_id = kwargs['environment_vip_id'] pools = facade.get_pool_list_by_environmentvip(environment_vip_id) only_main_property = True # serializer pools pool_serializer = serializers.PoolV3Serializer( pools, many=True, fields=( 'id', 'identifier', ) + self.fields, include=self.include, exclude=self.exclude, kind=self.kind) # prepare serializer with customized properties response = render_to_json(pool_serializer, main_property='server_pools', obj_model=pools, request=request, only_main_property=only_main_property) return CustomResponse(response, status=status.HTTP_200_OK, request=request) except Exception, exception: log.exception(exception) raise rest_exceptions.NetworkAPIException(exception)
class EquipmentRoutersView(APIView): def get(self, request, *args, **kwargs): try: env_id = kwargs.get('env_id') data = dict() if env_id: log.info('Get Routers by environment.') routers_list = [] rot_do_ambiente = facade.get_routers_by_environment( int(env_id)) for r in rot_do_ambiente: router_id = r.equipamento.id router = Equipamento().get_by_pk(router_id) routers_list.append(facade.get_equipment_map(router)) data['routers'] = routers_list return CustomResponse(data, status=status.HTTP_200_OK, request=request) except ObjectDoesNotExist, exception: log.error(exception) raise api_exceptions.ObjectDoesNotExistException( 'Equipment Does Not Exist') except Exception, exception: log.exception(exception) raise api_exceptions.NetworkAPIException()
def delete(self, request, *args, **kwargs): try: logging.getLogger('Remove environments and vlans.') rack_id = kwargs.get("rack_id") facade.deallocate_env_vlan(request.user, rack_id) data = dict() return Response(data, status=status.HTTP_200_OK) except Exception as e: raise api_exceptions.NetworkAPIException(e)
def post(self, request, *args, **kwargs): try: log.info("Gerando o arquivo de configuracao dos equipamentos do rack") rack_id = kwargs.get("rack_id") facade.gerar_arquivo_config([rack_id]) data = dict() return Response(data, status=status.HTTP_200_OK) except Exception as e: raise api_exceptions.NetworkAPIException(e)
def get(self, request, *args, **kwargs): """ """ try: return Response({}) except Exception, exception: log.exception(exception) raise api_exceptions.NetworkAPIException()
def post(self, request, *args, **kwargs): try: log = logging.getLogger('Alocando ambientes e vlans do rack') rack_id = kwargs.get("rack_id") facade.rack_environments_vlans(rack_id, request.user) data = dict() return Response(data, status=status.HTTP_200_OK) except Exception, e: raise api_exceptions.NetworkAPIException(e)
class ChannelV3View(APIView): """ Implements CRUD routes handlers of Channels """ log = getLogger(__name__) @logs_method_apiview @permission_classes((IsAuthenticated, ChannelRead)) def get(self, request, *args, **kwargs): """ Http handler to route v3/interface/channel/ for GET method """ data = None channel_name = kwargs.get('channel_id') try: channel_id = int(channel_name) channel = ChannelV3() data = channel.retrieve_by_id(channel_id) except ValueError: # In case we have a name instead of a ID channel = ChannelV3() data = channel.retrieve(channel_name) if data is None: error = {"error": "Channel not found: '%s'" % channel_name} return Response(error, status=status.HTTP_404_NOT_FOUND) return Response(data, status=status.HTTP_200_OK) @logs_method_apiview @permission_classes((IsAuthenticated, ChannelWrite)) @raise_json_validate('channel_post_v3') @commit_on_success def post(self, request, *args, **kwargs): """ Http handler to route v3/channel for POST method """ log.info("POST - api_channel") channels = request.DATA # json_validate(SPECS.get('channel_post_v3')).validate(channels) response = [] try: for channel_data in channels.get('channels'): channel = ChannelV3() data = channel.create(channel_data) response.append({'id': data.get('channels')}) except api_exceptions.ObjectDoesNotExistException, e: raise api_exceptions.ObjectDoesNotExistException(e.detail) except api_exceptions.ValidationAPIException, e: raise api_exceptions.NetworkAPIException(e.detail)
def delete(self, request, *args, **kwargs): """ Deletes list of vlans """ obj_ids = kwargs['obj_ids'].split(';') locks_list = create_lock(obj_ids, LOCK_VLAN) try: facade.delete_vlan(obj_ids) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException(exception)
def post(self, request, *args, **kwargs): """ Create Interface URL: api/v3/interface/ """ response = list() interfaces = request.DATA json_validate(SPECS.get('interface_post')).validate(interfaces) for i in interfaces.get('interfaces'): try: interface = facade.create_interface(i) response.append({'id': interface.id}) except api_exceptions.NetworkAPIException, e: log.error(e) raise api_exceptions.NetworkAPIException(e) except api_exceptions.ValidationAPIException, e: log.error(e) raise api_exceptions.NetworkAPIException(e)
def post(self, request, *args, **kwargs): """ Associates an interface to an environment. URL: api/v3/interface/environments/ """ response = list() interface_environments = request.DATA # json_validate(SPECS.get('interface_environments_post')).validate(interface_environments) for i in interface_environments.get('interface_environments'): try: int_envs = facade.create_interface_environments(i) response.append({'id': int_envs.id}) except api_exceptions.NetworkAPIException, e: log.error(e) raise api_exceptions.NetworkAPIException(e) except api_exceptions.ValidationAPIException, e: log.error(e) raise api_exceptions.NetworkAPIException(e)
def get(self, request, *args, **kwargs): try: log.info("GET Datacenter") dc = facade.listdc() data = dict() data['dc'] = dc return Response(data, status=status.HTTP_200_OK) except Exception, e: raise api_exceptions.NetworkAPIException(e)
def post(self, *args, **kwargs): log.info('RACK Foreman.') try: rack_id = kwargs.get('rack_id') rack = facade.get_by_pk(rack_id) facade.api_foreman(rack) return Response({}, status=status.HTTP_201_CREATED) except exceptions.RackNumberNotFoundError as e: log.exception(e) raise exceptions.NetworkAPIException(e) except var_exceptions.VariableDoesNotExistException as e: log.error(e) raise api_exceptions.NetworkAPIException( 'Erro ao registrar o Switch no Foreman. Erro: %s' % e) except Exception as e: log.exception(e) raise api_exceptions.NetworkAPIException(e)
def delete(self, request, *args, **kwargs): """ Deletes list of equipments """ obj_ids = kwargs['obj_id'].split(';') locks_list = create_lock(obj_ids, LOCK_EQUIPMENT) try: facade.delete_equipment(obj_ids) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException(exception)
def delete(self, request, *args, **kwargs): """ Deletes list of vip request """ vip_request_ids = kwargs['vip_request_ids'].split(';') locks_list = create_lock(vip_request_ids, LOCK_VIP) keepip = request.GET.get('keepip') or '0' try: facade.delete_vip_request(vip_request_ids, keepip) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException(exception)
def get_neighbor_v6_by_search(search=None): """Return a list of NeighborV6's by dict.""" try: objects = NeighborV6.objects.filter() search_dict = search if search else dict() object_map = build_query_to_datatable_v3(objects, search_dict) except FieldError as e: raise api_rest_exceptions.ValidationAPIException(str(e)) except Exception as e: raise api_rest_exceptions.NetworkAPIException(str(e)) else: return object_map
def delete(request): """ Delete Vip Request And Optional Related Pools. """ try: ids = request.DATA.get('ids') delete_pools = request.DATA.get('delete_pools', True) if delete_pools: vports_pool = VipPortToPool.objects.filter( requisicao_vip__id__in=ids) for vport in vports_pool: server_pool = vport.server_pool related = VipPortToPool.objects.filter( server_pool=server_pool).exclude( requisicao_vip=vport.requisicao_vip) if related: raise pool_exceptions.PoolConstraintVipException() vport.delete(request.user) for member in server_pool.serverpoolmember_set.all(): member.delete(request.user) server_pool.delete(request.user) vips_request = RequisicaoVips.objects.filter(id__in=ids) for vrequest in vips_request: """ if vip has DSRl3 """ # traffic=OptionVip.objects.filter(nome_opcao_txt='DSRL3') # traffic.id should be equal 48 # if vrequest.trafficreturn.id == 48: # try: # dsrl3= DsrL3_to_Vip.get_by_vip_id(ids) # dsrl3.delete(request.user) # except RequisicaoVipsMissingDSRL3idError, e: # log.error(u'Requisao Vip nao possui id DSRL3 correspondente cadastrado no banco') # raise RequisicaoVipsMissingDSRL3idError( # e, 'Requisao Vip com id %s possui DSRl3 id não foi encontrado' % # ids) vrequest.remove(request.user, vrequest.id) syncs.delete_new(ids) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException()
def get(self, request, *args, **kwargs): """ Returns a list of pools with updated states of members """ try: pool_ids = kwargs.get('pool_ids').split(';') checkstatus = request.GET.get('checkstatus') or '0' response = dict() server_pools = models_vips.ServerPool.objects.filter( id__in=pool_ids) if checkstatus == '1': serializer_server_pool = serializers.PoolV3Serializer( server_pools, many=True) mbr_state = facade_pool_deploy.get_poolmember_state( serializer_server_pool.data) for server_pool in server_pools: if mbr_state.get(server_pool.id): query_pools = models_vips.ServerPoolMember.objects.filter( server_pool=server_pool) for pm in query_pools: member_checked_status = mbr_state[server_pool.id][ pm.id] pm.member_status = member_checked_status pm.last_status_update = datetime.now() pm.save(request.user) # get pools updated server_pools = models_vips.ServerPool.objects.filter( id__in=pool_ids) serializer_server_pool = serializers.PoolV3Serializer(server_pools, many=True) response['server_pools'] = serializer_server_pool.data return CustomResponse(response, status=status.HTTP_200_OK, request=request) except Exception, exception: log.error(exception) raise rest_exceptions.NetworkAPIException(exception)
def post(self, request, *args, **kwargs): """ Create Interface URL: api/v3/interface/connections/<interface_a>/<interface_b> data: [{"id": id1, "link": "front"},{"id": id2, "link": "back"}] """ interfaces = request.DATA try: facade.link_interface(interfaces.get('interfaces')) except api_exceptions.NetworkAPIException, e: log.error(e) raise api_exceptions.NetworkAPIException(e)
def post(self, *args, **kwargs): try: log.info('RACK Foreman.') rack_id = kwargs.get('rack_id') rack = facade.get_by_pk(rack_id) # Create Foreman entries for rack switches facade.api_foreman(rack) raise api_exceptions.NetworkAPIException('chegou') return Response(datas, status=status.HTTP_201_CREATED) except exceptions.RackNumberNotFoundError, e: log.exception(e) raise exceptions.NetworkAPIException(e)
def patch(self, request, *args, **kwargs): """ Updates list of vip request in equipments """ vips = request.DATA json_validate(SPECS.get('vip_request_patch')).validate(vips) locks_list = create_lock(vips.get('vips'), LOCK_VIP) try: response = facade.patch_real_vip_request( vips['vips'], request.user) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException(exception)
def get(self, request, *args, **kwargs): """ Method to return finality, client or environment vip list. Param request.GET["finality"]: finality of environment(optional) Param request.GET["client"]: client of environment(optional) Param request.GET["environmentp44"]: environmentp44(optional) Return finality list: when request has no finality and client. Return client list: when request has only finality. Return environment vip list: when request has finality and client. Return object environment vip: when request has finality and client and environmentp44. """ try: data = request.GET finality = data.get('finality', '') client = data.get('client', '') environmentp44 = data.get('environmentp44', '') if client != '' and finality != '': if environmentp44 != '': obj = EnvironmentVip().get_by_values( finality, client, environmentp44) many = False else: obj = EnvironmentVip( ).list_all_ambientep44_by_finality_and_cliente( finality, client) many = True evip_values = serializers.EnvironmentVipV3Serializer( obj, many=many, fields=self.fields, include=self.include, exclude=self.exclude, kind=self.kind).data elif finality != '': evip_values = EnvironmentVip().list_all_clientes_by_finalitys( finality) else: evip_values = EnvironmentVip().list_all_finalitys() return CustomResponse(evip_values, status=status.HTTP_200_OK, request=request) except Exception, exception: log.error(exception) raise api_exceptions.NetworkAPIException()