def get(self):
        # http://127.0.0.1:8000/v1/api_data_collection_devices/?device_id=3
        device_id = views_helper.get_request_value(self.request, 'device_id',
                                                   'GET')
        # load devices list,init action
        if not device_id:
            devices_list = Devices.objects.filter(status=1).values(
                'device_id', 'hostname')
            arry = []
            for item in devices_list:
                arry.append(item)
            data = {
                'devices': arry,
                'new_token': self.new_token,
                constants.STATUS: {
                    constants.STATUS: constants.TRUE,
                    constants.MESSAGE: constants.SUCCESS
                }
            }
            return api_return(data=data)
        else:

            arry = self.__set_items_info_by_device(device_id)
            data = {
                'data': arry,
                'new_token': self.new_token,
                constants.STATUS: {
                    constants.STATUS: constants.TRUE,
                    constants.MESSAGE: constants.SUCCESS
                }
            }
            return api_return(data=data)
 def post(self):
     """!@brief
     Create policy group
     @return data: the status of whether create successful and the inserted data
     """
     try:
         with transaction.atomic():
             data = {
                 'name': self.name,
                 'desc': self.desc,
                 'ostypeid': self.ostype,
             }
             if self.name is not '':
                 get_name_from_cpg = self.get_cp_group(
                     **{'name': self.name})
                 if get_name_from_cpg is not False:
                     data = {
                         constants.STATUS: {
                             constants.STATUS:
                             constants.FALSE,
                             constants.MSG_TYPE:
                             'NAME_DUPLICATE',
                             constants.MESSAGE:
                             constants.
                             COLLECTION_POLICY_GROUP_NAME_DUPLICATE
                         }
                     }
                     return api_return(data=data)
             cps = views_helper.get_request_value(self.request, 'cps',
                                                  'BODY')
             serializer = CollPolicyGroupSerializer(data=data)
             if serializer.is_valid(Exception):
                 serializer.save()
                 policy_group_data = []
                 for per_cp in cps:
                     per_cp['policy_group'] = int(
                         serializer.data.get('policy_group_id'))
                     per_cp['history'] = time.time()
                     per_cp['policy'] = per_cp['policy']
                     policy_group_data.append(per_cp)
                 serializer_related = PolicyGroupSerializer(
                     data=policy_group_data, many=True)
                 if serializer_related.is_valid(Exception):
                     serializer_related.save()
                 data = {
                     'data': {
                         'data_coll_policy': serializer.data,
                         'data_policys_groups': serializer_related.data,
                     },
                     'new_token': self.new_token,
                     constants.STATUS: {
                         constants.STATUS: constants.TRUE,
                         constants.MESSAGE: constants.POST_SUCCESSFUL
                     }
                 }
                 return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 3
0
 def delete(self):
     """@brief
     delete a group
     @return: the success when delete success and error when delete fail
     """
     try:
         with transaction.atomic():
             if self.group_id:
                 kwards_schedules = {'device_group_id': self.group_id}
                 queryset_schedules = Schedules.objects.filter(
                     **kwards_schedules)
                 if queryset_schedules.count() != 0:
                     data = {
                         'new_token': self.new_token,
                         constants.STATUS: {
                             constants.STATUS: constants.FALSE,
                             constants.MESSAGE:
                             constants.EXISTS_IN_SCHEDULES
                         }
                     }
                     return api_return(data=data)
                 kwards_devicegroup = {'group_id': self.group_id}
                 queryset_device = DevicesGroups.objects.filter(
                     **kwards_devicegroup)
                 if queryset_device.count() != 0:
                     data = {
                         'new_token': self.new_token,
                         constants.STATUS: {
                             constants.STATUS:
                             constants.FALSE,
                             constants.MESSAGE:
                             constants.EXISTS_IN_DEVICESGROUPS
                         }
                     }
                     return api_return(data=data)
                 queryset = self.get_group({'group_id': self.group_id})
                 if queryset:
                     queryset.delete()
                     data = {
                         'new_token': self.new_token,
                         constants.STATUS: {
                             constants.STATUS: constants.TRUE,
                             constants.MESSAGE: constants.SUCCESS
                         }
                     }
                     return api_return(data=data)
                 else:
                     data = {
                         'new_token': self.new_token,
                         constants.STATUS: {
                             constants.STATUS: constants.FALSE,
                             constants.MESSAGE: constants.GROUP_NOT_EXIST
                         }
                     }
                 return api_return(data=data)
     except Exception, e:
         transaction.rollback()
         print e
         raise e
Esempio n. 4
0
 def get(self):
     """!@brief
     Rest Api of GET, get all the data for summary page or get the data according to table id
     @return data: the data for summary page
     """
     try:
         if self.id is not '':
             data = self.get_info_by_table_id(self.id)
             return api_return(data=data)
         field_relation_ships = {
             'table_id': 'id',
             'name': 'name',
             'descr': 'descr',
         }
         query_data = {
             'name': self.name,
             'desc': self.desc,
         }
         search_fields = ['name', 'desc']
         sorts, search_conditions = views_helper.get_search_conditions(
             self.request, field_relation_ships, query_data, search_fields)
         total_num = len(DataTable.objects.all())
         if search_conditions:
             queryset = DataTable.objects.filter(
                 **search_conditions).values(*[
                     'table_id', 'descr', 'name', 'coll_policy', 'groups',
                     'tree', 'coll_policy__policy_type'
                 ]).order_by(*sorts)
         else:
             queryset = DataTable.objects.all().values(*[
                 'table_id', 'descr', 'name', 'coll_policy', 'groups',
                 'tree', 'coll_policy__policy_type'
             ]).order_by(*sorts)
         # serializer = ActionPolicyDataTableSerializer(queryset, many=True)
         paginator = Paginator(list(queryset), int(self.max_size_per_page))
         contacts = paginator.page(int(self.page_from))
         data = {
             'data': {
                 'data': contacts.object_list,
             },
             'new_token': self.new_token,
             'num_page': paginator.num_pages,
             # 'page_range': list(paginator.page_range),
             'page_has_next': contacts.has_next(),
             'total_num': total_num,
             'current_page_num': contacts.number,
             constants.STATUS: {
                 constants.STATUS: constants.TRUE,
                 constants.MESSAGE: constants.SUCCESS
             },
         }
         return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 5
0
 def post(self):
     """!@brief
     add one schedule into schedule table,and many items into item table
     @author Gin Chen
     @date 2018/1/5
     """
     try:
         with transaction.atomic():
             param_dict = self.__set_request_param()
             opt = DataCollectionOptCls(**param_dict)
             # ready
             devices_list, coll_policy_list = opt.add_new_schedule_ready()
             # check whether the tree of cp is null or not
             for cp_dict in coll_policy_list:
                 cp_id = cp_dict['coll_policy_id']
                 if cp_dict['item_type'] == constants.ITEM_TYPE_CLI:
                     cp_leaf_nodes = CollPolicyRuleTree.objects.filter(
                         coll_policy=cp_id,
                         is_leaf=constants.LEAF_NODE_MARK)
                     if len(cp_leaf_nodes) == 0:
                         data = {
                             'new_token': self.new_token,
                             constants.STATUS: {
                                 constants.STATUS: constants.FALSE,
                                 constants.MESSAGE:
                                 constants.NULL_TREE_IN_CP
                             }
                         }
                         return api_return(data=data)
             # insert schedule
             res = opt.insert_new_schedule(devices_list, coll_policy_list)
             if res[0]:
                 # create item by schedule
                 opt.insert_new_items(devices_list, res[1],
                                      coll_policy_list)
                 data = {
                     'new_token': self.new_token,
                     constants.STATUS: {
                         constants.STATUS: constants.TRUE,
                         constants.MESSAGE: constants.SUCCESS
                     }
                 }
             else:
                 data = {
                     'new_token': self.new_token,
                     constants.STATUS: {
                         constants.STATUS: constants.FALSE,
                         constants.MESSAGE: res[1]
                     }
                 }
             return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
 def get(self):
     # http://127.0.0.1:8000/v1/api_data_collection_policy/?policy_id=3&device_name=test
     # http://127.0.0.1:8000/v1/api_data_collection_policy/?page=1&rows=1&policy_id=3&device_name=test
     coll_policy_id = views_helper.get_request_value(self.request, "coll_policy_id", "GET")
     device_name = views_helper.get_request_value(self.request, "device", "GET")
     if not coll_policy_id:
         # load all coll_policy
         coll_policy_list = CollPolicy.objects.values('coll_policy_id', 'name', 'policy_type')
         arry = []
         for item in coll_policy_list:
             arry.append(item)
         data = {
             'policies': arry,
             'new_token': self.new_token,
             constants.STATUS: {
                 constants.STATUS: constants.TRUE,
                 constants.MESSAGE: constants.SUCCESS
             }
         }
         return api_return(data=data)
     else:
         response_json_data = Tool.get_valid_item_by_cp({"policys_groups__status": 1, "coll_policy_id": coll_policy_id})
         arry = []
         for one_recoder in response_json_data:
             if device_name:
                 if device_name in one_recoder['device_name']:
                     isFilter = True
                 else:
                     isFilter = False
             else:
                 isFilter = True
             if int(one_recoder['coll_policy_id']) == int(coll_policy_id) and isFilter:
                 info = {
                     'deviceNo': one_recoder['device_id'],
                     'device': one_recoder['device_name'],
                     'status': Tool.set_cp_status_mapping(one_recoder['btn_status']),
                 }
                 arry.append(info)
         total_num = len(arry)
         paginator = Paginator(arry, int(self.max_size_per_page))
         contacts = paginator.page(int(self.page_from))
         data = {
             'data': contacts.object_list,
             'num_page': paginator.num_pages,
             'page_has_next': contacts.has_next(),
             'total_num': total_num,
             'current_page_num': contacts.number,
             'new_token': self.new_token,
             constants.STATUS: {
                 constants.STATUS: constants.TRUE,
                 constants.MESSAGE: constants.SUCCESS
             }
         }
         return api_return(data=data)
Esempio n. 7
0
 def get(self):
     """!@brief
     When select column2 after choosing column1 in 新规页面, column1 and column2 should be same with below 3 points:
     1.the same device group
     2.the same schedule_id(data_table_item-->item-->schedule)
     3.the same policy execute inteval(data_table_item-->item-->policys_groups)
     @post return verify result
     @return data: return verify result
     """
     try:
         if self.table_id_A is not '' and self.table_id_B is not '':
             # table_a = DataTable.objects.filter(table_id=self.table_id_A).values('groups', 'coll_policy__value_type',
             #                                                                     'coll_policy__policy_type')
             table_a_str = ''
             table_b_str = ''
             table_a = DataTableItems.objects.filter(
                 table_id=self.table_id_A).values('table__groups',
                                                  'item__schedule',
                                                  'item__policys_groups')
             if table_a:
                 table_a_str = str(table_a[0]['table__groups']) + '_' + str(
                     table_a[0]['item__schedule']) + '_' + str(
                         table_a[0]['item__policys_groups'])
             # table_b = DataTable.objects.filter(table_id=self.table_id_B).values('groups', 'coll_policy__value_type',
             #                                                                     'coll_policy__policy_type')
             table_b = DataTableItems.objects.filter(
                 table_id=self.table_id_B).values('table__groups',
                                                  'item__schedule',
                                                  'item__policys_groups')
             if table_b:
                 table_b_str = str(table_b[0]['table__groups']) + '_' + str(
                     table_b[0]['item__schedule']) + '_' + str(
                         table_b[0]['item__policys_groups'])
             if table_a_str == table_b_str:
                 data = {
                     constants.STATUS: {
                         constants.STATUS: constants.TRUE,
                         constants.MESSAGE: constants.SUCCESS
                     },
                 }
                 return api_return(data=data)
             data = {
                 constants.STATUS: {
                     constants.STATUS:
                     constants.FALSE,
                     constants.MESSAGE:
                     constants.COLUMN_A_COLUMN_B_VERIFY_FAILED
                 },
             }
             return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 8
0
    def put(self):
        """!@brief
        commit the collection policy update information
        @param
        @pre
        @post
        @note
        @return the update information
        @author Gin Chen
        @date 2018/1/18
        """
        coll_policy_id = views_helper.get_request_value(self.request, "coll_policy_id", "BODY")
        name = views_helper.get_request_value(self.request, "coll_policy_name", "BODY")
        command = views_helper.get_request_value(self.request, "command", "BODY")
        desc = views_helper.get_request_value(self.request, "desc", "BODY")
        ostype = views_helper.get_request_value(self.request, "ostype", "BODY")
        coll_policy_update_data = {
            'name': name,
            'cli_command': command,
            'desc': desc,
            'ostype': ostype
        }
        if len(CollPolicy.objects.filter(~Q(coll_policy_id=coll_policy_id), name=name)):
            data = {
                'data': '',
                'new_token': self.new_token,
                constants.STATUS: {
                    constants.STATUS: constants.FALSE,
                    constants.MSG_TYPE: 'NAME_DUPLICATE',
                    constants.MESSAGE: constants.COLLECTION_POLICY_NAME_DUPLICATE
                }

            }
            return api_return(data=data)
        obj = CollPolicy.objects.get(coll_policy_id=coll_policy_id)
        serializer = CollPolicyEditSerializer(instance=obj, data=coll_policy_update_data)
        try:
            if serializer.is_valid():
                serializer.save()
                data = {
                    'data': serializer.data,
                    'new_token': self.new_token,
                    constants.STATUS: {
                        constants.STATUS: constants.TRUE,
                        constants.MESSAGE: constants.SUCCESS
                    }

                }
                return api_return(data=data)
        except Exception as e:
            if constants.DEBUG_FLAG:
                print traceback.format_exc(e)
            return exception_handler(e)
Esempio n. 9
0
 def post(self):
     """@brief
     create a new group
     @return: the created group when create success and error when create fail
     """
     if "," in self.name:
         data = {
             'new_token': self.new_token,
             constants.STATUS: {
                 constants.STATUS: constants.FALSE,
                 constants.MESSAGE: constants.GROUP_NAME_FORMAT_ERROR
             }
         }
         return api_return(data=data)
     kwargs_groupname = {'name': self.name}
     groups = self.get_group(kwargs_groupname)
     if groups:
         data = {
             'new_token': self.new_token,
             constants.STATUS: {
                 constants.STATUS: constants.FALSE,
                 constants.MSG_TYPE: constants.NAME_DUPLICATE,
                 constants.MESSAGE: constants.GROUP_ALREADY_EXISTS
             }
         }
         return api_return(data=data)
     kwargs_ostypeid = {"ostypeid": self.ostype_id}
     ostype = self.get_ostype(kwargs_ostypeid)
     ostype_id = ostype.ostypeid
     ostype = model_to_dict(ostype)
     try:
         with transaction.atomic():
             data = {
                 'name': self.name,
                 'desc': self.desc,
                 'ostype': ostype,
             }
             serializer = DeviceGroupIDNameSerializer(data=data)
             if serializer.is_valid(Exception):
                 serializer.save(ostype_id=ostype_id)
                 data = {
                     'data': serializer.data,
                     'new_token': self.new_token,
                     constants.STATUS: {
                         constants.STATUS: constants.TRUE,
                         constants.MESSAGE: constants.SUCCESS
                     }
                 }
             return api_return(data=data)
     except Exception, e:
         transaction.rollback()
         print e
         raise e
Esempio n. 10
0
 def delete(self):
     """!@brief
     Rest Api of DELETE, delete data according to table id
     @return data: the status of whether delete successful
     """
     try:
         with transaction.atomic():
             kwargs = {'table_id': self.id}
             data_in_dp = self.get_data_table(**kwargs)
             data_in_trigger = self.get_trigger(self.id)
             data_table_item_info = self.get_data_table_item_for_delete(
                 **{'table_id': self.id})
             if len(data_in_dp) <= 0:
                 data = {
                     'new_token': self.new_token,
                     constants.STATUS: {
                         constants.STATUS:
                         constants.FALSE,
                         constants.MESSAGE:
                         constants.DATA_TABLE_NOT_EXIST_IN_SYSTEM
                     }
                 }
                 return api_return(data=data)
             if len(data_in_trigger) > 0:
                 data = {
                     'new_token': self.new_token,
                     constants.STATUS: {
                         constants.STATUS:
                         constants.FALSE,
                         constants.MESSAGE:
                         constants.DATA_TABLE_EXIST_IN_TRIGGER
                     }
                 }
                 return api_return(data=data)
             data_table_item_info.delete()
             data_in_dp.delete()
             data = {
                 'new_token': self.new_token,
                 constants.STATUS: {
                     constants.STATUS: constants.TRUE,
                     constants.MESSAGE: constants.DELETE_SUCCESSFUL
                 }
             }
             return api_return(data=data)
     except Exception, e:
         transaction.rollback()
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 11
0
 def get(self):
     try:
         queryset = CollPolicy.objects.all().values('coll_policy_id',
                                                    'value_type', 'name',
                                                    'policy_type')
         if self.id != '':
             queryset = CollPolicy.objects.filter(ostype=self.id).values(
                 'coll_policy_id', 'value_type', 'name', 'policy_type')
         # serializer = CollPolicyNameSerializer(queryset, many=True)
         for per in queryset:
             if per['policy_type'] == 1:
                 # SNMP
                 per['name'] = '[SNMP]' + per['name']
             else:
                 # CLI
                 per['name'] = '[CLI]' + per['name']
         data = {
             'data': list(queryset),
             'new_token': self.new_token,
             constants.STATUS: {
                 constants.STATUS: constants.TRUE,
                 constants.MESSAGE: constants.SUCCESS
             }
         }
         return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 12
0
    def get(self):
        """!@brief
        when jump to 'add a new schedule page',init ostype ,policy group, device group list
        @param
        @pre
        @post
        @return ostype list,policy group list,
        @author Gin Chen
        @date 2018/1/5
        """
        if self.ostype_id:
            # when Os type is selected
            cp_groups_dict = self.__get_coll_policy_groups()
            device_groups_dict = self.__get_device_groups()
            data = {
                'device_groups': device_groups_dict,
                'cp_groups': cp_groups_dict,
                'new_token': self.new_token,
                constants.STATUS: {
                    constants.STATUS: constants.TRUE,
                    constants.MESSAGE: constants.SUCCESS
                }
            }
        else:
            all_ostype_data = self.__get_ostype()
            data = {
                'data': all_ostype_data,
                'new_token': self.new_token,
                constants.STATUS: {
                    constants.STATUS: constants.TRUE,
                    constants.MESSAGE: constants.SUCCESS
                }
            }

        return api_return(data=data)
Esempio n. 13
0
 def post(self):
     """!@brief
     highlight function
     @param
     @pre
     @post
     @return the highlighted page
     @author Gin Chen
     @date 2017/12/18
     """
     request_dict = {
         'data': self.raw_data,
         'tree': self.tree,
         'tree_id': self.tree_id
     }
     try:
         render = Render(**request_dict)
         html_data = render.render()
         data = {
             'data': html_data,
             'new_token': self.new_token,
             constants.STATUS: {
                 constants.STATUS: constants.TRUE,
                 constants.MESSAGE: constants.SUCCESS
             }
         }
         return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 14
0
 def get(self):
     """!@brief
     Rest Api of GET, verify whether data table name was exist
     @return data: the status
     """
     try:
         if self.name is not '':
             get_name_from_data_table = self.get_data_table(
                 **{'name': self.name})
             data = {
                 constants.STATUS: {
                     constants.STATUS: constants.TRUE,
                     constants.MESSAGE: constants.SUCCESS
                 }
             }
             if len(get_name_from_data_table) > 0:
                 data = {
                     constants.STATUS: {
                         constants.STATUS: constants.FALSE,
                         constants.MSG_TYPE: 'NAME_DUPLICATE',
                         constants.MESSAGE:
                         constants.DATA_TABLE_NAME_DUPLICATE
                     }
                 }
             return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 15
0
 def get(self):
     """!@brief
     Get data in left for Step 4 when click [新规登陆]
     Get the tree for left in step 4
     @return data: data for left in step 4
     """
     try:
         if self.id is not '':
             policy_tree = Policy_tree(self.id)
             # get policy tree
             policy_tree_dict = policy_tree.get_policy_tree()
             data = {
                 'data': {
                     'data': policy_tree_dict,
                 },
                 'new_token': self.new_token,
                 constants.STATUS: {
                     constants.STATUS: constants.TRUE,
                     constants.MESSAGE: constants.SUCCESS,
                 },
             }
             return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 16
0
    def delete(self):

        schedule_id = views_helper.get_request_value(self.request, 'id', 'GET')
        try:
            with transaction.atomic():
                # close all function off thought update status =1
                obj = Schedules.objects.get(schedule_id=schedule_id)
                all_function_status = obj.status
                # all function off is opened
                if all_function_status == 0 and obj.policy_group is None:
                    device_group_id = obj.device_group
                    Schedules.objects.filter(
                        device_group=device_group_id).update(status=1)
                # delete items table
                # delete schedule table
                Items.objects.filter(schedule_id=schedule_id).delete()
                Schedules.objects.get(schedule_id=schedule_id).delete()
                data = {
                    'new_token': self.new_token,
                    constants.STATUS: {
                        constants.STATUS: constants.TRUE,
                        constants.MESSAGE: constants.SUCCESS
                    }
                }
                return api_return(data=data)
        except Exception as e:
            if constants.DEBUG_FLAG:
                print traceback.format_exc(e)
            return exception_handler(e)
Esempio n. 17
0
    def delete(self):
        """!@brief
       delete the rule
       @param
       @pre
       @post
       @note
       @return data rule tree and block rule tree
       @author Gin Chen
       @date 2017/12/25
       """
        try:
            rule_id = views_helper.get_request_value(self.request, key='rule_id', method_type='GET')
            policy_tree_id = views_helper.get_request_value(self.request, key='coll_policy_id', method_type='GET')
            CollPolicyCliRule.objects.get(ruleid=rule_id).delete()
            p = Policy_tree(policy_tree_id)
            rule_tree_tuple = p.get_rules_tree()
            data = {
                'data': {
                    "block_rule_tree_json": rule_tree_tuple[0],
                    "data_rule_tree_json": rule_tree_tuple[1]
                },
                constants.STATUS: {
                    constants.STATUS: constants.TRUE,
                    constants.MESSAGE: constants.SUCCESS
                }

            }
            return api_return(data=data)
        except Exception, e:
            if constants.DEBUG_FLAG:
                print traceback.format_exc(e)
            return exception_handler(e)
Esempio n. 18
0
    def get(self):
        """!@brief
        load the rule information when open the rule edit page
        @param
        @pre
        @post
        @return rule information,verify result(rule_is_used,is_processing,is_locked)
        @author Gin Chen
        @date 2017/12/25
        """
        try:
            coll_policy_id = views_helper.get_request_value(self.request, key='coll_policy_id', method_type='GET')
            rule_id = views_helper.get_request_value(self.request, key='rule_id', method_type='GET')
            query_set = CollPolicyRuleTree.objects.filter(rule=rule_id, coll_policy=coll_policy_id)
            is_used = False
            is_processing = False
            is_locked = False
            if len(query_set) > 0:
                is_processing = self.__judge_rule_is_processing(coll_policy_id)
                is_locked = self.__judge_rule_is_locked(coll_policy_id)
                is_used = True
            rule_info = CollPolicyCliRule.objects.get(ruleid=rule_id)
            result_dict = CollPolicyCliRuleSerializer(rule_info).data
            split_char = result_dict['split_char']
            if split_char:
                if split_char == '@space@':
                    result_dict['split_char'] = 4
                    result_dict['other_char'] = None
                elif split_char == ',':
                    result_dict['split_char'] = 1
                    result_dict['other_char'] = None

                elif split_char == '/':
                    result_dict['split_char'] = 2
                    result_dict['other_char'] = None
                else:
                    result_dict['split_char'] = 3
                    result_dict['other_char'] = split_char

            data = {
                'rule_is_used': is_used,
                'is_processing': is_processing,
                'is_locked': is_locked,
                'data': result_dict,
                'new_token': self.new_token,
                constants.STATUS: {
                    constants.STATUS: constants.TRUE,
                    constants.MESSAGE: constants.SUCCESS
                }
            }
            return api_return(data=data)
        except Exception, e:
            if constants.DEBUG_FLAG:
                print traceback.format_exc(e)
            return exception_handler(e)
Esempio n. 19
0
 def get(self):
     """!@brief
         Rest Api of GET, verify the expression
         @return data: the status of whether verify successful
         """
     try:
         data = self.expression_verify()
         if data[constants.STATUS] is not 'False':
             data = {
                 constants.STATUS: {
                     constants.STATUS: constants.TRUE,
                     constants.MESSAGE: constants.SUCCESS
                 },
             }
             return api_return(data=data)
         else:
             return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
 def get(self, action_name=None):
     """!@brief
     Rest Api of GET, get all the data for summary page or get the data according to action name
     @return data: the data for summary page
     """
     try:
         data = self.prepare_data_for_memory_cache(action_name)
         return api_return(data=data)
     except Exception as e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 21
0
    def put(self):
        """@brief
        check and change the status of telnet and snmp in Device_Tmp table by the list of device_id
        @return: the status of check result
        """
        try:
            with transaction.atomic():
                data_list = self.data_list
                data_return = []
                # telnet test
                pool = ThreadPool(device_views.CLI_THREADPOOL_SIZE)
                res_telnet = pool.map(self.telnet_status_check, data_list)
                pool.close()
                pool.join()
                for x in res_telnet:
                    device_pre = DevicesTmp.objects.get(device_id=x[1])
                    telnet_res = x[0]
                    data = {
                        'telnet_status': telnet_res,
                    }
                    serializer = DevicesTmpSerializer(device_pre, data=data, partial=True)
                    if serializer.is_valid(Exception):
                        serializer.save()
                # snmp test
                pool = ThreadPool(device_views.CLI_THREADPOOL_SIZE)
                res_snmp = pool.map(self.snmp_status_check, data_list)
                pool.close()
                pool.join()

                for x in res_snmp:
                    device_pre = DevicesTmp.objects.get(device_id=x[1])
                    snmp_res = x[0]
                    data = {
                        'snmp_status': snmp_res,
                    }
                    serializer = DevicesTmpSerializer(device_pre, data=data, partial=True)
                    if serializer.is_valid(Exception):
                        serializer.save()
                    data_return.append(serializer.data)
                data = {
                    'data': data_return,
                    'new_token': self.new_token,
                    constants.STATUS: {
                        constants.STATUS: constants.TRUE,
                        constants.MESSAGE: constants.SUCCESS
                    },
                }
                return api_return(data=data)
        except Exception, e:
            transaction.rollback()
            print e
            raise e
Esempio n. 22
0
 def csv_export(self):
     try:
         if self.id is not '':
             data_result = self.get_info_by_table_id(self.id)
             check_item_name = constants.EXPORT_CSV_TITLE_COLUMN_4
             csv_data = []
             if len(data_result['data']['data']):
                 check_item_name = data_result['data']['data'][0][
                     'checkitem']
                 if data_result['data']['data'][0]['item_type'].upper(
                 ) == 'SNMP':
                     check_item_name = 'Value'
                     constants.EXPORT_CSV_TITLE_COLUMN_3 = 'OID'
                 for per in data_result['data']['data']:
                     if per['item_type'].upper() == 'CLI':
                         csv_data.append([
                             per['hostname'], per['date'], per['path'],
                             per['value']
                         ])
                     else:
                         csv_data.append([
                             per['hostname'], per['date'], per['oid'],
                             per['value']
                         ])
             title = [
                 constants.EXPORT_CSV_TITLE_COLUMN_1,
                 constants.EXPORT_CSV_TITLE_COLUMN_2,
                 constants.EXPORT_CSV_TITLE_COLUMN_3, check_item_name
             ]
             script_dir = os.path.split(os.path.realpath(__file__))[0]
             csv_path = os.path.join(
                 os.path.dirname(
                     os.path.dirname(
                         os.path.dirname(os.path.dirname(script_dir)))),
                 constants.CSV_PATH)
             csv_data.insert(0, title)
             # create csv
             result = csv_export.csv_export(csv_path, csv_data)
             # download csv
             if result is False:
                 data = {
                     constants.STATUS: {
                         constants.STATUS: constants.FALSE,
                         constants.MESSAGE: constants.CSV_PATH_NOT_EXIST
                     },
                 }
                 return api_return(data=data)
             return result
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 23
0
 def get(self):
     """!@brief
     init policy tree edit page
     @note
     @return policy tree info,data rule rule,block rule
     @author Gin Chen
     @date 2017/12/18
     """
     try:
         self.coll_policy_id = views_helper.get_request_get(self.request, 'coll_policy_id')
         cp = CollPolicy.objects.get(coll_policy_id=self.coll_policy_id)
         cli_command_result = cp.cli_command_result
         policy_name = cp.name
         policy_tree = Policy_tree(self.coll_policy_id)
         # get policy tree
         policy_tree_dict = policy_tree.get_policy_tree()
         # get rules of the policy tree
         rule_tree_tuple = policy_tree.get_rules_tree()
         if rule_tree_tuple == 'Error':
             data = {
                 'data': '',
                 'new_token': self.new_token,
                 constants.STATUS: {
                     constants.STATUS: constants.FALSE,
                     constants.MESSAGE: constants.LOAD_RULE_TYPE_ERROR
                 }
             }
         else:
             block_rule_tree_dict = rule_tree_tuple[0]
             data_rule_tree_dict = rule_tree_tuple[1]
             data = {
                 'data': {
                     "coll_policy_name": policy_name,
                     "cli_command_result": cli_command_result,
                     "policy_tree_json": policy_tree_dict,
                     "block_rule_tree_json": block_rule_tree_dict,
                     "data_rule_tree_json": data_rule_tree_dict,
                 },
                 'new_token': self.new_token,
                 constants.STATUS: {
                     constants.STATUS: constants.TRUE,
                     constants.MESSAGE: constants.SUCCESS
                 }
             }
         return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
 def delete(self):
     """!@brief
     Delete policy group data
     @return data: the status of whether deleted successful
     """
     try:
         # self.get_execute_ing()
         with transaction.atomic():
             kwargs = {'policy_group_id': self.id}
             verify_result = self.verify_column(self.id)
             if not verify_result['status']:
                 data = {
                     'new_token': self.new_token,
                     constants.STATUS: {
                         constants.STATUS:
                         constants.FALSE,
                         constants.MESSAGE:
                         constants.COLL_POLICY_GROUP_EXIST_IN_SCHEDULE
                     }
                 }
                 return api_return(data=data)
             data = self.del_policy_group_and_coll_policy_group(**kwargs)
             if data is True:
                 data = {
                     'new_token': self.new_token,
                     constants.STATUS: {
                         constants.STATUS: constants.TRUE,
                         constants.MESSAGE: constants.DELETE_SUCCESSFUL
                     }
                 }
             return api_return(data=data)
     except Exception, e:
         transaction.rollback()
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 25
0
 def post(self):
     try:
         output = self.snmp_work()
         data = {
             'data': {
                 'data': output,
             },
             constants.STATUS: {
                 constants.STATUS: constants.TRUE,
                 constants.MESSAGE: constants.PUT_SUCCESSFUL
             }
         }
         return api_return(data=data)
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
    def put(self):
        # http://127.0.0.1:8000/v1/api_data_collection_devices/
        # request param: is_all,coll_policy_id,device_id,policy_group_id,status
        # is_all =1: all stop,is_all = 0:stop some item
        is_all = int(
            views_helper.get_request_value(self.request, 'is_all', 'BODY'))
        coll_policy_id = views_helper.get_request_value(
            self.request, 'coll_policy_id', 'BODY')
        device_id = views_helper.get_request_value(self.request, 'device_id',
                                                   'BODY')
        status = int(
            views_helper.get_request_value(self.request, 'status', 'BODY'))
        policy_group_id = int(
            views_helper.get_request_value(self.request, 'policy_group_id',
                                           'BODY'))

        try:
            if is_all == 1:
                # stop all items of the device
                Items.objects.filter(device=device_id).update(status=status)
            else:
                policys_groups_id_queryset = PolicysGroups.objects.filter(
                    policy=coll_policy_id, policy_group=policy_group_id)

                with transaction.atomic():
                    for obj in policys_groups_id_queryset:
                        Items.objects.filter(
                            device=device_id,
                            coll_policy=obj.policy,
                            policys_groups=obj.policys_groups_id).update(
                                status=status)

            data = {
                'new_token': self.new_token,
                constants.STATUS: {
                    constants.STATUS: constants.TRUE,
                    constants.MESSAGE: constants.SUCCESS
                }
            }
            return api_return(data=data)
        except Exception as e:
            print e
            return exception_handler(e)
Esempio n. 27
0
 def get(self):
     """!@brief
     load the collection policy information when open the collection policy edit page from cp tree page
     @param
     @pre
     @post
     @note
     @return rule information,verify result
     @author Gin Chen
     @date 2018/1/18
     """
     try:
         coll_policy_id = views_helper.get_request_value(self.request, "coll_policy_id", "GET")
         obj = CollPolicy.objects.get(coll_policy_id=coll_policy_id)
         is_used = False
         if not Tool.get_policy_status(coll_policy_id):
             is_used = True
         is_not_in_group = True
         if len(PolicysGroups.objects.filter(policy=coll_policy_id)) > 0:
             is_not_in_group = False
         column_status={
             'name': True,
             'desc': True,
             'ostype': is_not_in_group,
             'cli_command': is_used
         }
         serializer = CollPolicyEditSerializer(obj)
         data = {
             'data': {
                 'policy_detail': serializer.data,
                 'verify_result': column_status
             },
             'new_token': self.new_token,
             constants.STATUS: {
                 constants.STATUS: constants.TRUE,
                 constants.MESSAGE: constants.SUCCESS
             }
         }
         return api_return(data=data)
     except Exception as e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 28
0
    def get(self):

        device_name = views_helper.get_request_value(self.request, 'device', 'GET')
        try:

            emergency_stop_list = Tool.get_emergency_stop_list(device_name)
            arry = self.__set_emergency_stop_list_table_view(emergency_stop_list)
            data = {
                'data': arry,
                'new_token': self.new_token,
                constants.STATUS: {
                    constants.STATUS: constants.TRUE,
                    constants.MESSAGE: constants.SUCCESS
                }
            }
            return api_return(data=data)
        except Exception as e:
            print e
            return exception_handler(e)
Esempio n. 29
0
 def get(self):
     try:
         queryset = Ostype.objects.all()
         if self.id:
             query_conditions = {'ostypeid': self.id}
             queryset = Ostype.objects.filter(**query_conditions)
         serializer = OstypeSerializer(queryset, many=True)
         data = {
             'data': serializer.data,
             'new_token': self.new_token,
             constants.STATUS: {
                 constants.STATUS: constants.TRUE,
                 constants.MESSAGE: constants.SUCCESS
             }
         }
         return api_return(data=data)
     except Exception, e:
         print traceback.format_exc(e)
         return exception_handler(e)
Esempio n. 30
0
 def delete(self):
     # self.request.session[self.username] = None
     # if self.request.session[self.username] is None:
     #     data = {
     #         constants.STATUS: {
     #             'status': 'True',
     #             'message': 'Logout Success.',
     #             'username': self.username
     #         }
     #     }
     #     return api_return(data=data)
     # else:
     #     data = {
     #         constants.STATUS: {
     #             'status': 'False',
     #             'message': 'Logout Success.',
     #             'username': self.username
     #         }
     #     }
     #     return api_return(data=data)
     try:
         self.logger.info(constants.USER_LOGOUT_SUCCESSFUL)  ###Logger###
         self.request.session.clear()
         data = {
             constants.USERNAME: self.username,
             constants.STATUS: {
                 constants.STATUS: constants.TRUE,
                 constants.MESSAGE: constants.USER_LOGOUT_SUCCESSFUL
             }
         }
         return api_return(data=data)
         # print self.request.session.keys()
         # print self.request.session.get('TOKEN_IN_SESSION')
     except Exception, e:
         if constants.DEBUG_FLAG:
             print traceback.format_exc(e)
         return exception_handler(e)