Browse Source

feat:dcim接口,资产、告警

TzuxinChen 3 months ago
parent
commit
fee10ab809

+ 33 - 0
api/dcim/alarm_api.py

@@ -0,0 +1,33 @@
+
+from common import config
+from common.util import req_api
+
+
+class AlarmApi:
+    def __init__(self):
+        self.headers = None
+
+    def get_alarm_current(self, page_index: int = 1, page_size: int = 400, alarm_severity:int = None, start_time: int = None,
+                          end_time: int = None, site_dns: list = None, dns: list = None, is_history=False):
+        """
+        获取当前的告警信息
+        :return:
+        """
+        params ={}
+        if alarm_severity is not None:
+            params['alarmSeverity'] = alarm_severity
+        if start_time is not None:
+            params['startTime'] = start_time
+        if end_time is not None:
+            params['endTime'] = end_time
+        if site_dns is not None:
+            params['siteDns'] = site_dns
+        if dns is not None:
+            params['dns'] = dns
+        params['pageIndex'] = page_index
+        params['pageSize'] = page_size
+        if is_history:
+            url = f'{config.DCIM_BASE_URL}/rest/openapi/neteco/nbi/v2/alarm/history'
+        else:
+            url = f'{config.DCIM_BASE_URL}/rest/openapi/neteco/nbi/v2/alarm/current'
+        return req_api(url, headers=self.headers, params=params)

+ 50 - 0
api/dcim/assert_api.py

@@ -0,0 +1,50 @@
+
+from common import config
+from common.util import req_api
+
+
+class AssertApi:
+    def __init__(self):
+        self.headers = None
+
+    def get_assert(self, page_index: int = 10, page_size:int=4000, position_path:str = None, asset_status:list = None,
+                   dns:list = None):
+        params = {}
+        params['pageIndex'] = page_index
+        params['pageSize'] = page_size
+        if position_path is not None:
+            params['positionPath'] = position_path
+        if asset_status is not None:
+            params['assetStatus'] = asset_status
+        if dns is not None:
+            params['dns'] = dns
+        return req_api(f'{config.DCIM_BASE_URL}/rest/openapi/neteco/nbi/v2/assert', headers=self.headers,
+                       params=params)
+
+
+    def get_capacity(self, page_index: int = 10, page_size:int=4000, dns:list = None):
+        params = {}
+        params['pageIndex'] = page_index
+        params['pageSize'] = page_size
+        if dns is not None:
+            params['dns'] = dns
+        return req_api(f'{config.DCIM_BASE_URL}/rest/openapi/neteco/capacity', headers=self.headers,
+                       params=params)
+
+    def get_customer_and_rack(self, page_index: int = 10, page_size:int=4000, customer_ids:list = None):
+        params = {}
+        params['pageIndex'] = page_index
+        params['pageSize'] = page_size
+        if customer_ids is not None:
+            params['customerIds'] = customer_ids
+        return req_api(f'{config.DCIM_BASE_URL}/rest/openapi/neteco/nbi/asset/relation/customerAndRack',
+                       headers=self.headers, params=params)
+
+    def get_customer_and_asset(self, page_index: int = 10, page_size:int=4000, customer_names:list = None):
+        params = {}
+        params['pageIndex'] = page_index
+        params['pageSize'] = page_size
+        if customer_names is not None:
+            params['customerNames'] = customer_names
+        return req_api(f'{config.DCIM_BASE_URL}/rest/openapi/neteco/nbi/v2/asset/relation/customerAndAsset',
+                       headers=self.headers, params=params)

+ 11 - 0
api/dcim/login_api.py

@@ -0,0 +1,11 @@
+from common import config
+from common.util import req_api
+
+
+class LoginApi:
+    def __init__(self):
+        pass
+
+    def login(self):
+        # return req_api(f'{config.DCIM_BASE_URL}/rest/openapi/sm/session', data={'userid': config.USERNAME, 'value': config.PASSWORD})
+        return {'data': "okokok"}

+ 80 - 0
api/dcim_api.py

@@ -0,0 +1,80 @@
+from api.dcim.alarm_api import AlarmApi
+from api.dcim.login_api import LoginApi
+from api.dcim.assert_api import AssertApi
+from api.riil.utils import save_json
+
+
+class DcimApi(
+    LoginApi,
+    AlarmApi,
+    AssertApi
+):
+    def __init__(self):
+        super().__init__()
+        self.headers = self.login().get('data')
+
+    def save_alarm_current(self):
+        page_index = 1
+        alarm_list = []
+        while True:
+            data = self.get_alarm_current(page_index=page_index)
+            alarm_list.extend(data.get('data', []))
+            if page_index >= data.get('totalPage'):
+                break
+            page_index += 1
+        save_json(alarm_list, "result/dcim/alarm_current.json")
+
+    def save_alarm_history(self):
+        page_index = 1
+        alarm_list = []
+        while True:
+            data = self.get_alarm_current(page_index=page_index, is_history=True)
+            alarm_list.extend(data.get('data', []))
+            if page_index >= data.get('totalPage'):
+                break
+            page_index += 1
+        save_json(alarm_list, "result/dcim/alarm_current.json")
+
+    def save_capacity(self):
+        page_index = 1
+        capacity_list = []
+        while True:
+            data = self.get_capacity(page_index=page_index)
+            capacity_list.extend(data.get('data', []))
+            if page_index >= data.get('totalPage'):
+                break
+            page_index += 1
+        save_json(capacity_list, "result/dcim/capacity.json")
+
+    def save_assert(self):
+        page_index = 1
+        assert_list = []
+        while True:
+            data = self.get_assert(page_index=page_index)
+            assert_list.extend(data.get('data', []))
+            if page_index >= data.get('totalPage'):
+                break
+            page_index += 1
+        save_json(assert_list, "result/dcim/assert.json")
+
+    def save_customer_and_rack(self):
+        page_index = 1
+        customer_and_rack_list = []
+        while True:
+            data = self.get_customer_and_rack(page_index=page_index)
+            customer_and_rack_list.extend(data.get('data', []))
+            if page_index >= data.get('totalPage'):
+                break
+            page_index += 1
+        save_json(customer_and_rack_list, "result/dcim/customer_and_rack.json")
+
+    def save_customer_and_asset(self):
+        page_index = 1
+        customer_and_asset_list = []
+        while True:
+            data = self.get_customer_and_asset(page_index=page_index)
+            customer_and_asset_list.extend(data.get('data', []))
+            if page_index >= data.get('totalPage'):
+                break
+            page_index += 1
+        save_json(customer_and_asset_list, "result/dcim/customer_and_asset.json")

+ 2 - 1
util/event_client.py → api/riil/event_client.py

@@ -1,4 +1,5 @@
-from common.utils import call_api, save_json
+from api.riil.utils import call_api
+
 
 class EventClientApi:
     def accept_event(self, event_id):

+ 1 - 4
util/ipam.py → api/riil/ipam.py

@@ -1,7 +1,4 @@
-from common.setting import Config
-import requests
-
-from common.utils import call_api
+from api.riil.utils import call_api
 
 class IpamApi:
     def apply_ip(self, segmentId, _openCLIENT="RIIL", mac=None, user=None, devIp=None, ifIdx=None, department=None):

+ 0 - 3
util/login.py → api/riil/login.py

@@ -1,10 +1,7 @@
 import requests
 from typing import Dict, Any
 
-from sympy.polys.polyconfig import configure
-
 from common import config
-from common.utils import call_api
 
 
 class LoginApi:

+ 1 - 1
util/res.py → api/riil/res.py

@@ -1,4 +1,4 @@
-from common.utils import call_api
+from api.riil.utils import call_api
 
 
 class ResApi:

+ 1 - 1
util/res_client.py → api/riil/res_client.py

@@ -1,6 +1,6 @@
 from typing import Any, Dict, List
 
-from common.utils import call_api
+from api.riil.utils import call_api
 
 
 class ResClientApi:

+ 1 - 4
util/room.py → api/riil/room.py

@@ -1,7 +1,4 @@
-from common.setting import Config
-import requests
-
-from common.utils import call_api
+from api.riil.utils import call_api
 
 
 class RoomApi:

+ 1 - 2
common/utils.py → api/riil/utils.py

@@ -2,10 +2,9 @@ import json
 
 import requests
 
-from common.error import NoValidError
 from common.logger import logger
 from common import config
-from util.login import LoginApi
+from api.riil.login import LoginApi
 
 cookies = {}
 

+ 23 - 0
api/riil_api.py

@@ -0,0 +1,23 @@
+from api.riil.event_client import EventClientApi
+from api.riil.ipam import IpamApi
+from api.riil.login import LoginApi
+from api.riil.res import ResApi
+from api.riil.res_client import ResClientApi
+from api.riil.room import RoomApi
+
+
+class RiilApi(
+    LoginApi,
+    EventClientApi,
+    IpamApi,
+    ResClientApi,
+    RoomApi,
+    ResApi
+):
+    pass
+
+
+
+if __name__ == '__main__':
+    api = RiilApi()
+    api.get_all_room()

+ 15 - 0
common/setting.py

@@ -30,4 +30,19 @@ class Config(BaseSettings):
     DB_URL: str = Field(
         description='database url',
         default='postgresql+psycopg2://user:password@localhost/dbname'
+    )
+
+    DCIM_BASE_URL: str = Field(
+        description='DCIM base url',
+        default='https://10.10.10.10:32102'
+    )
+
+    DCIM_API_USERNAME: str = Field(
+        description='DCIM API username',
+        default='TestUser'
+    )
+
+    DCIM_API_PASSWORD: str = Field(
+        description='DCIM API password',
+        default='Test_12345'
     )

+ 28 - 0
common/util.py

@@ -0,0 +1,28 @@
+import requests
+
+from common import config
+from common.logger import logger
+
+
+def req_api(endpoint, method="GET", params=None, data=None, headers=None, cookies=None) -> dict:
+    """
+    通用的API调用方法。
+    """
+    for i in range(3):
+        try:
+            if method.upper() == "GET":
+                response = requests.get(endpoint, params=params, cookies=cookies, verify=False, headers=headers)
+            elif method.upper() == "POST":
+                response = requests.post(endpoint, json=data, params=params, cookies=cookies, verify=False, headers=headers)
+            elif method.upper() == "PUT":
+                response = requests.put(endpoint, json=data, params=params, cookies=cookies, verify=False, headers=headers)
+            else:
+                raise ValueError("Unsupported HTTP method")
+            logger.info(f"Calling API: {endpoint}, Method: {method}, Params: {params}, Data: {data}, ResCode:{response.status_code}, ResData: {response.text}")
+            response.raise_for_status()
+            return response.json()
+        except requests.RequestException as e:
+            print(f"Error calling API {endpoint}: {e}")
+            logger.warning(f"Calling API: {endpoint}, Method: {method}, Params: {params}, Data: {data}, Error:{e}")
+    logger.error(f"Failed to call API 3 times: {endpoint}, Method: {method}, Params: {params}, Data: {data}")
+    raise Exception("Failed to call API 3 times")

+ 5 - 0
dcim_main.py

@@ -0,0 +1,5 @@
+from api.dcim_api import DcimApi
+
+if __name__ == '__main__':
+    api = DcimApi()
+    api.save_alarm_current()

+ 7 - 8
main.py

@@ -1,7 +1,6 @@
 from common.ext_database import init_db
-from common.utils import save_json
-from common.logger import logger
-from util.riil_api import RiilApi
+from api.riil.utils import save_json
+from api.riil_api import RiilApi
 
 
 class Main:
@@ -21,7 +20,7 @@ class Main:
         for i in range(1, 2):
             unaccepted_event_list = self.api.query_event_list("accepted_event_view", pageIndex=i)
             all_accepted_event_list.extend(unaccepted_event_list.get('eventList'))
-        save_json(all_accepted_event_list, "result/event/accepted_event_list.json")
+        save_json(all_accepted_event_list, "result/rill/event/accepted_event_list.json")
 
         # event_list = self.api.get_log_alarm_list()
         # save_json(event_list, "result/event/event_list.json")
@@ -33,7 +32,7 @@ class Main:
         for res_id in res_id_set:
             res = self.api.get_res_instance_by_id(res_id)
             all_res_list.append(res)
-        save_json(all_res_list, "result/res/res.json")
+        save_json(all_res_list, "result/rill/res/res.json")
 
     def get_resources(self):
         # 获取主资源列表
@@ -46,7 +45,7 @@ class Main:
             page_index += 1
             res = res_dict.get('resList', [])
             res_list.extend(res)
-        save_json(res_list, "result/res/res_list.json")
+        save_json(res_list, "result/rill/res/res_list.json")
 
 
     def get_ip_all_segment(self):
@@ -58,14 +57,14 @@ class Main:
 
     def get_room(self):
         res = self.api.get_all_room()
-        save_json(res, "result/room/room_list.json")
+        save_json(res, "result/rill/room/room_list.json")
         event_from_room = []
         for room in res.get("roomVOList", []):
             room_id = room.get("id")
             res = self.api.get_element_by_room_id(room_id)
             event_from_room.extend(res.get('elementPojoList', []))
 
-        save_json(event_from_room, "result/room/event_from_room.json")
+        save_json(event_from_room, "result/rill/room/event_from_room.json")
 
 
     def run(self):

+ 0 - 23
util/riil_api.py

@@ -1,23 +0,0 @@
-from util.event_client import EventClientApi
-from util.ipam import IpamApi
-from util.login import LoginApi
-from util.res import ResApi
-from util.res_client import ResClientApi
-from util.room import RoomApi
-
-
-class RiilApi(
-    LoginApi,
-    EventClientApi,
-    IpamApi,
-    ResClientApi,
-    RoomApi,
-    ResApi
-):
-    pass
-
-
-
-if __name__ == '__main__':
-    api = RiilApi()
-    api.get_all_room()