Example #1
0
async def metrics():
    service = get_service()
    labels = {"service": service.name, "node": config.node}
    if service.pooled:
        labels["pool"] = config.pool
    if hasattr(service, "slot_number"):
        labels["slot"] = service.slot_number
    out = []
    mdata = service.get_mon_data()
    for key in mdata:
        if key == "pid":
            continue
        metric_name = key
        local_labels = {}
        if isinstance(mdata[key], (bool, str)):
            continue
        if isinstance(key, tuple):
            metric_name = key[0]
            for k in key[1:]:
                local_labels.update({k[0]: k[1]})
        local_labels.update(labels)
        cleared_name = str(metric_name).translate(TR).lower()
        value = mdata[key]
        if value is None:
            continue
        if hasattr(value, "iter_prom_metrics"):
            out += list(value.iter_prom_metrics(cleared_name, local_labels))
        else:
            out_labels = ",".join(['%s="%s"' % (i.lower(), local_labels[i]) for i in local_labels])
            out += ["# TYPE %s untyped" % cleared_name]
            out += ["%s{%s} %s" % (cleared_name, out_labels, value)]
    return PlainTextResponse(
        content="\n".join(out) + "\n", headers={"Content-Type": "text/plain; version=0.0.4"}
    )
Example #2
0
File: mx.py Project: nbashev/noc
def send_message(data: Any,
                 message_type: str,
                 headers: Optional[Dict[str, bytes]],
                 sharding_key: int = 0):
    """
    Build message and schedule to send to mx service

    :param data:
    :param message_type:
    :param headers:
    :param sharding_key:
    :return:
    """
    msg_headers = {
        MX_MESSAGE_TYPE: smart_bytes(message_type),
        MX_SHARDING_KEY: smart_bytes(sharding_key),
    }
    if headers:
        msg_headers.update(headers)
    svc = get_service()
    n_partitions = get_mx_partitions()
    svc.publish(
        value=orjson.dumps(data),
        stream=MX_STREAM,
        partition=sharding_key % n_partitions,
        headers=msg_headers,
    )
Example #3
0
 def handle(self, *args, **options):
     from noc.lib.app.site import site
     site.service = get_service()
     try:
         Permission.sync()
     except ValueError as e:
         self.die(str(e))
Example #4
0
    def handle(self, services=None, *args, **options):
        service = get_service()

        out = [["Service", "ID", "Address"]]
        for sn in services:
            service.dcs.resolve_sync(sn)
            if sn in service.dcs.resolvers:
                for svc_id, address in service.dcs.resolvers[
                        sn].services.items():
                    out += [[sn, svc_id, address]]
        self.stdout.write(format_table([0, 0, 0, 0, 0], out) + "\n")
Example #5
0
    def handle(self, *args, **options):
        from noc.lib.app.site import site

        connect()
        # Install service stub
        site.service = get_service()
        # Synchronize permissions
        try:
            Permission.sync()
        except ValueError as e:
            self.die(str(e))
Example #6
0
async def mon():
    mdata = get_service().get_mon_data()
    response = {}
    for key in mdata:
        if isinstance(key, tuple):
            metric_name = key[0]
            for k in key[1:]:
                metric_name += "_%s" % "_".join(str(i) for i in k)
        else:
            metric_name = key.lower()
        cleared_name = str(metric_name).translate(TR)
        response[cleared_name] = mdata[key]
    return response
Example #7
0
    def _set_timer(self, item: Session, timer: Optional[int] = None):
        def _run_timer(session: str, t: Optional[int]):
            # Running on main service's event loop
            with self._lock:
                i = self._sessions.get(session)
                if not i:
                    return
                if i.timer_task:
                    i.timer_task.cancel()
                if t:
                    i.timer_task = asyncio.create_task(
                        self._timer_task(session, t))

        loop = get_service().get_event_loop()
        if not loop:
            raise RuntimeError("Event Loop is not running")
        if item.timer_task is not None or timer:
            loop.call_soon_threadsafe(_run_timer, item.session, timer)
Example #8
0
async def health(service: Optional[str] = None):
    svc = get_service()
    if service and not svc.is_valid_health_check(service):
        return PlainTextResponse(content="Invalid service id", status_code=400)
    status, message = svc.get_health_status()
    return PlainTextResponse(content=message, status_code=status)
Example #9
0
def test_permissions():
    site.service = get_service()
    Permission.sync()
    assert Permission.objects.count() > 0