예제 #1
0
 def inner_document(qs):
     if value and not is_objectid(value):
         raise HTTPException(
             status_code=HTTPStatus.UNPROCESSABLE_ENTITY,
             detail=f"'{value}' is not a valid ObjectId",
         )
     vv = self.model.get_by_id(value) if value else None
     if value and not vv:
         raise HTTPException(
             status_code=HTTPStatus.NOT_FOUND,
             detail=f"NotFond {str(self.model)}: {value}")
     return qs.filter(**{self.name: vv})
예제 #2
0
 def api_add_group(self, request, type, name, container=None, serial=None):
     if is_objectid(container):
         c = Object.get_by_id(container)
         if not c:
             return self.response_not_found()
         c = c.id
     elif container:
         return self.response_bad_request()
     else:
         c = None
     m = ObjectModel.get_by_id(type)
     if not m:
         return self.response_not_found()
     o = Object(name=name, model=m, container=c)
     if serial and m.get_data("asset", "part_no0"):
         o.set_data("asset", "serial", serial)
     o.save()
     o.log("Created", user=request.user.username, system="WEB", op="CREATE")
     return str(o.id)
예제 #3
0
 def api_test(self, request):
     q = self.deserialize(request.body)
     errors = []
     patterns = []
     result = False
     # Get data
     data = {}
     vars = {}
     required_vars = set()
     r_patterns = []
     event_class = None
     subject = None
     body = None
     if "data" in q:
         if is_objectid(q["data"]):
             event = get_event(q["data"])
             if event:
                 data = event.raw_vars.copy()
                 data["profile"] = event.managed_object.profile.name
                 data["source"] = event.source
             else:
                 errors += ["Event not found: %s" % q["data"]]
         else:
             # Decode json
             try:
                 e = self.deserialize(q["data"])
             except Exception:
                 errors += ["Cannot decode JSON"]
                 e = None
             if isinstance(e, list):
                 e = e[0]
             if not isinstance(e, dict) or "raw_vars" not in e:
                 errors += ["Invalid JSON data"]
             else:
                 data = e["raw_vars"]
                 if "profile" in e:
                     data["profile"] = e["profile"]
                 if "source" in e:
                     data["source"] = e["source"]
         if data.get("source") == "SNMP Trap":
             # Resolve MIBs
             data.update(MIB.resolve_vars(data))
     # Check event class
     if "event_class" in q:
         event_class = self.get_object_or_404(EventClass,
                                              id=q["event_class"])
         for v in event_class.vars:
             if v.required:
                 required_vars.add(v.name)
                 vars[v.name] = "MISSED!"
     # Check patterns
     if "patterns" in q:
         for p in q["patterns"]:
             if "key_re" in p and "value_re" in p:
                 k = None
                 v = None
                 try:
                     k = re.compile(p["key_re"])
                 except re.error as why:
                     errors += [
                         "Invalid key regular expression <<<%s>>>: %s" %
                         (p["key_re"], why)
                     ]
                 try:
                     v = re.compile(p["value_re"])
                 except re.error as why:
                     errors += [
                         "Invalid value regular expression <<<%s>>>: %s" %
                         (p["value_re"], why)
                     ]
                 if k and v:
                     patterns += [(k, v)]
     # Try to match rule
     if patterns and not errors:
         s_patterns = []
         i_patterns = []
         for pkey, pvalue in patterns:
             matched = False
             for k in data:
                 k_match = pkey.search(k)
                 if k_match:
                     v_match = pvalue.search(data[k])
                     if v_match:
                         # Line match
                         # Update vars
                         v = {}
                         v.update(k_match.groupdict())
                         v.update(v_match.groupdict())
                         vars.update(v)
                         # Save patterns
                         s_patterns += [{
                             "status":
                             True,
                             "key":
                             k,
                             "value":
                             data[k],
                             "key_re":
                             pkey.pattern,
                             "value_re":
                             pvalue.pattern,
                             "vars": [{
                                 "key": k,
                                 "value": v[k]
                             } for k in v],
                         }]
                     else:
                         i_patterns += [{
                             "status": False,
                             "key": k,
                             "value": data[k],
                             "key_re": pkey.pattern,
                             "value_re": pvalue.pattern,
                             "vars": {},
                         }]
                     matched = True
                     break
             if not matched:
                 i_patterns += [{
                     "status": False,
                     "key": None,
                     "value": None,
                     "key_re": pkey.pattern,
                     "value_re": pvalue.pattern,
                     "vars": {},
                 }]
         if s_patterns and not i_patterns:
             result = True
         r_patterns = s_patterns + i_patterns
     # Calculate rule variables
     if "vars" in q and q["vars"]:
         for v in q["vars"]:
             if v["value"].startswith("="):
                 # Evaluate
                 try:
                     vars[v["name"]] = eval(v["value"][1:], {}, vars)
                 except Exception as why:
                     errors += [
                         "Error when evaluating '%s': %s" % (v["name"], why)
                     ]
             else:
                 vars[v["name"]] = v["value"]
     # Check required variables
     for rvars in required_vars:
         if rvars not in vars:
             errors += ["Missed required variable: %s" % rvars]
     # Fill event class template
     if event_class:
         # lang = "en"
         ctx = Context(vars)
         subject = Template(event_class.subject_template).render(ctx)
         body = Template(event_class.body_template).render(ctx)
     # Check expression
     r = {"result": result}
     if errors:
         r["errors"] = errors
     if vars:
         r["vars"] = [{"key": k, "value": vars[k]} for k in vars]
     if r_patterns:
         r["patterns"] = r_patterns
     if subject:
         r["subject"] = subject
     if body:
         r["body"] = body
     return r
예제 #4
0
    def api_node(self, request):
        children = []
        if request.GET and "node" in request.GET:
            container = request.GET["node"]
            if is_objectid(container):
                container = Object.get_by_id(container)
                if not container:
                    return self.response_not_found()
                children = [
                    (o.name, o)
                    for o in Object.objects.filter(container=container.id)
                ]
                # Collect inner connections
                children += [
                    (name, o)
                    for name, o, _ in container.get_inner_connections()
                ]
            elif container == "root":
                cmodels = [
                    d["_id"] for d in ObjectModel._get_collection().find(
                        {"data.container.container": True}, {"_id": 1})
                ]
                children = [(o.name, o)
                            for o in Object.objects.filter(__raw__={
                                "container": None,
                                "model": {
                                    "$in": cmodels
                                }
                            })]

            else:
                return self.response_bad_request()
        r = []
        # Build node interface
        for name, o in children:
            m_plugins = o.model.plugins or []
            disabled_plugins = set(p[1:] for p in m_plugins
                                   if p.startswith("-"))
            n = {
                "id": str(o.id),
                "name": name,
                "plugins": [],
                "can_add": bool(o.get_data("container", "container")),
                "can_delete": str(o.model.uuid) not in self.UNDELETABLE,
            }
            if o.get_data("container",
                          "container") or o.has_inner_connections():
                # n["expanded"] = Object.objects.filter(container=o.id).count() == 1
                n["expanded"] = False
            else:
                n["leaf"] = True
            if o.get_data("rack", "units"):
                n["plugins"] += [self.get_plugin_data("rack")]
            if o.model.connections:
                n["plugins"] += [self.get_plugin_data("inventory")]
            if o.get_data("geopoint", "layer"):
                n["plugins"] += [self.get_plugin_data("map")]
            if o.get_data("management", "managed_object"):
                n["plugins"] += [self.get_plugin_data("managedobject")]
            if o.get_data("contacts", "has_contacts"):
                n["plugins"] += [self.get_plugin_data("contacts")]
            # Append model's plugins
            for p in m_plugins:
                if not p.startswith("-"):
                    n["plugins"] += [self.get_plugin_data(p)]
            n["plugins"] += [
                self.get_plugin_data("data"),
                self.get_plugin_data("comment"),
                self.get_plugin_data("file"),
                self.get_plugin_data("log"),
            ]
            # Process disabled plugins
            n["plugins"] = [
                p for p in n["plugins"] if p["name"] not in disabled_plugins
            ]
            r += [n]
        return r
예제 #5
0
def test_is_objectid(raw, expected):
    assert is_objectid(raw) is expected
예제 #6
0
 def get_Q(self, request, query):
     if is_objectid(query):
         q = Q(id=query)
     else:
         q = super(ServiceApplication, self).get_Q(request, query)
     return q
예제 #7
0
 def get_Q(self, request, query):
     if is_objectid(query):
         q = Q(id=query)
     else:
         q = super().get_Q(request, query)
     return q