Example #1
0
 def put(self, request, id, format=None):
     fabric_obj = self.get_object(id)
     topology_id = fabric_obj.topology.id
     serializer = FabricPutSerializer(data=request.data)
     if serializer.is_valid():
         if ((request.data['topology_id'] != topology_id) or (fabric_obj.name != request.data['name'])):
             logger.error("Failed to Update Fabric id " + str(id)\
             +" cannot change base Topology or Fabric Name")
         else:
             topology = Topology.objects.get(id=request.data['topology_id'])
             topology_json = json.loads(topology.topology_json)
             me = RequestValidator(request.META)
             fabric_obj.user_id = me.user_is_exist().user_id
             fabric_obj.validate = request.data['validate']
             fabric_obj.locked = request.data['locked']
             fabric_obj.config_json = json.dumps(request.data['config_json'])
             fabric_obj.submit = request.data['submit']
             fabric_obj.instance = request.data['instance']
             if delete_fabric_rules(id):
                 if (generate_fabric_rules(request.data['name'],\
                     request.data['instance'], fabric_obj, request.data['config_json'],\
                     topology_json)):
                     logger.error("Failed to update Fabric id: " + str(id))
                     logger.info("Successfully  update Fabric id: " + str(id))
                     serializer = FabricGetDetailSerializer(fabric_obj)
                     resp = serializer.data
                     resp['config_json'] = json.loads(resp['config_json'])
                     fabric_obj.save()
                     return Response(resp)
                 else:
                     logger.error("Failed to update Fabric id: " + str(id))
             else:
                 logger.error("Failed to delete Rules from fabric Rule DB for Fabric id: " + str(id))
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #2
0
 def dispatch(self,request, *args, **kwargs):
     me = RequestValidator(request.META)
     if me.user_is_exist():
         return super(DiscoveryRuleDetailList, self).dispatch(request,*args, **kwargs)
     else:
         resp = me.invalid_token()
         return JsonResponse(resp,status=status.HTTP_400_BAD_REQUEST)
Example #3
0
 def put(self, request, id, format=None):
     topology = self.get_object(id)
     if request.data['name'] == self.get_object(id).name:
         serializer = TopologyPutSerializer(data=request.data)
     else:
         serializer = TopologySerializer(data=request.data)
     me = RequestValidator(request.META)
     if serializer.is_valid():
         count = Fabric.objects.filter(topology = topology).count()
         if count:
             logger.error("Fail to update Topology id " + str(id) + ", Number of Fabrics using it as base topology-" + str(count))
         else:
             topology_obj = topology
             topology_obj.user_id = me.user_is_exist().user_id
             topology_obj.name = request.data['name']
             topology_obj.submit = request.data['submit']
             topology_obj.topology_json = json.dumps(request.data['topology_json'])
             try:
                 topology_obj.config_json = json.dumps(request.data['config_json'])
             except:
                 topology_obj.config_json = json.dumps([])
             topology_obj.save()
             serailizer = TopologyGetDetailSerializer(topology_obj)
             resp = serailizer.data
             resp['topology_json'] = json.loads(resp['topology_json'])
             try:
                 resp['config_json'] = json.loads(resp['config_json'])
             except:
                 resp['config_json'] = []
             return Response(resp)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #4
0
 def post(self, request, format=None):
     me = RequestValidator(request.META)
     if request.data['match'] != 'serial_id':
         serializer = DiscoveryRuleSerializer(data=request.data)
         if serializer.is_valid():
             rule_object = DiscoveryRule()
             rule_object.name = serializer.data['name']
             rule_object.priority = serializer.data['priority']
             rule_object.user_id = me.user_is_exist().user_id
             rule_object.config_id = serializer.data['config_id']
             rule_object.subrules = json.dumps(serializer.data['subrules'])
             rule_object.match = serializer.data['match'].lower()
             rule_object.save()
             serializer = DiscoveryRuleGetSerializer(rule_object)
             return Response(serializer.data,
                             status=status.HTTP_201_CREATED)
     else:
         serializer = DiscoveryRuleSerialIDSerializer(data=request.data)
         if serializer.is_valid():
             rule_object = DiscoveryRule()
             rule_object.name = serializer.data['name']
             rule_object.priority = serializer.data['priority']
             rule_object.user_id = me.user_is_exist().user_id
             rule_object.config_id = serializer.data['config_id']
             for i in range(len(serializer.data['subrules'])):
                 serializer.data['subrules'][i] = str(
                     serializer.data['subrules'][i])
             rule_object.subrules = str(serializer.data['subrules'])
             rule_object.match = serializer.data['match']
             rule_object.save()
             serializer = DiscoveryRuleGetSerializer(rule_object)
             return Response(serializer.data,
                             status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #5
0
 def put(self, request, id, format=None):
     me = RequestValidator(request.META)
     discoveryrule=self.get_object(id)
     if request.data['match']!='serial_id':
         serializer = DiscoveryRulePutSerializer(data=request.data)
         if serializer.is_valid():
             rule_object = self.get_object(id)
             subrules = json.dumps(serializer.data['subrules'])
             rule_object.subrules = subrules
             rule_object.priority = serializer.data['priority']
             rule_object.user_id = me.user_is_exist().user_id
             rule_object.config_id = serializer.data['config_id'] 
             rule_object.match = serializer.data['match'].lower()
             rule_object.save()
             serializer = DiscoveryRuleGetDetailSerializer(rule_object)
             resp = serializer.data
             resp['subrules'] = json.loads(resp['subrules'])
             return Response(resp)
     else:
         serializer = DiscoveryRuleIDPutSerializer(data=request.data)
         if serializer.is_valid():
             rule_object = self.get_object(id)
             for i in range(len(serializer.data['subrules'])):
                 serializer.data['subrules'][i]=str(serializer.data['subrules'][i])
             subrules = str(serializer.data['subrules'])
             rule_object.subrules = subrules
             rule_object.priority = serializer.data['priority']
             rule_object.user_id = me.user_is_exist().user_id
             rule_object.config_id = serializer.data['config_id'] 
             rule_object.match = serializer.data['match'].lower()
             rule_object.save()
             return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #6
0
 def dispatch(self, request, *args, **kwargs):
     me = RequestValidator(request.META)
     if me.user_is_exist():
         return super(SwitchList, self).dispatch(request, *args, **kwargs)
     else:
         resp = me.invalid_token()
         return JsonResponse(resp, status=status.HTTP_400_BAD_REQUEST)
Example #7
0
    def post(self, request, format=None):

        serializer = FabricSerializer(data=request.data)
        topology = Topology.objects.get(id=request.data['topology_id'])
        topology_json = json.loads(topology.topology_json)
        me = RequestValidator(request.META)
        if serializer.is_valid():
            if request.data['instance'] < 1:
                logger.error("Fabric Instances cannot be less than 1")
            else:
                fabric_obj = Fabric()
                fabric_obj.name = request.data['name']
                fabric_obj.user_id = me.user_is_exist().user_id
                fabric_obj.topology = topology
                topology.used += 1
                topology.save()
                fabric_obj.instance = request.data['instance']
                fabric_obj.validate = request.data['validate']
                fabric_obj.locked = request.data['locked']
                fabric_obj.config_json = json.dumps(request.data['config_json'])
                fabric_obj.submit = request.data['submit']
                fabric_obj.save()
                if (generate_fabric_rules(request.data['name'],\
                request.data['instance'], fabric_obj, request.data['config_json'],\
                topology_json)):
                    serializer = FabricGetSerializer(fabric_obj)
                    logger.info("Successfully created Fabric id: " + str(id))
                    return Response(serializer.data, status=status.HTTP_201_CREATED)
                else:
                    Fabric.objects.filter(id = fabric_obj.id).delete()
                    logger.error("Failed to create Fabric: " + fabric_obj.name)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #8
0
 def post(self, request, format=None):
     me = RequestValidator(request.META)
     if request.data['match']!='serial_id':
         serializer = DiscoveryRuleSerializer(data=request.data)
         if serializer.is_valid():
             rule_object = DiscoveryRule()
             rule_object.name = serializer.data['name']
             rule_object.priority = serializer.data['priority']
             rule_object.user_id = me.user_is_exist().user_id
             rule_object.config_id = serializer.data['config_id']
             rule_object.subrules = json.dumps(serializer.data['subrules'])
             rule_object.match = serializer.data['match'].lower()
             rule_object.save()
             serializer = DiscoveryRuleGetSerializer(rule_object)
             return Response(serializer.data, status=status.HTTP_201_CREATED)
     else:
         serializer = DiscoveryRuleSerialIDSerializer(data=request.data)
         if serializer.is_valid():
             rule_object = DiscoveryRule()
             rule_object.name = serializer.data['name']
             rule_object.priority = serializer.data['priority']
             rule_object.user_id = me.user_is_exist().user_id
             rule_object.config_id = serializer.data['config_id']
             for i in range(len(serializer.data['subrules'])):
                 serializer.data['subrules'][i]=str(serializer.data['subrules'][i])
             rule_object.subrules = str(serializer.data['subrules'])
             rule_object.match = serializer.data['match']
             rule_object.save()
             serializer = DiscoveryRuleGetSerializer(rule_object)
             return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #9
0
 def dispatch(self,request, *args, **kwargs):
     me = RequestValidator(request.META)
     if me.user_is_exist():
         logger.debug("User Id exist")
         return super(ConfigletList, self).dispatch(request,*args, **kwargs)
     else:
         resp = me.invalid_token()
         return JsonResponse(resp,status=status.HTTP_400_BAD_REQUEST)
Example #10
0
 def dispatch(self,request, *args, **kwargs):
     me = RequestValidator(request.META)
     if me.user_is_exist():
         logger.debug("User Id exist")
         return super(ProfileTemplateList, self).dispatch(request,*args, **kwargs)
     else:
         resp = me.invalid_token()
         return JsonResponse(resp,status=status.HTTP_400_BAD_REQUEST)
Example #11
0
 def post(self, request, format=None):
     serializer = TopologySerializer(data=request.data)
     me = RequestValidator(request.META)
     if serializer.is_valid():
         topology_obj = Topology()
         topology_obj.user_id = me.user_is_exist().user_id
         topology_obj.name = request.data['name']
         topology_obj.submit = request.data['submit']
         topology_obj.topology_json = json.dumps(request.data['topology_json'])
         try:
             topology_obj.config_json = json.dumps(request.data['config_json'])
         except:
             topology_obj.config_json = json.dumps([])
         topology_obj.save()
         serializer = TopologyGetSerializer(topology_obj)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #12
0
 def put(self, request, id, format=None):
     topology = self.get_object(id)
     if request.data['name'] == self.get_object(id).name:
         serializer = TopologyPutSerializer(data=request.data)
     else:
         serializer = TopologySerializer(data=request.data)
     me = RequestValidator(request.META)
     if serializer.is_valid():
         count = Fabric.objects.filter(topology=topology).count()
         if count:
             logger.error("Fail to update Topology id " + str(id) +
                          ", Number of Fabrics using it as base topology-" +
                          str(count))
         else:
             topology_obj = topology
             topology_obj.user_id = me.user_is_exist().user_id
             topology_obj.name = request.data['name']
             topology_obj.submit = request.data['submit']
             topology_obj.topology_json = json.dumps(
                 request.data['topology_json'])
             try:
                 topology_obj.config_json = json.dumps(
                     request.data['config_json'])
             except:
                 topology_obj.config_json = json.dumps([])
             try:
                 topology_obj.defaults = json.dumps(
                     request.data['defaults'])
             except:
                 topology_obj.defaults = json.dumps({})
             topology_obj.save()
             serailizer = TopologyGetDetailSerializer(topology_obj)
             resp = serailizer.data
             resp['topology_json'] = json.loads(resp['topology_json'])
             try:
                 resp['config_json'] = json.loads(resp['config_json'])
             except:
                 resp['config_json'] = []
             try:
                 resp['defaults'] = json.loads(resp['defaults'])
             except:
                 resp['defaults'] = {}
             return Response(resp)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #13
0
 def put(self, request, id, format=None):
     me = RequestValidator(request.META)
     discoveryrule = self.get_object(id)
     if request.data['match'] != 'serial_id':
         if request.data['name'] == self.get_object(id).name:
             serializer = DiscoveryRulePutSerializer(data=request.data)
         else:
             serializer = DiscoveryRuleSerializer(data=request.data)
         if serializer.is_valid():
             rule_object = self.get_object(id)
             subrules = json.dumps(serializer.data['subrules'])
             rule_object.name = serializer.data['name']
             rule_object.subrules = subrules
             rule_object.priority = serializer.data['priority']
             rule_object.user_id = me.user_is_exist().user_id
             rule_object.config_id = serializer.data['config_id']
             rule_object.match = serializer.data['match'].lower()
             rule_object.save()
             serializer = DiscoveryRuleGetDetailSerializer(rule_object)
             resp = serializer.data
             resp['subrules'] = json.loads(resp['subrules'])
             return Response(resp)
     else:
         if request.data['name'] == self.get_object(id).name:
             serializer = DiscoveryRuleIDPutSerializer(data=request.data)
         else:
             serializer = DiscoveryRuleSerialIDSerializer(data=request.data)
         if serializer.is_valid():
             rule_object = self.get_object(id)
             for i in range(len(serializer.data['subrules'])):
                 serializer.data['subrules'][i] = str(
                     serializer.data['subrules'][i])
             subrules = str(serializer.data['subrules'])
             rule_object.name = serializer.data['name']
             rule_object.subrules = subrules
             rule_object.priority = serializer.data['priority']
             rule_object.user_id = me.user_is_exist().user_id
             rule_object.config_id = serializer.data['config_id']
             rule_object.match = serializer.data['match'].lower()
             rule_object.save()
             return Response(serializer.data)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #14
0
 def post(self, request, format=None):
     serializer = TopologySerializer(data=request.data)
     me = RequestValidator(request.META)
     if serializer.is_valid():
         topology_obj = Topology()
         topology_obj.user_id = me.user_is_exist().user_id
         topology_obj.name = request.data['name']
         topology_obj.submit = request.data['submit']
         topology_obj.topology_json = json.dumps(
             request.data['topology_json'])
         try:
             topology_obj.config_json = json.dumps(
                 request.data['config_json'])
         except:
             topology_obj.config_json = json.dumps([])
         try:
             topology_obj.defaults = json.dumps(request.data['defaults'])
         except:
             topology_obj.defaults = json.dumps({})
         topology_obj.save()
         serializer = TopologyGetSerializer(topology_obj)
         return Response(serializer.data, status=status.HTTP_201_CREATED)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #15
0
 def put(self, request, id, format=None):
     success = True
     resp = {}
     resp['Error'] = ' '
     fabric_obj = self.get_object(id)
     topology_id = fabric_obj.topology.id
     serializer = FabricPutSerializer(data=request.data)
     if serializer.is_valid():
         if ((request.data['topology_id'] != topology_id) or (fabric_obj.name != request.data['name'])):
             logger.error("Failed to Update Fabric id " + str(id)\
             +" cannot change base Topology or Fabric Name")
         else:
             topology = Topology.objects.get(id=request.data['topology_id'])
             topology_json = json.loads(topology.topology_json)
             me = RequestValidator(request.META)
             fabric_obj.user_id = me.user_is_exist().user_id
             fabric_obj.validate = request.data['validate']
             fabric_obj.locked = request.data['locked']
             find_dup_data = {'system_id':['system_id','name'], 'config_json':['name']}
             for key,val in find_dup_data.iteritems():
                 for value in val:
                     err_msg, isError = findDuplicate(request.data[key], value)
                     if isError:
                         resp['Error'] = err_msg
                         return Response(resp, status=status.HTTP_400_BAD_REQUEST)
             err = uniqueSystenmId(request.data['system_id'], fabric_obj.id)
             if err !="":
                 resp['Error'] = err
                 return Response(resp, status=status.HTTP_400_BAD_REQUEST)
             config_in_fabric = json.loads(fabric_obj.config_json)
             for config in config_in_fabric:
                 config_obj = Configuration.objects.get(id = config['configuration_id'])
                 config_obj.used -= 1
                 config_obj.save()
             fabric_obj.config_json = json.dumps(request.data['config_json'])
             for config in request.data['config_json']:
                 config_obj = Configuration.objects.get(id = config['configuration_id'])
                 config_obj.used += 1
                 config_obj.save()
             fabric_obj.submit = request.data['submit']
             fabric_obj.instance = request.data['instance']
             # filling image details
             try: 
                 fabric_obj.image_details = json.dumps(request.data['image_details'])
             except:
                 pass
             # filling profiles
             """
             try:
                 fabric_obj.profiles = json.loads(request.data['profiles'])
             except:pass
             """
                             # filling discovery rule db
             try:
                 DiscoveryRule.objects.filter(fabric_id=id).delete()
             except:
                 logger.error('Failed to delete Discovery rules with fabric_id:'+str(id))
                 resp['Error'] = ['Failed to delete Discovery rules']
                 return Response(resp, status=status.HTTP_400_BAD_REQUEST)
             success, resp, dis_bulk_obj = add_dis_rule(request.data,success,resp,fabric_obj.id)
             
             if success:
                 if delete_fabric_rules(id):
                     if (generate_fabric_rules(request.data['name'],\
                         request.data['instance'], fabric_obj, request.data['config_json'],\
                         topology_json)):
                         logger.info("Successfully  update Fabric id: " + str(id))
                         serializer = FabricGetDetailSerializer(fabric_obj)
                         data = serializer.data
                         data['config_json'] = json.loads(data['config_json'])
                         try:
                             data['system_id'] = json.loads(data['system_id'])
                         except:
                             data['system_id'] = []
                         try: # image details
                             data['image_details'] = json.loads(data['image_details'])
                         except:
                             data['image_details'] = []
                         for obj in dis_bulk_obj:
                             obj.save()
                         fabric_obj.save()
                         return Response(data)
                     else:
                         success = False
                         resp['Error'] = 'Failed to update Fabric'
                         logger.error("Failed to update Fabric id: " + str(id))
                 else:
                     success = False
                     resp['Error'] = 'Failed to update Fabric Rule DB'
                     logger.error("Failed to delete Rules from fabric Rule DB for Fabric id: " + str(id))
             if not success:
                 return Response(resp, status=status.HTTP_400_BAD_REQUEST)
             
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #16
0
 def post(self, request, format=None):
     
     success = True
     resp = {}
     resp['Error'] = ' '
     serializer = FabricSerializer(data=request.data)
     topology = Topology.objects.get(id=request.data['topology_id'])
     topology_json = json.loads(topology.topology_json)
     me = RequestValidator(request.META)
     if serializer.is_valid():
         if request.data['instance'] < 1:
             logger.error("Fabric Instances cannot be less than 1")
         else:
             fabric_obj = Fabric()
             find_dup_data = {'system_id':['system_id','name'], 'config_json':['name']}
             for key,val in find_dup_data.iteritems():
                 for value in val:
                     err_msg, isError = findDuplicate(request.data[key], value)
                     if isError:
                         resp['Error'] = err_msg
                         return Response(resp, status=status.HTTP_400_BAD_REQUEST)
             err = uniqueSystenmId(request.data['system_id'],fabric_obj.id)
             if err != "":
                 resp['Error'] = err
                 return Response(resp, status=status.HTTP_400_BAD_REQUEST)
             fabric_obj.name = request.data['name']
             fabric_obj.user_id = me.user_is_exist().user_id
             fabric_obj.topology = topology
             topology.used += 1
             topology.save()
             fabric_obj.instance = request.data['instance']
             fabric_obj.validate = request.data['validate']
             fabric_obj.locked = request.data['locked']
             fabric_obj.config_json = json.dumps(request.data['config_json'])
             for config in request.data['config_json']:
                 config_obj = Configuration.objects.get(id = config['configuration_id'])
                 config_obj.used += 1
                 config_obj.save()
             fabric_obj.submit = request.data['submit']
             try:
                 fabric_obj.system_id = json.dumps(request.data['system_id'])
             except:
                 fabric_obj.system_id = []
             """
             try:
                 fabric_obj.profiles = json.dumps(request.data['profiles'])
             except:
                 fabric_obj.profiles = json.dumps({})
             """    
             try:   # fill image details
                 fabric_obj.image_details = json.dumps(request.data['image_details'])
             except:
                 fabric_obj.image_details = json.dumps({})
             try:  # save object
                 fabric_obj.save()
             except:
                 logger.error("Failed to create Fabric: " + fabric_obj.name)
                 resp['Error'] = 'Failed to create Fabric' 
                 return JsonResponse(resp,status=status.HTTP_400_BAD_REQUEST)
                             
             # filling discovery rule with system_id
             success, resp, dis_bulk_obj = add_dis_rule(request.data,success,resp,fabric_obj.id)
             
             if success:   
                 if (generate_fabric_rules(request.data['name'],\
                 request.data['instance'], fabric_obj, request.data['config_json'],\
                 topology_json)):
                     serializer = FabricGetSerializer(fabric_obj)
                     logger.info("Successfully created Fabric id: " + str(fabric_obj.id))
                     try:
                         for obj in dis_bulk_obj:
                             obj.save()
                     except:
                         logger.error('failed to save dis_rule_obj')
                         resp['Error']='Failed to save DiscoveryRules'
                         return JsonResponse(resp,status=status.HTTP_400_BAD_REQUEST)
                     return Response(serializer.data, status=status.HTTP_201_CREATED)
                 else:
                     success = False
                     logger.error("Failed to update FabricRuleDb: " + fabric_obj.name)
                     resp['Error'] = 'Failed to update FabricRule DB'
                     
                 
             if not success:
                 try:
                     DiscoveryRule.objects.filter(fabric_id = fabric_obj.id).delete()
                 except:
                     pass
                 Fabric.objects.filter(id = fabric_obj.id).delete()
                 logger.error("Failed to create Fabric: " + fabric_obj.name)
                 return JsonResponse(resp,status=status.HTTP_400_BAD_REQUEST)
                     
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #17
0
    def put(self, request, id, format=None):
        success = True
        resp = {}
        resp['Error'] = ' '
        fabric_obj = self.get_object(id)
        topology_id = fabric_obj.topology.id
        serializer = FabricPutSerializer(data=request.data)
        if serializer.is_valid():
            if ((request.data['topology_id'] != topology_id)
                    or (fabric_obj.name != request.data['name'])):
                logger.error("Failed to Update Fabric id " + str(id)\
                +" cannot change base Topology or Fabric Name")
            else:
                topology = Topology.objects.get(id=request.data['topology_id'])
                topology_json = json.loads(topology.topology_json)
                me = RequestValidator(request.META)
                fabric_obj.user_id = me.user_is_exist().user_id
                fabric_obj.validate = request.data['validate']
                fabric_obj.locked = request.data['locked']
                find_dup_data = {
                    'system_id': ['system_id', 'name'],
                    'config_json': ['name']
                }
                for key, val in find_dup_data.iteritems():
                    for value in val:
                        err_msg, isError = findDuplicate(
                            request.data[key], value)
                        if isError:
                            resp['Error'] = err_msg
                            return Response(resp,
                                            status=status.HTTP_400_BAD_REQUEST)
                err = uniqueSystenmId(request.data['system_id'], fabric_obj.id)
                if err != "":
                    resp['Error'] = err
                    return Response(resp, status=status.HTTP_400_BAD_REQUEST)
                config_in_fabric = json.loads(fabric_obj.config_json)
                for config in config_in_fabric:
                    config_obj = Configuration.objects.get(
                        id=config['configuration_id'])
                    config_obj.used -= 1
                    config_obj.save()
                fabric_obj.config_json = json.dumps(
                    request.data['config_json'])
                for config in request.data['config_json']:
                    config_obj = Configuration.objects.get(
                        id=config['configuration_id'])
                    config_obj.used += 1
                    config_obj.save()
                fabric_obj.submit = request.data['submit']
                fabric_obj.instance = request.data['instance']
                # filling image details
                try:
                    fabric_obj.image_details = json.dumps(
                        request.data['image_details'])
                except:
                    pass
                # filling profiles
                """
                try:
                    fabric_obj.profiles = json.loads(request.data['profiles'])
                except:pass
                """
                # filling discovery rule db
                try:
                    DiscoveryRule.objects.filter(fabric_id=id).delete()
                except:
                    logger.error(
                        'Failed to delete Discovery rules with fabric_id:' +
                        str(id))
                    resp['Error'] = ['Failed to delete Discovery rules']
                    return Response(resp, status=status.HTTP_400_BAD_REQUEST)
                success, resp, dis_bulk_obj = add_dis_rule(
                    request.data, success, resp, fabric_obj.id)

                if success:
                    if delete_fabric_rules(id):
                        if (generate_fabric_rules(request.data['name'],\
                            request.data['instance'], fabric_obj, request.data['config_json'],\
                            topology_json)):
                            logger.info("Successfully  update Fabric id: " +
                                        str(id))
                            serializer = FabricGetDetailSerializer(fabric_obj)
                            data = serializer.data
                            data['config_json'] = json.loads(
                                data['config_json'])
                            try:
                                data['system_id'] = json.loads(
                                    data['system_id'])
                            except:
                                data['system_id'] = []
                            try:  # image details
                                data['image_details'] = json.loads(
                                    data['image_details'])
                            except:
                                data['image_details'] = []
                            for obj in dis_bulk_obj:
                                obj.save()
                            fabric_obj.save()
                            return Response(data)
                        else:
                            success = False
                            resp['Error'] = 'Failed to update Fabric'
                            logger.error("Failed to update Fabric id: " +
                                         str(id))
                    else:
                        success = False
                        resp['Error'] = 'Failed to update Fabric Rule DB'
                        logger.error(
                            "Failed to delete Rules from fabric Rule DB for Fabric id: "
                            + str(id))
                if not success:
                    return Response(resp, status=status.HTTP_400_BAD_REQUEST)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #18
0
    def post(self, request, format=None):

        success = True
        resp = {}
        resp['Error'] = ' '
        serializer = FabricSerializer(data=request.data)
        topology = Topology.objects.get(id=request.data['topology_id'])
        topology_json = json.loads(topology.topology_json)
        me = RequestValidator(request.META)
        if serializer.is_valid():
            if request.data['instance'] < 1:
                logger.error("Fabric Instances cannot be less than 1")
            else:
                fabric_obj = Fabric()
                find_dup_data = {
                    'system_id': ['system_id', 'name'],
                    'config_json': ['name']
                }
                for key, val in find_dup_data.iteritems():
                    for value in val:
                        err_msg, isError = findDuplicate(
                            request.data[key], value)
                        if isError:
                            resp['Error'] = err_msg
                            return Response(resp,
                                            status=status.HTTP_400_BAD_REQUEST)
                err = uniqueSystenmId(request.data['system_id'], fabric_obj.id)
                if err != "":
                    resp['Error'] = err
                    return Response(resp, status=status.HTTP_400_BAD_REQUEST)
                fabric_obj.name = request.data['name']
                fabric_obj.user_id = me.user_is_exist().user_id
                fabric_obj.topology = topology
                topology.used += 1
                topology.save()
                fabric_obj.instance = request.data['instance']
                fabric_obj.validate = request.data['validate']
                fabric_obj.locked = request.data['locked']
                fabric_obj.config_json = json.dumps(
                    request.data['config_json'])
                for config in request.data['config_json']:
                    config_obj = Configuration.objects.get(
                        id=config['configuration_id'])
                    config_obj.used += 1
                    config_obj.save()
                fabric_obj.submit = request.data['submit']
                try:
                    fabric_obj.system_id = json.dumps(
                        request.data['system_id'])
                except:
                    fabric_obj.system_id = []
                """
                try:
                    fabric_obj.profiles = json.dumps(request.data['profiles'])
                except:
                    fabric_obj.profiles = json.dumps({})
                """
                try:  # fill image details
                    fabric_obj.image_details = json.dumps(
                        request.data['image_details'])
                except:
                    fabric_obj.image_details = json.dumps({})
                try:  # save object
                    fabric_obj.save()
                except:
                    logger.error("Failed to create Fabric: " + fabric_obj.name)
                    resp['Error'] = 'Failed to create Fabric'
                    return JsonResponse(resp,
                                        status=status.HTTP_400_BAD_REQUEST)

                # filling discovery rule with system_id
                success, resp, dis_bulk_obj = add_dis_rule(
                    request.data, success, resp, fabric_obj.id)

                if success:
                    if (generate_fabric_rules(request.data['name'],\
                    request.data['instance'], fabric_obj, request.data['config_json'],\
                    topology_json)):
                        serializer = FabricGetSerializer(fabric_obj)
                        logger.info("Successfully created Fabric id: " +
                                    str(fabric_obj.id))
                        try:
                            for obj in dis_bulk_obj:
                                obj.save()
                        except:
                            logger.error('failed to save dis_rule_obj')
                            resp['Error'] = 'Failed to save DiscoveryRules'
                            return JsonResponse(
                                resp, status=status.HTTP_400_BAD_REQUEST)
                        return Response(serializer.data,
                                        status=status.HTTP_201_CREATED)
                    else:
                        success = False
                        logger.error("Failed to update FabricRuleDb: " +
                                     fabric_obj.name)
                        resp['Error'] = 'Failed to update FabricRule DB'

                if not success:
                    try:
                        DiscoveryRule.objects.filter(
                            fabric_id=fabric_obj.id).delete()
                    except:
                        pass
                    Fabric.objects.filter(id=fabric_obj.id).delete()
                    logger.error("Failed to create Fabric: " + fabric_obj.name)
                    return JsonResponse(resp,
                                        status=status.HTTP_400_BAD_REQUEST)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #19
0
    def post(self, request, format=None):

        success = True
        resp = {}
        resp['Error'] = ' '
        serializer = FabricSerializer(data=request.data)
        topology = Topology.objects.get(id=request.data['topology_id'])
        topology_json = json.loads(topology.topology_json)
        me = RequestValidator(request.META)
        if serializer.is_valid():
            if request.data['instance'] < 1:
                logger.error("Fabric Instances cannot be less than 1")
            else:
                fabric_obj = Fabric()
                fabric_obj.name = request.data['name']
                fabric_obj.user_id = me.user_is_exist().user_id
                fabric_obj.topology = topology
                topology.used += 1
                topology.save()
                fabric_obj.instance = request.data['instance']
                fabric_obj.validate = request.data['validate']
                fabric_obj.locked = request.data['locked']
                fabric_obj.config_json = json.dumps(
                    request.data['config_json'])
                for config in request.data['config_json']:
                    config_obj = Configuration.objects.get(
                        id=config['configuration_id'])
                    config_obj.used += 1
                    config_obj.save()
                fabric_obj.submit = request.data['submit']
                try:
                    fabric_obj.system_id = json.dumps(
                        request.data['system_id'])
                except:
                    fabric_obj.system_id = []
                try:
                    fabric_obj.save()
                except:
                    logger.error("Failed to create Fabric: " + fabric_obj.name)
                    resp['Error'] = 'Failed to create Fabric'
                    return JsonResponse(resp,
                                        status=status.HTTP_400_BAD_REQUEST)

                # filling discovery rule with system_id
                try:
                    sys_id_obj = json.loads(fabric_obj.system_id)
                    config_obj = json.loads(fabric_obj.config_json)
                    regex = fabric_obj.name + "(_)([1-9][0-9]*)(_)([a-zA-Z]*-[1-9])"
                    for switch_systemId_info in sys_id_obj:
                        if not success:
                            break
                        switch_name = (re.search(
                            regex, switch_systemId_info['name'])).group(4)
                        replica_num = int(
                            (re.search(regex,
                                       switch_systemId_info['name'])).group(2))
                        system_id = switch_systemId_info['system_id']
                        for config in config_obj:
                            if switch_name == config['name']:
                                discoveryrule_name = 'serial_' + switch_systemId_info[
                                    'system_id']
                                old_dis_rule = DiscoveryRule.objects.filter(
                                    name=discoveryrule_name)
                                if old_dis_rule:
                                    obj = DiscoveryRule.objects.get(
                                        name=discoveryrule_name)
                                    logger.error("DIscovery Rule existed with system id: "+switch_systemId_info\
                                                 ['system_id']+" wiht switch_name: "+obj.switch_name)
                                    if obj.fabric_id == fabric_obj.id:
                                        resp['Error'] = 'Serial id: '+switch_systemId_info['system_id']+\
                                                        ' is repeated in this Fabric'
                                    else:
                                        resp['Error'] = "serial id: "+switch_systemId_info['system_id']+\
                                                        " is existed with switch: "+obj.switch_name
                                    logger.error(resp['Error'])
                                    success = False
                                    break

                                dis_rule_obj = DiscoveryRule()
                                dis_rule_obj.priority = 100
                                dis_rule_obj.name = discoveryrule_name
                                dis_rule_obj.config_id = config[
                                    'configuration_id']
                                dis_rule_obj.match = 'serial_id'
                                dis_rule_obj.subrules = [system_id]
                                dis_rule_obj.fabric_id = fabric_obj.id
                                dis_rule_obj.replica_num = replica_num
                                dis_rule_obj.switch_name = switch_systemId_info[
                                    'name']
                                dis_rule_obj.save()
                except:
                    success = False
                    logger.error('Failed to update discoveryRule DB with system_id rule for fabric_id: '+\
                                 str(fabric_obj.id))
                    resp['Error'] = 'Failed to update DiscoveryRule DB'

                if success:
                    if (generate_fabric_rules(request.data['name'],\
                    request.data['instance'], fabric_obj, request.data['config_json'],\
                    topology_json)):
                        serializer = FabricGetSerializer(fabric_obj)
                        logger.info("Successfully created Fabric id: " +
                                    str(fabric_obj.id))
                        return Response(serializer.data,
                                        status=status.HTTP_201_CREATED)
                    else:
                        success = False
                        logger.error("Failed to update FabricRuleDb: " +
                                     fabric_obj.name)
                        resp['Error'] = 'Failed to update FabricRule DB'

                if not success:
                    try:
                        DiscoveryRule.objects.filter(
                            fabric_id=fabric_obj.id).delete()
                    except:
                        pass
                    Fabric.objects.filter(id=fabric_obj.id).delete()
                    logger.error("Failed to create Fabric: " + fabric_obj.name)
                    return JsonResponse(resp,
                                        status=status.HTTP_400_BAD_REQUEST)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Example #20
0
    def put(self, request, id, format=None):
        success = True
        resp = {}
        resp['Error'] = ' '
        fabric_obj = self.get_object(id)
        topology_id = fabric_obj.topology.id
        serializer = FabricPutSerializer(data=request.data)
        if serializer.is_valid():
            if ((request.data['topology_id'] != topology_id)
                    or (fabric_obj.name != request.data['name'])):
                logger.error("Failed to Update Fabric id " + str(id)\
                +" cannot change base Topology or Fabric Name")
            else:
                topology = Topology.objects.get(id=request.data['topology_id'])
                topology_json = json.loads(topology.topology_json)
                me = RequestValidator(request.META)
                fabric_obj.user_id = me.user_is_exist().user_id
                fabric_obj.validate = request.data['validate']
                fabric_obj.locked = request.data['locked']
                try:
                    sysId_list = []
                    fabric_obj.system_id = json.dumps(
                        request.data['system_id'])
                    for swtch in request.data['system_id']:
                        sysId_list.append(swtch['system_id'])
                    dup_items = [
                        k for k, v in Counter(sysId_list).items() if v > 1
                    ]
                    if len(dup_items) > 0:
                        error_string = ','.join(
                            str(item) for item in dup_items)
                        resp[
                            'Error'] = 'System id: ' + error_string + ' repeated.'
                        logger.error(resp['Error'])
                        return Response(resp,
                                        status=status.HTTP_400_BAD_REQUEST)
                except:
                    fabric_obj.system_id = []

                config_in_fabric = json.loads(fabric_obj.config_json)
                for config in config_in_fabric:
                    config_obj = Configuration.objects.get(
                        id=config['configuration_id'])
                    config_obj.used -= 1
                    config_obj.save()
                fabric_obj.config_json = json.dumps(
                    request.data['config_json'])
                for config in request.data['config_json']:
                    config_obj = Configuration.objects.get(
                        id=config['configuration_id'])
                    config_obj.used += 1
                    config_obj.save()
                fabric_obj.submit = request.data['submit']
                fabric_obj.instance = request.data['instance']
                # filling discovery rule db
                try:
                    dis_bulkObject_list = []
                    config_obj = request.data['config_json']
                    regex = fabric_obj.name + "(_)([1-9][0-9]*)(_)([a-zA-Z]*-[1-9])"
                    for switch_systemId_info in request.data['system_id']:
                        if not success:
                            break
                        switch_name = (re.search(
                            regex, switch_systemId_info['name'])).group(4)
                        replica_num = int(
                            (re.search(regex,
                                       switch_systemId_info['name'])).group(2))
                        for config in config_obj:
                            if switch_name == config['name']:
                                discoveryrule_name = 'serial_' + switch_systemId_info[
                                    'system_id']
                                old_dis_rule_name = DiscoveryRule.objects.filter(fabric_id =fabric_obj.id).\
                                                    filter(switch_name=switch_systemId_info['name'])
                                if old_dis_rule_name:
                                    try:
                                        find_obj = DiscoveryRule.objects.filter(
                                            name=discoveryrule_name)
                                        if find_obj:
                                            obj = DiscoveryRule.objects.get(
                                                name=discoveryrule_name)
                                            if obj.switch_name != switch_systemId_info[
                                                    'name']:
                                                success = False
                                                if obj.fabric_id == fabric_obj.id:
                                                    resp['Error'] = 'Serial id: '+switch_systemId_info['system_id']\
                                                                    +' is repeated in this fabric'
                                                resp['Error'] = 'switch: '+obj.switch_name+' is assigned with: '\
                                                                +switch_systemId_info['system_id']
                                                logger.error(resp['Error'])
                                                break
                                    except:
                                        pass
                                    try:
                                        dis_obj = DiscoveryRule.objects.get(
                                            switch_name=switch_systemId_info[
                                                'name'])
                                        if dis_obj.config_id != config[
                                                'configuration_id']:
                                            dis_obj.config_id = config[
                                                'configuration_id']
                                            dis_bulkObject_list.append(dis_obj)
#                                             dis_obj.save()
                                        if dis_obj.name != discoveryrule_name:
                                            dis_obj.name = discoveryrule_name
                                            dis_obj.subrules = [
                                                switch_systemId_info[
                                                    'system_id']
                                            ]
                                            dis_bulkObject_list.append(dis_obj)
#                                             dis_obj.save()
                                    except:
                                        pass
                                else:
                                    dis_rule_obj = DiscoveryRule()
                                    dis_rule_obj.priority = 100
                                    dis_rule_obj.name = discoveryrule_name
                                    dis_rule_obj.config_id = config[
                                        'configuration_id']
                                    dis_rule_obj.match = 'serial_id'
                                    dis_rule_obj.subrules = [
                                        switch_systemId_info['system_id']
                                    ]
                                    dis_rule_obj.fabric_id = fabric_obj.id
                                    dis_rule_obj.replica_num = replica_num
                                    dis_rule_obj.switch_name = switch_systemId_info[
                                        'name']
                                    dis_bulkObject_list.append(dis_obj)
                                    # saving objects as bulk at the end


#                                     dis_rule_obj.save()

                except:
                    success = False
                    logger.error(
                        'Failed to fill discoveryRule DB with fabric_id: ' +
                        str(fabric_obj.id))

                if success:
                    if delete_fabric_rules(id):
                        if (generate_fabric_rules(request.data['name'],\
                            request.data['instance'], fabric_obj, request.data['config_json'],\
                            topology_json)):
                            logger.info("Successfully  update Fabric id: " +
                                        str(id))
                            serializer = FabricGetDetailSerializer(fabric_obj)
                            data = serializer.data
                            data['config_json'] = json.loads(
                                data['config_json'])
                            try:
                                data['system_id'] = json.loads(
                                    data['system_id'])
                            except:
                                data['system_id'] = []
                            for obj in dis_bulkObject_list:
                                obj.save()
                            fabric_obj.save()
                            return Response(data)
                        else:
                            success = False
                            resp['Error'] = 'Failed to update Fabric'
                            logger.error("Failed to update Fabric id: " +
                                         str(id))
                    else:
                        success = False
                        resp['Error'] = 'Failed to update Fabric Rule DB'
                        logger.error(
                            "Failed to delete Rules from fabric Rule DB for Fabric id: "
                            + str(id))
                if not success:
                    return Response(resp, status=status.HTTP_400_BAD_REQUEST)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)