zoukankan      html  css  js  c++  java
  • CMDB服务器管理系统【s5day90】:API构造可插拔式插件逻辑

    1、服务器端目录结构:

    1、__init__.py

    from django.conf import settings
    from repository import models
    import importlib
    from .server import Server
    
    class PluginManger(object):
    
        def __init__(self):
            self.plugin_items = settings.PLUGIN_ITEMS
            self.basic_key = "basic"
            self.board_key = "board"
    
        def exec(self,server_dict):
            """
    
            :param server_dict:
            :return: 1,执行完全成功; 2, 局部失败;3,执行失败;4. 服务器不存在
            """
            ret = {'code': 1,'msg':None}
    
            hostname = server_dict[self.basic_key]['data']['hostname']
            server_obj = models.Server.objects.filter(hostname=hostname).first()
            if not  server_obj:
                ret['code'] = 4
                return ret
    
            obj = Server(server_obj,server_dict[self.basic_key],server_dict[self.board_key])
            obj.process()
    
            # 对比更新[硬盘,网卡,内存,可插拔的插件]
            for k,v in self.plugin_items.items():
                try:
                    module_path,cls_name = v.rsplit('.',maxsplit=1)
    
                    md = importlib.import_module(module_path)
                    cls = getattr(md,cls_name)
                    obj = cls(server_obj,server_dict[k])
                    obj.process()
                except Exception as e:
                    ret['code'] = 2
    
            return ret

    2、disk.py

    from repository import models
    
    class Disk(object):
        def __init__(self,server_obj,info):
            self.server_obj = server_obj
            self.disk_dict = info
    
        def process(self):
            # 硬盘、网卡和内存
            new_disk_info_dict = self.disk_dict['data']
            """
            {
                '0': {'slot': '0', 'pd_type': 'SAS', 'capacity': '279.396', 'model': 'SEAGATE ST300MM0006     LS08S0K2B5NV'},
                '1': {'slot': '1', 'pd_type': 'SAS', 'capacity': '279.396', 'model': 'SEAGATE ST300MM0006     LS08S0K2B5AH'},
                '2': {'slot': '2', 'pd_type': 'SATA', 'capacity': '476.939', 'model': 'S1SZNSAFA01085L     Samsung SSD 850 PRO 512GB               EXM01B6Q'},
                '3': {'slot': '3', 'pd_type': 'SATA', 'capacity': '476.939', 'model': 'S1AXNSAF912433K     Samsung SSD 840 PRO Series              DXM06B0Q'},
                '4': {'slot': '4', 'pd_type': 'SATA', 'capacity': '476.939', 'model': 'S1AXNSAF303909M     Samsung SSD 840 PRO Series              DXM05B0Q'},
                '5': {'slot': '5', 'pd_type': 'SATA', 'capacity': '476.939', 'model': 'S1AXNSAFB00549A     Samsung SSD 840 PRO Series
            }"""
            new_disk_info_list = self.server_obj.disk.all()
            """
            [
                obj,
                obj,
                obj,
            ]
            """
            new_disk_slot_set = set(new_disk_info_dict.keys())
            old_disk_slot_set = {obj.slot for obj in new_disk_info_list}
    
            # add_slot_list = new_disk_slot_set - old_disk_slot_set
            add_slot_list = new_disk_slot_set.difference(old_disk_slot_set)
            del_slot_list = old_disk_slot_set.difference(new_disk_slot_set)
            update_slot_list = old_disk_slot_set.intersection(new_disk_slot_set)
    
            add_record_list = []
            # 增加 [2,5]
            for slot in add_slot_list:
                value = new_disk_info_dict[slot]
                tmp = "添加硬盘..."
                add_record_list.append(tmp)
                value['server_obj'] = self.server_obj
                models.Disk.objects.create(**value)
            # 删除 [4,6]
            models.Disk.objects.filter(server_obj=self.server_obj, slot__in=del_slot_list).delete()
    
            # 更新 [7,8]
            for slot in update_slot_list:
                value = new_disk_info_dict[
                    slot]  # {'slot': '0', 'pd_type': 'SAS', 'capacity': '279.396', 'model': 'SEAGATE ST300MM0006     LS08S0K2B5NV'}
                obj = models.Disk.objects.filter(server_obj=self.server_obj, slot=slot).first()
                for k, new_val in value.items():
                    old_val = getattr(obj, k)
                    if old_val != new_val:
                        setattr(obj, k, new_val)
                obj.save()
    
        def add_disk(self):
            pass
    
        def del_disk(self):
            pass
    
        def update_disk(self):
            pass

    3、nic.py

    class Nic(object):
        def __init__(self,server_obj,info):
            self.server_obj = server_obj
            self.nic_dict = info
    
        def process(self):
            pass

    4、server.py

    from repository import models
    
    class Server(object):
    
        def __init__(self,server_obj,basic_dict,board_dict):
            self.server_obj = server_obj
            self.basic_dict = basic_dict
            self.board_dict = board_dict
    
        def process(self,):
            # 更新server表
            tmp = {}
            tmp.update(self.basic_dict['data'])
            tmp.update(self.board_dict['data'])
    
            # 服务器数据更新
            tmp.pop('hostname')
            record_list = []
            for k, new_val in tmp.items():
                old_val = getattr(self.server_obj, k)
                if old_val != new_val:
                    record = "[%s]的[%s]由[%s]变更为[%s]" % (self.server_obj.hostname, k, old_val, new_val)
                    record_list.append(record)
                    setattr(self.server_obj, k, new_val)
            self.server_obj.save()
            if record_list:
                models.ServerRecord.objects.create(server_obj=self.server_obj, content=';'.join(record_list))

    5、views.py

    import json
    from django.shortcuts import render,HttpResponse
    from django.views.decorators.csrf import csrf_exempt
    from django.conf import settings
    from repository import models
    from .plugins import PluginManger
    
    
    def server(request):
        # 客户端提交的最新资产数据
        server_dict = json.loads(request.body.decode('utf-8'))
    
        # 检查server表中是否有当前资产信息【主机名是唯一标识】
        if not server_dict['basic']['status']:
            return HttpResponse('臣妾做不到')
    
        manager = PluginManger()
        response = manager.exec(server_dict)
    
        return HttpResponse(json.dumps(response))

    settings.py在尾部添加如下内容:

    PLUGIN_ITEMS = {
        "nic": "api.plugins.nic.Nic",
        "disk": "api.plugins.disk.Disk",
        "memory": "api.plugins.memory.Memory",
    }
    

      

  • 相关阅读:
    1257: [CQOI2007]余数之和
    BZOJ1036[ZJOI2008]树的统计——树链剖分+线段树
    BZOJ4822[Cqoi2017]老C的任务——树状数组(二维数点)
    BZOJ4196[Noi2015]软件包管理器——树链剖分+线段树
    BZOJ4034[HAOI2015]树上操作——树链剖分+线段树
    BZOJ5415[Noi2018]归程——kruskal重构树+倍增+堆优化dijkstra
    BZOJ2120&2453数颜色——线段树套平衡树(treap)+set/带修改莫队
    BZOJ2141排队——树状数组套权值线段树(带修改的主席树)
    初探莫比乌斯反演及欧拉反演
    BZOJ1146[CTSC2008]网络管理——出栈入栈序+树状数组套主席树
  • 原文地址:https://www.cnblogs.com/luoahong/p/9337879.html
Copyright © 2011-2022 走看看