diff --git a/networkapi/api_asn/models.py b/networkapi/api_asn/models.py index f88d510c8..e10bd7a49 100644 --- a/networkapi/api_asn/models.py +++ b/networkapi/api_asn/models.py @@ -61,6 +61,28 @@ def get_by_pk(cls, id): cls.log.error(u'Failure to search the ASN.') raise exceptions.AsnError(u'Failure to search the ASN.') + def get_by_asn(cls, asn): + """Get AS by id. + + :return: AS. + + :raise AsnNotFoundError: As not registered. + :raise AsnError: Failed to search for the As. + :raise OperationalError: Lock wait timeout exceeded + """ + try: + return Asn.objects.get(asn=asn) + except ObjectDoesNotExist: + cls.log.error(u'ASN not found. pk {}'.format(id)) + raise exceptions.AsnNotFoundError(id) + except OperationalError: + cls.log.error(u'Lock wait timeout exceeded.') + raise OperationalError() + except Exception: + cls.log.error(u'Failure to search the ASN.') + raise exceptions.AsnError(u'Failure to search the ASN.') + + def create_v4(self, as_map): """Create ASN.""" @@ -138,7 +160,7 @@ class Meta(BaseModel.Meta): managed = True @classmethod - def get_by_pk(cls, id): + def get_by_pk(cls, ids=None, asn=None, equipment=None): """Get AsnEquipment by id. :return: AsnEquipment. @@ -148,16 +170,26 @@ def get_by_pk(cls, id): :raise OperationalError: Lock wait timeout exceeded """ try: - return AsnEquipment.objects.get(id=id) + logging.info("get asn_equipment by id, asn or equipment") + if ids: + return AsnEquipment.objects.get(id=int(ids)) + elif asn: + return AsnEquipment.objects.filter(asn=int(asn)) + elif equipment: + return AsnEquipment.objects.filter(equipment__id=int(equipment)) + + return AsnEquipment.objects.all() + except ObjectDoesNotExist: cls.log.error(u'AsnEquipment not found. pk {}'.format(id)) raise exceptions.AsnEquipmentNotFoundError(id) except OperationalError: cls.log.error(u'Lock wait timeout exceeded.') raise OperationalError() - except Exception: - cls.log.error(u'Failure to search the AS.') - raise exceptions.AsnEquipmentError(u'Failure to search the AS.') + except Exception as e: + cls.log.error(u'Failure to search the ASNEquipment. E: %s' % e) + raise exceptions.AsnEquipmentError( + u'Failure to search the ASNEquipment. E: %s' % e) def create_v4(self, as_equipment): """Create AsnEquipment relationship.""" @@ -176,3 +208,15 @@ def delete_v4(self): """Delete AsnEquipment relationship.""" super(AsnEquipment, self).delete() + + def update_v4(self, asn_equipment): + """Update ASNEquipment """ + + equipment = get_model('equipamento', 'Equipamento') + + self.equipment = equipment().get_by_pk( + asn_equipment.get('equipment')[0]) + self.asn = Asn().get_by_pk(asn_equipment.get('asn')) + self.save() + + return self diff --git a/networkapi/api_asn/v4/facade.py b/networkapi/api_asn/v4/facade.py index a3c935ced..c46799978 100644 --- a/networkapi/api_asn/v4/facade.py +++ b/networkapi/api_asn/v4/facade.py @@ -4,6 +4,7 @@ from django.core.exceptions import FieldError from networkapi.api_asn.models import Asn +from networkapi.api_asn.models import AsnEquipment from networkapi.api_asn.v4 import exceptions from networkapi.api_asn.v4.exceptions import AsnErrorV4 from networkapi.api_asn.v4.exceptions import AsnNotFoundError, AsnError @@ -38,7 +39,22 @@ def get_as_by_id(as_id): try: as_ = Asn.get_by_pk(id=as_id) - except AsnNotFoundError, e: + except AsnNotFoundError as e: + raise exceptions.AsnDoesNotExistException(str(e)) + + return as_ + + +def get_as_by_asn(asn_): + """Return an AS by id. + + Args: + asn: ASN + """ + + try: + as_ = Asn.get_by_asn(asn_) + except AsnNotFoundError as e: raise exceptions.AsnDoesNotExistException(str(e)) return as_ @@ -56,9 +72,9 @@ def get_as_by_ids(autonomous_systems_ids): try: as_ = get_as_by_id(as_id).id as_ids.append(as_) - except exceptions.AsnDoesNotExistException, e: + except exceptions.AsnDoesNotExistException as e: raise ObjectDoesNotExistException(str(e)) - except Exception, e: + except Exception as e: raise NetworkAPIException(str(e)) as_s = Asn.objects.filter(id__in=as_ids) @@ -72,13 +88,13 @@ def update_as(as_): try: as_obj = get_as_by_id(as_.get('id')) as_obj.update_v4(as_) - except AsnErrorV4, e: + except AsnErrorV4 as e: raise ValidationAPIException(str(e)) - except ValidationAPIException, e: + except ValidationAPIException as e: raise ValidationAPIException(str(e)) - except exceptions.AsnDoesNotExistException, e: + except exceptions.AsnDoesNotExistException as e: raise ObjectDoesNotExistException(str(e)) - except Exception, e: + except Exception as e: raise NetworkAPIException(str(e)) return as_obj @@ -90,11 +106,11 @@ def create_as(as_): try: as_obj = Asn() as_obj.create_v4(as_) - except AsnErrorV4, e: + except AsnErrorV4 as e: raise ValidationAPIException(str(e)) - except ValidationAPIException, e: + except ValidationAPIException as e: raise ValidationAPIException(str(e)) - except Exception, e: + except Exception as e: raise NetworkAPIException(str(e)) return as_obj @@ -107,12 +123,190 @@ def delete_as(as_ids): try: as_obj = get_as_by_id(as_id) as_obj.delete_v4() - except exceptions.AsnDoesNotExistException, e: + except exceptions.AsnDoesNotExistException as e: raise ObjectDoesNotExistException(str(e)) - except exceptions.AsnAssociatedToEquipmentError, e: + except exceptions.AsnAssociatedToEquipmentError as e: raise ValidationAPIException(str(e)) - except AsnError, e: + except AsnError as e: raise NetworkAPIException(str(e)) - except Exception, e: + except Exception as e: raise NetworkAPIException(str(e)) + +def get_as_equipment_by_search(search=dict()): + """Return a list of ASEquipment's by dict.""" + + try: + as_equipment = AsnEquipment.get_by_pk() + as_map = build_query_to_datatable_v3(as_equipment, search) + except FieldError as e: + raise ValidationAPIException(str(e)) + except Exception as e: + raise NetworkAPIException(str(e)) + else: + return as_map + + +def get_as_equipment_by_id(as_equipment_id=None): + """Return an ASEquipment by id. + + Args: + as_equipment_id: Id of ASEquipment + + """ + + try: + as_equipment_list = list() + for asn in as_equipment_id: + as_equipment = AsnEquipment.get_by_pk(ids=asn) + as_equipment_list.append(as_equipment) + except AsnNotFoundError as e: + raise exceptions.AsnDoesNotExistException(str(e)) + + return as_equipment_list + + +def get_as_equipment_by_asn(asn_id=None): + """Return an ASEquipment by asn id. + + Args: + asn_id: Id of ASN + + """ + + try: + as_equipment = list() + for asn in asn_id: + as_equipment += AsnEquipment.get_by_pk(asn=asn) + + except AsnNotFoundError as e: + raise exceptions.AsnDoesNotExistException(str(e)) + + return as_equipment + + +def get_as_equipment_by_equip(equipment_id=None): + """Return an ASEquipment by equipment id. + + Args: + equipment_id: Id of Equipment + + """ + + try: + as_equipment = list() + for equip in equipment_id: + as_equipment += AsnEquipment.get_by_pk(equipment=equip) + + except AsnNotFoundError as e: + raise exceptions.AsnDoesNotExistException(str(e)) + + return as_equipment + + +def create_asn_equipment(asn_equipment): + """Create ASNEquipment.""" + + try: + asn_equipment_list = list() + + for equipment in asn_equipment.get("equipment"): + obj = dict() + obj["equipment"] = equipment + obj["asn"] = asn_equipment.get("asn") + as_obj = AsnEquipment() + as_obj.create_v4(obj) + asn_equipment_list.append({'id': as_obj.id}) + + except AsnErrorV4 as e: + raise ValidationAPIException(str(e)) + except ValidationAPIException as e: + raise ValidationAPIException(str(e)) + except Exception as e: + raise NetworkAPIException(str(e)) + + return asn_equipment_list + + +def delete_asn_equipment(as_ids): + """Delete ASNEquipment.""" + + try: + asn_equipment = AsnEquipment() + obj = asn_equipment.get_by_pk(ids=as_ids) + obj.delete_v4() + except exceptions.AsnDoesNotExistException as e: + raise ObjectDoesNotExistException(str(e)) + except exceptions.AsnAssociatedToEquipmentError as e: + raise ValidationAPIException(str(e)) + except AsnError as e: + raise NetworkAPIException(str(e)) + except Exception as e: + raise NetworkAPIException(str(e)) + + +def delete_asn_equipment_by_asn(asn_id): + """Delete ASNEquipment.""" + + try: + asn_obj = AsnEquipment() + asn_equipment = asn_obj.get_by_pk(asn=asn_id) + for obj in asn_equipment: + obj.delete_v4() + + except exceptions.AsnDoesNotExistException as e: + raise ObjectDoesNotExistException(str(e)) + except exceptions.AsnAssociatedToEquipmentError as e: + raise ValidationAPIException(str(e)) + except AsnError as e: + raise NetworkAPIException(str(e)) + except Exception as e: + raise NetworkAPIException(str(e)) + + +def update_asn_equipment(as_): + """Update ASNEquipment.""" + + try: + as_obj = AsnEquipment() + if not as_.get('id'): + raise Exception("The object do not have the id.") + asn_equipment = as_obj.get_by_pk(ids=as_.get('id')) + asn_equipment.update_v4(as_) + except AsnErrorV4 as e: + raise ValidationAPIException(str(e)) + except ValidationAPIException as e: + raise ValidationAPIException(str(e)) + except exceptions.AsnDoesNotExistException as e: + raise ObjectDoesNotExistException(str(e)) + except Exception as e: + raise NetworkAPIException(str(e)) + + return asn_equipment + + +def update_asn_equipment_by_asn(asn_id, as_): + """ + Update ASNEquipment. + Return new asn_equipments new ids + """ + + try: + as_obj = AsnEquipment() + asn_equipment = as_obj.get_by_pk(asn=asn_id) + for obj in asn_equipment: + obj.delete_v4() + + asn_equipment_obj = create_asn_equipment(as_) + + except AsnErrorV4 as e: + raise ValidationAPIException(str(e)) + except ValidationAPIException as e: + raise ValidationAPIException(str(e)) + except exceptions.AsnDoesNotExistException as e: + raise ObjectDoesNotExistException(str(e)) + except Exception as e: + raise NetworkAPIException(str(e)) + + return asn_equipment_obj + diff --git a/networkapi/api_asn/v4/specs/asn_equipment_post.json b/networkapi/api_asn/v4/specs/asn_equipment_post.json new file mode 100644 index 000000000..19ef79eac --- /dev/null +++ b/networkapi/api_asn/v4/specs/asn_equipment_post.json @@ -0,0 +1,28 @@ +{ + "title": "ASNEquipment Post", + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "required": [ + "asn_equipment" + ], + "properties": { + "networks": { + "type": "array", + "items": { + "type": "object", + "properties": { + "asn": { + "type": "integer" + }, + "equipment": { + "type": "array" + } + }, + "required": [ + "asn", + "equipment" + ] + } + } + } +} diff --git a/networkapi/api_asn/v4/urls.py b/networkapi/api_asn/v4/urls.py index a8763e2b1..a270ed294 100644 --- a/networkapi/api_asn/v4/urls.py +++ b/networkapi/api_asn/v4/urls.py @@ -6,6 +6,12 @@ urlpatterns = patterns( '', + url(r'^asnequipment/asn/((?P[;\w]+)/)?$', + views.AsEquipmentDBView.as_view()), + url(r'^asnequipment/equipment/((?P[;\w]+)/)?$', + views.AsEquipmentDBView.as_view()), + url(r'^asnequipment/((?P[;\w]+)/)?$', + views.AsEquipmentDBView.as_view()), url(r'^as/((?P[;\w]+)/)?$', views.AsDBView.as_view()), ) diff --git a/networkapi/api_asn/v4/views.py b/networkapi/api_asn/v4/views.py index 6d1314bdb..838fee1a3 100644 --- a/networkapi/api_asn/v4/views.py +++ b/networkapi/api_asn/v4/views.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- # Create your views here. +import logging from django.db.transaction import commit_on_success from rest_framework import status from rest_framework.permissions import IsAuthenticated @@ -19,6 +20,9 @@ from networkapi.util.json_validate import raise_json_validate +log = logging.getLogger(__name__) + + class AsDBView(CustomAPIView): @logs_method_apiview @@ -106,3 +110,106 @@ def delete(self, request, *args, **kwargs): facade.delete_as(obj_ids) return Response({}, status=status.HTTP_200_OK) + + +class AsEquipmentDBView(CustomAPIView): + + @logs_method_apiview + @raise_json_validate('') + @permission_classes_apiview((IsAuthenticated, Read)) + @prepare_search + def get(self, request, *args, **kwargs): + """Returns a list of AS's by ids ou dict.""" + + if not kwargs.get('obj_ids') and\ + not kwargs.get('asn_ids') and\ + not kwargs.get('equip_ids'): + obj_model = facade.get_as_equipment_by_search(self.search) + as_s = obj_model['query_set'] + only_main_property = False + else: + obj_model = None + only_main_property = True + if kwargs.get('obj_ids'): + as_ids = kwargs.get('obj_ids').split(';') + as_s = facade.get_as_equipment_by_id(as_ids) + elif kwargs.get('asn_ids'): + as_ids = kwargs.get('asn_ids').split(';') + as_s = facade.get_as_equipment_by_asn(as_ids) + elif kwargs.get('equip_ids'): + as_ids = kwargs.get('equip_ids').split(';') + as_s = facade.get_as_equipment_by_equip(as_ids) + + serializer_as = serializers.AsnEquipmentV4Serializer( + as_s, + many=True, + fields=self.fields, + include=self.include, + exclude=self.exclude, + kind=self.kind + ) + + data = render_to_json( + serializer_as, + main_property='asn_equipment', + obj_model=obj_model, + request=request, + only_main_property=only_main_property + ) + + return Response(data, status=status.HTTP_200_OK) + + @logs_method_apiview + @raise_json_validate('asn_equipment_post_v4') + @permission_classes_apiview((IsAuthenticated, Write)) + @commit_on_success + def post(self, request, *args, **kwargs): + """Create new ASNEquipment.""" + + as_s = request.DATA + json_validate(SPECS.get('asn_equipment_post_v4')).validate(as_s) + response = list() + for as_ in as_s['asn_equipment']: + response = facade.create_asn_equipment(as_) + + return Response(response, status=status.HTTP_201_CREATED) + + @logs_method_apiview + @permission_classes_apiview((IsAuthenticated, Write)) + @commit_on_success + def delete(self, request, *args, **kwargs): + """Delete AS.""" + + if not kwargs.get('asn_ids'): + + obj_ids = kwargs['obj_ids'].split(';') + for obj in obj_ids: + facade.delete_asn_equipment(obj) + else: + obj_ids = kwargs['asn_ids'].split(';') + for obj in obj_ids: + facade.delete_asn_equipment_by_asn(obj) + + return Response({}, status=status.HTTP_200_OK) + + @logs_method_apiview + # @raise_json_validate('as_put_v4') + @permission_classes_apiview((IsAuthenticated, Write)) + @commit_on_success + def put(self, request, *args, **kwargs): + """Update AS.""" + + asn_equipment = request.DATA + # json_validate(SPECS.get('as_put_v4')).validate(as_s) + response = list() + + if not kwargs.get('asn_ids'): + for as_ in asn_equipment['asn_equipment']: + as_obj = facade.update_asn_equipment(as_) + response.append({'id': as_obj.id}) + else: + for as_ in asn_equipment['asn_equipment']: + response = facade.update_asn_equipment_by_asn( + kwargs.get('asn_ids'), as_) + + return Response(response, status=status.HTTP_200_OK) diff --git a/networkapi/api_rack/facade.py b/networkapi/api_rack/facade.py index b7a603e1e..083e22425 100644 --- a/networkapi/api_rack/facade.py +++ b/networkapi/api_rack/facade.py @@ -36,7 +36,6 @@ from networkapi.api_rack import serializers as rack_serializers from networkapi.api_rack import exceptions from networkapi.api_rack import provision -from networkapi.api_rack import autoprovision from networkapi.system import exceptions as var_exceptions from networkapi.system.facade import get_value as get_variable from networkapi.api_rest.exceptions import ValidationAPIException, ObjectDoesNotExistException, \ @@ -140,7 +139,6 @@ def get_fabric(idt=None, name=None, id_dc=None): else: fabric = fabric_obj.get_dcrooms() - for i in fabric: fabric_list.append(rack_serializers.DCRoomSerializer(i).data) @@ -154,7 +152,7 @@ def update_fabric_config(fabric_id, fabric_dict): try: fabriconfig = ast.literal_eval(fabric.config) - except: + except Exception: fabriconfig = dict() fabric_dict = fabric_dict.get("config") @@ -195,10 +193,12 @@ def save_rack_dc(rack_dict): rack.id_sw1 = Equipamento().get_by_pk(rack_dict.get('id_sw1')) rack.id_sw2 = Equipamento().get_by_pk(rack_dict.get('id_sw2')) rack.id_sw3 = Equipamento().get_by_pk(rack_dict.get('id_ilo')) - rack.dcroom = DatacenterRooms().get_dcrooms(idt=rack_dict.get('fabric_id')) if rack_dict.get('fabric_id') else None + rack.dcroom = DatacenterRooms().get_dcrooms( + idt=rack_dict.get('fabric_id')) if rack_dict.get('fabric_id') else None if not rack.nome: - raise exceptions.InvalidInputException("O nome do Rack não foi informado.") + raise exceptions.InvalidInputException( + "O nome do Rack não foi informado.") rack.save_rack() return rack @@ -218,8 +218,8 @@ def update_rack(rack_id, rack): rack_obj.id_sw1 = Equipamento().get_by_pk(int(rack.get("id_sw1"))) rack_obj.id_sw2 = Equipamento().get_by_pk(int(rack.get("id_sw2"))) rack_obj.id_ilo = Equipamento().get_by_pk(int(rack.get("id_ilo"))) - rack_obj.dcroom = DatacenterRooms().get_dcrooms(idt=rack.get('fabric_id')) if rack.get('fabric_id') \ - else None + rack_obj.dcroom = DatacenterRooms().get_dcrooms( + idt=rack.get('fabric_id')) if rack.get('fabric_id') else None rack_obj.save() @@ -242,13 +242,16 @@ def get_rack(fabric_id=None, rack_id=None): try: if fabric_id: rack = rack_obj.get_rack(dcroom_id=fabric_id) - rack_list = rack_serializers.RackSerializer(rack, many=True).data if rack else list() + rack_list = rack_serializers.RackSerializer( + rack, many=True).data if rack else list() elif rack_id: rack = rack_obj.get_rack(idt=rack_id) - rack_list = [rack_serializers.RackSerializer(rack).data] if rack else list() + rack_list = [rack_serializers.RackSerializer( + rack).data] if rack else list() else: rack = rack_obj.get_rack() - rack_list = rack_serializers.RackSerializer(rack, many=True).data if rack else list() + rack_list = rack_serializers.RackSerializer( + rack, many=True).data if rack else list() return rack_list @@ -327,9 +330,10 @@ def _buscar_ip(id_sw): for ip_equip in ips_equip: ip_sw = ip_equip.ip - if not ip_sw == None: + if not ip_sw is None: if regexp.search(ip_sw.networkipv4.vlan.ambiente.ambiente_logico.nome) is not None: - return str(ip_sw.oct1) + '.' + str(ip_sw.oct2) + '.' + str(ip_sw.oct3) + '.' + str(ip_sw.oct4) + return str(ip_sw.oct1) + '.' + str(ip_sw.oct2) + '.' \ + + str(ip_sw.oct3) + '.' + str(ip_sw.oct4) return "" @@ -368,7 +372,9 @@ def gerar_arquivo_config(ids): oob["modelo"] = rack.id_ilo.modelo.nome equips.append(oob) except: - raise Exception("Erro: Informações incompletas. Verifique o cadastro do Datacenter, do Fabric e do Rack") + raise Exception("Erro: Informações incompletas. " + "Verifique o cadastro do Datacenter, " + "do Fabric e do Rack") prefixspn = "SPN" prefixlf = "LF-" @@ -395,13 +401,15 @@ def gerar_arquivo_config(ids): pass except: raise Exception( - "Erro ao buscar o roteiro de configuracao ou as interfaces associadas ao equipamento: %s." - % equip.get("nome")) + "Erro ao buscar o roteiro de configuracao ou as interfaces " + "associadas ao equipamento: %s." % equip.get("nome")) try: - equip["roteiro"] = _buscar_roteiro(equip.get("id"), "CONFIGURACAO") + equip["roteiro"] = _buscar_roteiro(equip.get("id"), + "CONFIGURACAO") equip["ip_mngt"] = _buscar_ip(equip.get("id")) except: - raise Exception("Erro ao buscar os roteiros do equipamento: %s" % equip.get("nome")) + raise Exception("Erro ao buscar os roteiros do equipamento: " + "%s" % equip.get("nome")) # autoprovision.autoprovision_splf(rack, equips) # autoprovision.autoprovision_coreoob(rack, equips) @@ -448,7 +456,8 @@ def _create_spnlfenv(user, rack): for spn in range(spines): amb_log_name = "SPINE0" + str(spn+1) + "LEAF" try: - id_amb_log = models_env.AmbienteLogico().get_by_name(amb_log_name).id + id_amb_log = models_env.AmbienteLogico().get_by_name( + amb_log_name).id except: amb_log_dict = models_env.AmbienteLogico() amb_log_dict.nome = amb_log_name @@ -518,7 +527,8 @@ def _create_spnlfvlans(rack, user): base_rack = 1 vlan_base = env.min_num_vlan_1 vlan_number = int(vlan_base) + int(rack_number) + (spn-1)*base_rack - vlan_name = "VLAN_" + env.divisao_dc.nome + "_" + env.ambiente_logico.nome + "_" + rack.nome + vlan_name = "VLAN_" + env.divisao_dc.nome + "_" + env.ambiente_logico.nome \ + + "_" + rack.nome for net in env.configs: prefix = int(net.subnet_mask) @@ -788,7 +798,8 @@ def _create_lflf_envs(rack): for env in env_lf: config_subnet = [] for net in env.configs: - cidr = list(IPNetwork(net.network).subnet(int(net.subnet_mask)))[rack.numero] + cidr = list(IPNetwork(net.network).subnet(int( + net.subnet_mask)))[rack.numero] network = { 'network': str(cidr), 'ip_version': str(net.ip_version), @@ -907,9 +918,12 @@ def _create_oobvlans(rack, user): oct4, prefix = var.split('/') netmask = str(new_v4.netmask) mask1, mask2, mask3, mask4 = netmask.split('.') - network = dict(oct1=oct1, oct2=oct2, oct3=oct3, oct4=oct4, prefix=prefix, mask_oct1=mask1, mask_oct2=mask2, - mask_oct3=mask3, mask_oct4=mask4, cluster_unit=None, vlan=vlan.id, - network_type=config.id_network_type.id, environmentvip=None) + network = dict(oct1=oct1, oct2=oct2, oct3=oct3, + oct4=oct4, prefix=prefix, mask_oct1=mask1, + mask_oct2=mask2, mask_oct3=mask3, mask_oct4=mask4, + cluster_unit=None, vlan=vlan.id, + network_type=config.id_network_type.id, + environmentvip=None) log.debug("Network allocated: "+ str(network)) facade_redev4_v3.create_networkipv4(network, user) @@ -968,6 +982,8 @@ def allocate_env_vlan(user, rack_id): rack_env.allocate() + rack_env.create_asn_equipment() + return rack_env.rack @@ -980,6 +996,7 @@ def deallocate_env_vlan(user, rack_id): rack_env.rack_vlans_remove() rack_env.rack_environment_remove() + # rack_env.rack_asn_remove() rack_env.deallocate() @@ -992,59 +1009,87 @@ def api_foreman(rack): NETWORKAPI_FOREMAN_PASSWORD = get_variable("foreman_password") FOREMAN_HOSTS_ENVIRONMENT_ID = get_variable("foreman_hosts_environment_id") except ObjectDoesNotExist: - raise var_exceptions.VariableDoesNotExistException("Erro buscando as variáveis relativas ao Foreman.") + raise var_exceptions.VariableDoesNotExistException( + "Erro buscando as variáveis relativas ao Foreman.") - foreman = Foreman(NETWORKAPI_FOREMAN_URL, (NETWORKAPI_FOREMAN_USERNAME, NETWORKAPI_FOREMAN_PASSWORD), api_version=2) + foreman = Foreman(NETWORKAPI_FOREMAN_URL, + (NETWORKAPI_FOREMAN_USERNAME, + NETWORKAPI_FOREMAN_PASSWORD), + api_version=2) - # for each switch, check the switch ip against foreman know networks, finds foreman hostgroup + # for each switch, check the switch ip against foreman know networks, + # finds foreman hostgroup # based on model and brand and inserts the host in foreman # if host already exists, delete and recreate with new information - for [switch, mac] in [[rack.id_sw1, rack.mac_sw1], [rack.id_sw2, rack.mac_sw2], [rack.id_ilo, rack.mac_ilo]]: - # Get all foremand subnets and compare with the IP address of the switches until find it - if mac == None: - raise RackConfigError(None, rack.nome, ("Could not create entry for %s. There is no mac address." % - switch.nome)) + for [switch, mac] in [[rack.id_sw1, rack.mac_sw1], + [rack.id_sw2, rack.mac_sw2], + [rack.id_ilo, rack.mac_ilo]]: + # Get all foremand subnets and compare with the IP address + # of the switches until find it + if mac is None: + raise RackConfigError( + None, rack.nome, + ("Could not create entry for %s. " + "There is no mac address." % switch.nome)) ip = _buscar_ip(switch.id) - if ip == None: - raise RackConfigError(None, rack.nome, ("Could not create entry for %s. There is no management IP." % - switch.nome)) + if ip is None: + raise RackConfigError( + None, rack.nome, + ("Could not create entry for %s. " + "There is no management IP." % switch.nome)) switch_cadastrado = 0 for subnet in foreman.subnets.index()['results']: network = IPNetwork(ip + '/' + subnet['mask']).network - # check if switches ip network is the same as subnet['subnet']['network'] e subnet['subnet']['mask'] + # check if switches ip network is the same as subnet['subnet']['network'] + # e subnet['subnet']['mask'] if network.__str__() == subnet['network']: subnet_id = subnet['id'] - hosts = foreman.hosts.index(search = switch.nome)['results'] + hosts = foreman.hosts.index(search=switch.nome)['results'] if len(hosts) == 1: - foreman.hosts.destroy(id = hosts[0]['id']) + foreman.hosts.destroy(id=hosts[0]['id']) elif len(hosts) > 1: - raise RackConfigError(None, rack.nome, ("Could not create entry for %s. There are multiple entries " - "with the sam name." % switch.nome)) + raise RackConfigError( + None, rack.nome, + ("Could not create entry for %s. " + "There are multiple entries " + "with the sam name." % switch.nome)) # Lookup foreman hostgroup # By definition, hostgroup should be Marca+"_"+Modelo hostgroup_name = switch.modelo.marca.nome + "_" + switch.modelo.nome - hostgroups = foreman.hostgroups.index(search = hostgroup_name) + hostgroups = foreman.hostgroups.index(search=hostgroup_name) if len(hostgroups['results']) == 0: - raise RackConfigError(None, rack.nome, "Could not create entry for %s. Could not find hostgroup %s " - "in foreman." % (switch.nome, hostgroup_name)) - elif len(hostgroups['results'])>1: - raise RackConfigError(None, rack.nome, "Could not create entry for %s. Multiple hostgroups %s found" - " in Foreman." % (switch.nome, hostgroup_name)) + raise RackConfigError( + None, rack.nome, + "Could not create entry for %s. " + "Could not find hostgroup %s " + "in foreman." % (switch.nome, hostgroup_name)) + elif len(hostgroups['results']) > 1: + raise RackConfigError( + None, rack.nome, + "Could not create entry for %s. " + "Multiple hostgroups %s found" + " in Foreman." % (switch.nome, hostgroup_name)) else: hostgroup_id = hostgroups['results'][0]['id'] - foreman.hosts.create(host = {'name': switch.nome, 'ip': ip, 'mac': mac, - 'environment_id': FOREMAN_HOSTS_ENVIRONMENT_ID, - 'hostgroup_id': hostgroup_id, 'subnet_id': subnet_id, - 'build': 'true', 'overwrite': 'true'}) + foreman.hosts.create(host={'name': switch.nome, + 'ip': ip, + 'mac': mac, + 'environment_id': FOREMAN_HOSTS_ENVIRONMENT_ID, + 'hostgroup_id': hostgroup_id, + 'subnet_id': subnet_id, + 'build': 'true', + 'overwrite': 'true'}) switch_cadastrado = 1 if not switch_cadastrado: - raise RackConfigError(None, rack.nome, "Unknown error. Could not create entry for %s in foreman." % - switch.nome) + raise RackConfigError( + None, rack.nome, + "Unknown error. Could not create entry for " + "%s in foreman." % switch.nome) # ################################################### old diff --git a/networkapi/api_rack/rackenvironments.py b/networkapi/api_rack/rackenvironments.py index c3d1d0f95..a3a932e50 100644 --- a/networkapi/api_rack/rackenvironments.py +++ b/networkapi/api_rack/rackenvironments.py @@ -23,6 +23,8 @@ class RackEnvironment: def __init__(self, user, rack_id): self.rack = Rack().get_by_pk(rack_id) self.user = user + self.dcroom_config = self._get_config_file() + self.rack_asn = self._get_rack_asn() @staticmethod def save_environment(self, env): @@ -290,22 +292,7 @@ def prod_environment_save(self): id_grupo_l3 = grupo_l3_dict.id pass - if self.rack.dcroom.config: - fabricconfig = self.rack.dcroom.config - else: - log.debug("sem configuracoes do fabric %s" % str(self.rack.dcroom.id)) - fabricconfig = list() - - try: - fabricconfig = json.loads(fabricconfig) - except: - pass - - try: - fabricconfig = ast.literal_eval(fabricconfig) - log.debug("config -ast: %s" % str(fabricconfig)) - except: - pass + fabricconfig = self.dcroom_config environment = list() for env in prod_envs: @@ -376,18 +363,7 @@ def children_prod_environment_save(self): except Exception as e: raise Exception("Erro: %s" % e) - if self.rack.dcroom.config: - fabricconfig = self.rack.dcroom.config - else: - log.debug("No fabric configurations %s" % str(self.rack.dcroom.id)) - fabricconfig = list() - - try: - fabricconfig = json.loads(fabricconfig) - fabricconfig = ast.literal_eval(fabricconfig) - log.debug("config -ast: %s" % str(fabricconfig)) - except: - log.debug("Error loading fabric json.") + fabricconfig = self.dcroom_config environment = None father_id = env.id @@ -519,3 +495,66 @@ def rack_vlans_remove(self): vlan.delete_v3() log.debug("Vlans: %s. total: %s" % (vlans, len(vlans))) + + def rack_asn_remove(self): + from networkapi.api_asn.models import Asn + from networkapi.api_asn.v4 import facade + + if self.rack_asn: + asn = facade.get_as_by_asn(self.rack_asn) + asn_equipment = facade.get_as_equipment_by_asn([asn]) + log.debug(asn_equipment) + for obj in asn_equipment: + obj.delete_v4() + + Asn.delete_as([asn]) + + def create_asn_equipment(self): + from networkapi.api_asn.v4 import facade + + if self.rack_asn: + try: + asn_obj = dict(name=self.rack_asn, description=self.rack.nome) + asn = facade.create_as(asn_obj) + + obj = dict(asn=asn.id, equipment=[self.rack.id_sw1.id, + self.rack.id_sw2.id, + self.rack.id_ilo.id]) + facade.create_asn_equipment(obj) + except Exception as e: + log.debug("Error while trying to create the asn %s for rack %s. " + "E: %s" % (self.rack_asn, self.rack.nome, e)) + + def _get_rack_asn(self): + + if self.dcroom_config: + BGP = self.dcroom_config.get("BGP") + BASE_AS_LFS = int(BGP.get("leafs")) + rack_as = BASE_AS_LFS + self.rack.numero + + if rack_as: + return rack_as + else: + return None + + def _get_config_file(self): + + fabricconfig = self.rack.dcroom.config + + try: + fabricconfig = json.loads(fabricconfig) + log.debug("type -ast: %s" % str(type(fabricconfig))) + except: + pass + + try: + fabricconfig = ast.literal_eval(fabricconfig) + log.debug("config -ast: %s" % str(fabricconfig)) + except: + pass + + if fabricconfig: + return fabricconfig + else: + log.debug("sem configuracoes do fabric %s" % str(self.rack.dcroom.id)) + return list() diff --git a/networkapi/settings.py b/networkapi/settings.py index 80b496116..9e30d6775 100644 --- a/networkapi/settings.py +++ b/networkapi/settings.py @@ -546,6 +546,10 @@ def local_files(path): PROJECT_ROOT_PATH, 'api_asn/v4/specs/as_put.json' ), + 'asn_equipment_post_v4': os.path.join( + PROJECT_ROOT_PATH, + 'api_asn/v4/specs/asn_equipment_post.json' + ), 'equipment_post_v4': os.path.join( PROJECT_ROOT_PATH, 'api_equipment/v4/specs/equipment_post.json'