Esempio n. 1
0
 def callback(self, msg):
     '''
     :param msg:
     :return:
     '''
     # TODO  识别访问src ip是否为外网地址, 若为外网地址, 则统一归属为netmapcloud
     try:
         access_data = {
             "uuid": msg.get("id"),
             "src": msg.get("src"),
             "dest": msg.get("dest"),
             "port": msg.get("port")
         }
         self.mongoClient.insert(access_data)
         ip_data = IpaddressApi().get(primiry_id=msg.get("src"))
         if ip_data:
             HostGraphApi().create_relation(
                 primary_key1=msg.get("id"),
                 primary_key2=ip_data.get("host_id"),
                 re_type="access",
                 port=msg.get("port"),
                 access="%s_%s" % (msg.get("src"), msg.get("dest")))
     except:
         logger.info(traceback.format_exc())
         logger.info("Access Drawer failed: %s" % to_str(msg))
Esempio n. 2
0
    def on_patch(self, req, resp, **kwargs):
        '''
        Handles patch requests
        :param req:
        :param resp:
        :param kwargs:
        :return: 返回json
        '''

        self.url = req.path
        self._validate_method(req)
        self._validate_header(req)
        data = self._fetch_data(req)
        self.trace_req_log(req, data)
        result = {}
        try:
            self._before_update(req, data=data, **kwargs)
            num, update_data = self.update(req=req,
                                           data=data,
                                           resp=resp,
                                           **kwargs)
            if update_data:
                result = {"num": num, "id": update_data}
                resp.status = falcon.HTTP_200
            else:
                resp.status = falcon.HTTP_404
        except (ValueError, TypeError, IndexError, UnicodeError) as e:
            logger.info(traceback.format_exc())
            resp.status = falcon.HTTP_400
            result = {
                "title": e.__class__.__name__,
                "description": e.args[0],
                "code": 400
            }
        except (ResourceNotFound) as e:
            resp.status = falcon.HTTP_404
        except (MethodNotAllowed) as e:
            logger.info(traceback.format_exc())
            resp.status = falcon.HTTP_405
            result = {
                "title": "method error",
                "description": "method not allowed",
                "code": 405
            }
        except Exception as e:
            logger.info(traceback.format_exc())
            resp.status = falcon.HTTP_500
            result = {
                "title": "service error",
                "description": "服务器异常",
                "code": 500
            }
        finally:
            resp.body = to_str(result)
            resp.set_headers(header)
            resp.set_header("ReqId", self.req_id)
            self.trace_resp_log(req, result=result, resp=resp)
Esempio n. 3
0
    def valitdae_host(self, uuid):
        cache_data = Redis.get(uuid)
        if cache_data:
            if cache_data == "-":
                raise ResourceNotFound("主机记录不存在")
            return to_json(cache_data)

        _host = self.get(primiry_id=uuid)
        if not _host:
            Redis.set(uuid, "-")
            raise ResourceNotFound("主机记录不存在")
        Redis.set(uuid, to_str(_host))
        return _host
Esempio n. 4
0
    def create(self, req, data, resp, **kwargs):
        if not data.get("id"):
            raise ValueError("主机注册缺少UUID")
        hostApi = HostApi()
        uuid = data["id"]
        hostRegisterData = hostApi.get(primiry_id=uuid)
        if hostRegisterData:
            raise ValueError(
                "UUID:%s 已注册, 注册信息 - HOSTNAME %s - IP: " %
                (uuid, hostRegisterData["hostname"]),
                hostRegisterData["ipaddress"])

        # 一台主机可能拥有多个ip, 注册主机以请求IP进行注册(默认情况下, 该ip应该为默认出口ip)
        data["ipaddress"] = getRequestIpaddress(req)
        self.on_ipaddress_create(uuid, data)
        self.on_graph_create(uuid, data)
        count, cid = hostApi.insert(data)
        Redis.set(uuid, to_str(data=data))
        return count.cid
Esempio n. 5
0
 def __format_msg(self, msg):
     if isinstance(msg, (dict, list)):
         msg = to_str(msg)
     return msg
Esempio n. 6
0
 def trace_resp_log(self, req, result, resp, **kwargs):
     status = resp.status or 000
     msg = "[ %s ][URL:%s] - [METHOD: %s] [%s] - [RESULT: %s]" % (
         self.req_id, req.path, req.method.lower(), status,
         to_str(result)[:LOG_MSG_MAX_LEN])
     logger.info(msg)
Esempio n. 7
0
 def trace_req_log(self, req, data, **kwargs):
     self.req_id = "req-%s" % (allocate_uuid())
     msg = "[ %s ][URL:%s] - [METHOD: %s] [000] - [DATA: %s]" % (
         self.req_id, req.path, req.method.lower(),
         to_str(data)[:LOG_MSG_MAX_LEN])
     logger.info(msg)
Esempio n. 8
0
    def on_get(self, req, resp, **kwargs):
        '''
        Handles get requests
        :param req:
        :param resp:
        :param kwargs:
        :return: 返回json
        '''
        self.url = req.path
        self._validate_method(req)
        self._validate_header(req)
        data = self._fetch_data(req)
        self.trace_req_log(req, data)
        result = {}
        try:
            if kwargs:
                self._before_detail(req, data, **kwargs)
                result = self.detail(req, data, resp, **kwargs)
            else:
                order_by = data.pop("order_by", None)
                if order_by:
                    if order_by.endswith("__-1"):
                        order_by = "-%s" % order_by.strip("__-1")
                    if order_by.endswith("__1"):
                        order_by = order_by.strip("__1")
                limit = data.pop("limit", None)
                offset = data.pop("offset", None)
                self._before_list(req, data=data)
                count, _data = self.list(req,
                                         data,
                                         resp,
                                         offset=offset,
                                         limit=limit,
                                         order_by=order_by)
                result = {"count": count, "data": _data}

            if result:
                resp.status = falcon.HTTP_200
            else:
                resp.status = falcon.HTTP_404
        except (ValueError, TypeError, IndexError, UnicodeError) as e:
            logger.info(traceback.format_exc())
            resp.status = falcon.HTTP_400
            result = {
                "title": e.__class__.__name__,
                "description": e.args[0],
                "code": 400
            }
        except (ResourceNotFound) as e:
            resp.status = falcon.HTTP_404
        except (MethodNotAllowed) as e:
            logger.info(traceback.format_exc())
            resp.status = falcon.HTTP_405
            result = {
                "title": "method error",
                "description": "method not allowed",
                "code": 405
            }
        except Exception as e:
            logger.info(traceback.format_exc())
            resp.status = falcon.HTTP_500
            result = {
                "title": "service error",
                "description": "服务器异常",
                "code": 500
            }
        finally:
            resp.body = to_str(result)
            resp.set_headers(header)
            resp.set_header("ReqId", self.req_id)
            self.trace_resp_log(req, result=result, resp=resp)