junos-exporter 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- junos_exporter/__init__.py +0 -0
- junos_exporter/__main__.py +4 -0
- junos_exporter/cli.py +64 -0
- junos_exporter/config.py +125 -0
- junos_exporter/connector.py +157 -0
- junos_exporter/exporter.py +115 -0
- junos_exporter-0.0.1.dist-info/METADATA +191 -0
- junos_exporter-0.0.1.dist-info/RECORD +11 -0
- junos_exporter-0.0.1.dist-info/WHEEL +4 -0
- junos_exporter-0.0.1.dist-info/entry_points.txt +2 -0
- junos_exporter-0.0.1.dist-info/licenses/LICENSE +21 -0
|
File without changes
|
junos_exporter/cli.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
from collections.abc import AsyncGenerator
|
|
5
|
+
from contextlib import asynccontextmanager
|
|
6
|
+
from typing import Generator
|
|
7
|
+
|
|
8
|
+
import uvicorn
|
|
9
|
+
from fastapi import Depends, FastAPI
|
|
10
|
+
from fastapi.responses import PlainTextResponse
|
|
11
|
+
from pydantic import ValidationError
|
|
12
|
+
from starlette.exceptions import HTTPException as StarletteHTTPException
|
|
13
|
+
|
|
14
|
+
from .config import Config
|
|
15
|
+
from .connector import ConnecterBuilder, Connector
|
|
16
|
+
from .exporter import Exporter, ExporterBuilder
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@asynccontextmanager
|
|
20
|
+
async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
|
|
21
|
+
config = Config.get()
|
|
22
|
+
app.exporter = ExporterBuilder(config) # type: ignore
|
|
23
|
+
app.connector = ConnecterBuilder(config) # type: ignore
|
|
24
|
+
yield
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
app = FastAPI(default_response_class=PlainTextResponse, lifespan=lifespan)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@app.exception_handler(StarletteHTTPException)
|
|
31
|
+
def http_exception_handler(request, exc) -> PlainTextResponse:
|
|
32
|
+
return PlainTextResponse(content=str(exc.detail), status_code=exc.status_code)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_connector(target: str, module: str) -> Generator[Connector, None, None]:
|
|
36
|
+
with app.connector.build(target, module) as connector: # type: ignore
|
|
37
|
+
yield connector
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@app.get("/metrics")
|
|
41
|
+
def collect(
|
|
42
|
+
target: str, module: str, connector: Connector = Depends(get_connector)
|
|
43
|
+
) -> str:
|
|
44
|
+
exporter: Exporter = app.exporter.build(module) # type: ignore
|
|
45
|
+
return exporter.collect(connector)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def cli() -> None:
|
|
49
|
+
try:
|
|
50
|
+
parser = argparse.ArgumentParser()
|
|
51
|
+
parser.add_argument(
|
|
52
|
+
"-c",
|
|
53
|
+
"--config",
|
|
54
|
+
type=str,
|
|
55
|
+
default="config.yml",
|
|
56
|
+
help="configuration file path",
|
|
57
|
+
)
|
|
58
|
+
args = parser.parse_args()
|
|
59
|
+
config = Config(args.config)
|
|
60
|
+
uvicorn.run("junos_exporter.cli:app", host="0.0.0.0", port=config.port)
|
|
61
|
+
except FileNotFoundError:
|
|
62
|
+
sys.exit(f"config file({os.path.abspath(args.config)}) is not found")
|
|
63
|
+
except ValidationError as e:
|
|
64
|
+
sys.exit(f"config file({os.path.abspath(args.config)}) is invalid.\n{e}")
|
junos_exporter/config.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from typing import DefaultDict, Literal
|
|
5
|
+
|
|
6
|
+
import yaml
|
|
7
|
+
from pydantic import (
|
|
8
|
+
BaseModel,
|
|
9
|
+
ConfigDict,
|
|
10
|
+
Field,
|
|
11
|
+
ValidationInfo,
|
|
12
|
+
field_validator,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class General(BaseModel):
|
|
17
|
+
port: int = 9326
|
|
18
|
+
prefix: str = "junos"
|
|
19
|
+
optables_dir: str | None = None
|
|
20
|
+
textfsm_dir: str | None = None
|
|
21
|
+
|
|
22
|
+
@field_validator("optables_dir", "textfsm_dir", mode="after")
|
|
23
|
+
@classmethod
|
|
24
|
+
def check_exist_dir(cls, path: str) -> str:
|
|
25
|
+
abs_path = os.path.abspath(path)
|
|
26
|
+
if not os.path.isdir(abs_path):
|
|
27
|
+
raise ValueError(f"directory({abs_path}) does not exist")
|
|
28
|
+
return abs_path
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Module(BaseModel):
|
|
32
|
+
username: str
|
|
33
|
+
password: str
|
|
34
|
+
tables: list[str]
|
|
35
|
+
|
|
36
|
+
@field_validator("tables", mode="before")
|
|
37
|
+
@classmethod
|
|
38
|
+
def check_exist_optables(cls, tables: list[str], info: ValidationInfo) -> list[str]:
|
|
39
|
+
if isinstance(info.context, dict):
|
|
40
|
+
optables = info.context.get("optables", dict())
|
|
41
|
+
for table in tables:
|
|
42
|
+
if table not in optables:
|
|
43
|
+
raise ValueError(f"table({table}) does not contain optables")
|
|
44
|
+
return tables
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class Label(BaseModel):
|
|
48
|
+
model_config = ConfigDict(coerce_numbers_to_str=True)
|
|
49
|
+
|
|
50
|
+
name: str
|
|
51
|
+
value: str
|
|
52
|
+
regex: re.Pattern | None = None
|
|
53
|
+
|
|
54
|
+
@field_validator("regex", mode="before")
|
|
55
|
+
@classmethod
|
|
56
|
+
def to_re_pattern(cls, regex: str) -> re.Pattern:
|
|
57
|
+
if not isinstance(regex, str):
|
|
58
|
+
raise ValueError(f"regex({regex}) is not a str")
|
|
59
|
+
return re.compile(regex)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Metric(BaseModel):
|
|
63
|
+
model_config = ConfigDict(coerce_numbers_to_str=True)
|
|
64
|
+
|
|
65
|
+
name: str
|
|
66
|
+
value: str
|
|
67
|
+
type_: Literal["untyped", "counter", "gauge"] = Field("untyped", alias="type")
|
|
68
|
+
help_: str = Field("", alias="help")
|
|
69
|
+
value_transform: DefaultDict[str, float] | None = None
|
|
70
|
+
|
|
71
|
+
@field_validator("value_transform", mode="before")
|
|
72
|
+
@classmethod
|
|
73
|
+
def to_defaultdict(cls, value_transform: dict) -> dict:
|
|
74
|
+
return defaultdict(lambda: "NaN", value_transform)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class OpTable(BaseModel):
|
|
78
|
+
metrics: list[Metric]
|
|
79
|
+
labels: list[Label]
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Config:
|
|
83
|
+
_instance: "Config | None" = None
|
|
84
|
+
_config_path: str
|
|
85
|
+
|
|
86
|
+
def __new__(cls, config_path: str) -> "Config":
|
|
87
|
+
if cls._instance is None:
|
|
88
|
+
cls._instance = super().__new__(cls)
|
|
89
|
+
cls._config_path = config_path
|
|
90
|
+
return cls._instance
|
|
91
|
+
|
|
92
|
+
def __init__(self, config_path: str) -> None:
|
|
93
|
+
with open(self._config_path, "r") as f:
|
|
94
|
+
config = yaml.safe_load(f)
|
|
95
|
+
|
|
96
|
+
self.general = General(**config["general"])
|
|
97
|
+
self.modules = {
|
|
98
|
+
name: Module.model_validate(
|
|
99
|
+
module, context={"optables": config["optables"]}
|
|
100
|
+
)
|
|
101
|
+
for name, module in config["modules"].items()
|
|
102
|
+
}
|
|
103
|
+
self.optables = {
|
|
104
|
+
name: OpTable(**optable) for name, optable in config["optables"].items()
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
@classmethod
|
|
108
|
+
def get(cls) -> "Config | None":
|
|
109
|
+
return cls._instance
|
|
110
|
+
|
|
111
|
+
@property
|
|
112
|
+
def port(self) -> int:
|
|
113
|
+
return self.general.port
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def prefix(self) -> str:
|
|
117
|
+
return self.general.prefix
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def optables_dir(self) -> str | None:
|
|
121
|
+
return self.general.optables_dir
|
|
122
|
+
|
|
123
|
+
@property
|
|
124
|
+
def textfsm_dir(self) -> str | None:
|
|
125
|
+
return self.general.textfsm_dir
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from glob import glob
|
|
3
|
+
|
|
4
|
+
import yaml
|
|
5
|
+
from fastapi import HTTPException, status
|
|
6
|
+
from jnpr.junos import Device
|
|
7
|
+
from jnpr.junos.exception import ConnectError, RpcError
|
|
8
|
+
from jnpr.junos.factory import loadyaml
|
|
9
|
+
from jnpr.junos.factory.cmdtable import CMDTable
|
|
10
|
+
from jnpr.junos.factory.optable import OpTable
|
|
11
|
+
|
|
12
|
+
# predefined table
|
|
13
|
+
from jnpr.junos.op.arp import ArpTable
|
|
14
|
+
from jnpr.junos.op.bfd import BfdSessionTable
|
|
15
|
+
from jnpr.junos.op.bgp import bgpTable
|
|
16
|
+
from jnpr.junos.op.ccc import CCCTable
|
|
17
|
+
from jnpr.junos.op.ddos import DDOSTable
|
|
18
|
+
from jnpr.junos.op.elsethernetswitchingtable import ElsEthernetSwitchingTable
|
|
19
|
+
from jnpr.junos.op.ethernetswitchingtable import EthernetSwitchingTable
|
|
20
|
+
from jnpr.junos.op.ethport import EthPortTable
|
|
21
|
+
from jnpr.junos.op.fpc import FpcHwTable, FpcInfoTable, FpcMiReHwTable, FpcMiReInfoTable
|
|
22
|
+
from jnpr.junos.op.idpattacks import IDPAttackTable
|
|
23
|
+
from jnpr.junos.op.intopticdiag import PhyPortDiagTable
|
|
24
|
+
from jnpr.junos.op.inventory import ModuleTable
|
|
25
|
+
from jnpr.junos.op.isis import IsisAdjacencyTable
|
|
26
|
+
from jnpr.junos.op.l2circuit import L2CircuitConnectionTable
|
|
27
|
+
from jnpr.junos.op.lacp import LacpPortTable
|
|
28
|
+
from jnpr.junos.op.ldp import LdpNeighborTable
|
|
29
|
+
from jnpr.junos.op.lldp import LLDPNeighborTable
|
|
30
|
+
from jnpr.junos.op.nd import NdTable
|
|
31
|
+
from jnpr.junos.op.ospf import (
|
|
32
|
+
OspfInterfaceTable,
|
|
33
|
+
OSPFIOStatsTable,
|
|
34
|
+
OspfNeighborTable,
|
|
35
|
+
OspfRoutesTable,
|
|
36
|
+
OSPFStatsTable,
|
|
37
|
+
ospfTable,
|
|
38
|
+
)
|
|
39
|
+
from jnpr.junos.op.pfestats import PFEStatsTrafficTable
|
|
40
|
+
from jnpr.junos.op.phyport import PhyPortErrorTable, PhyPortStatsTable, PhyPortTable
|
|
41
|
+
from jnpr.junos.op.ppm import PPMTable
|
|
42
|
+
from jnpr.junos.op.routes import RouteSummaryTable, RouteTable
|
|
43
|
+
from jnpr.junos.op.securityzone import SecurityZoneTable
|
|
44
|
+
|
|
45
|
+
# from jnpr.junos.op.systemstorage import SystemStorageTable
|
|
46
|
+
from jnpr.junos.op.taskmemory import TaskMemoryTable
|
|
47
|
+
from jnpr.junos.op.teddb import TedSummaryTable, TedTable
|
|
48
|
+
from jnpr.junos.op.vlan import VlanTable
|
|
49
|
+
from jnpr.junos.op.xcvr import XcvrTable
|
|
50
|
+
|
|
51
|
+
from .config import Config, Module
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class Connector:
|
|
55
|
+
def __init__(
|
|
56
|
+
self, host: str, username: str, password: str, textfsm_dir: str | None
|
|
57
|
+
) -> None:
|
|
58
|
+
self.device: Device = None
|
|
59
|
+
self.host: str = host
|
|
60
|
+
self.username: str = username
|
|
61
|
+
self.password: str = password
|
|
62
|
+
self.textfsm_dir: str | None = textfsm_dir
|
|
63
|
+
|
|
64
|
+
def __enter__(self) -> "Connector":
|
|
65
|
+
try:
|
|
66
|
+
self.device = Device(
|
|
67
|
+
host=self.host, user=self.username, password=self.password
|
|
68
|
+
).open()
|
|
69
|
+
except ConnectError:
|
|
70
|
+
raise HTTPException(
|
|
71
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
72
|
+
detail=f"Cannot connect to {self.host}",
|
|
73
|
+
)
|
|
74
|
+
return self
|
|
75
|
+
|
|
76
|
+
def __exit__(self, exc_type, exc_value, traceback) -> None:
|
|
77
|
+
self.device.close()
|
|
78
|
+
|
|
79
|
+
def collect(self, name) -> list[dict]:
|
|
80
|
+
if issubclass(globals()[name], CMDTable):
|
|
81
|
+
if self.textfsm_dir is None:
|
|
82
|
+
table = globals()[name](self.device)
|
|
83
|
+
else:
|
|
84
|
+
table = globals()[name](self.device, template_dir=self.textfsm_dir)
|
|
85
|
+
elif issubclass(globals()[name], OpTable):
|
|
86
|
+
table = globals()[name](self.device)
|
|
87
|
+
else:
|
|
88
|
+
raise NotImplementedError
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
table.get()
|
|
92
|
+
except RpcError:
|
|
93
|
+
# cannot get rpc
|
|
94
|
+
return []
|
|
95
|
+
|
|
96
|
+
items = []
|
|
97
|
+
if isinstance(table, CMDTable):
|
|
98
|
+
for t in table:
|
|
99
|
+
key, table = t
|
|
100
|
+
item = {}
|
|
101
|
+
if type(name) is tuple:
|
|
102
|
+
for i, n in enumerate(name):
|
|
103
|
+
item[f"key.{i}"] = n
|
|
104
|
+
item[f"name.{i}"] = n
|
|
105
|
+
else:
|
|
106
|
+
item["key"] = key
|
|
107
|
+
item["name"] = key
|
|
108
|
+
|
|
109
|
+
for k, v in table.items():
|
|
110
|
+
item[k] = v
|
|
111
|
+
items.append(item)
|
|
112
|
+
elif isinstance(table, OpTable):
|
|
113
|
+
for t in table:
|
|
114
|
+
item = {}
|
|
115
|
+
if type(t.key) is tuple:
|
|
116
|
+
for i, n in enumerate(t.key):
|
|
117
|
+
item[f"key.{i}"] = n
|
|
118
|
+
item[f"name.{i}"] = n
|
|
119
|
+
else:
|
|
120
|
+
item["key"] = t.key
|
|
121
|
+
item["name"] = t.key
|
|
122
|
+
|
|
123
|
+
for k, v in t.items():
|
|
124
|
+
item[k] = v
|
|
125
|
+
items.append(item)
|
|
126
|
+
else:
|
|
127
|
+
raise NotImplementedError
|
|
128
|
+
|
|
129
|
+
return items
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
class ConnecterBuilder:
|
|
133
|
+
def __init__(self, config: Config) -> None:
|
|
134
|
+
self.optables_dir: str | None = config.optables_dir
|
|
135
|
+
self.textfsm_dir: str | None = config.textfsm_dir
|
|
136
|
+
self.modules: dict[str, Module] = config.modules
|
|
137
|
+
self._load_optables()
|
|
138
|
+
|
|
139
|
+
def _load_optables(self) -> None:
|
|
140
|
+
if self.optables_dir is None:
|
|
141
|
+
return
|
|
142
|
+
for yml in glob(f"{self.optables_dir}/*"):
|
|
143
|
+
if re.match(r".+\.(yml|yaml)$", yml):
|
|
144
|
+
globals().update(loadyaml(yaml.safe_load(yml)))
|
|
145
|
+
|
|
146
|
+
def build(self, host: str, module_name: str) -> Connector:
|
|
147
|
+
if module_name not in self.modules:
|
|
148
|
+
raise HTTPException(
|
|
149
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
150
|
+
detail=f"module({module_name}) is not defined",
|
|
151
|
+
)
|
|
152
|
+
return Connector(
|
|
153
|
+
host=host,
|
|
154
|
+
username=self.modules[module_name].username,
|
|
155
|
+
password=self.modules[module_name].password,
|
|
156
|
+
textfsm_dir=self.textfsm_dir,
|
|
157
|
+
)
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
from fastapi import HTTPException, status
|
|
2
|
+
|
|
3
|
+
from .config import Config, Label, Metric
|
|
4
|
+
from .connector import Connector
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MetricConverter:
|
|
8
|
+
def __init__(self, metric: Metric, labels: list[Label], prefix: str):
|
|
9
|
+
if metric.type_ == "counter":
|
|
10
|
+
self.name = f"{prefix}_{metric.name}_total"
|
|
11
|
+
else:
|
|
12
|
+
self.name = f"{prefix}_{metric.name}"
|
|
13
|
+
self.value = metric.value
|
|
14
|
+
self.type_ = metric.type_
|
|
15
|
+
self.help_ = metric.help_
|
|
16
|
+
self.value_transform = metric.value_transform
|
|
17
|
+
self.labels = labels
|
|
18
|
+
|
|
19
|
+
def convert(self, items: list[dict]) -> str:
|
|
20
|
+
exposition = []
|
|
21
|
+
exposition.append(f"# HELP {self.name} {self.help_}")
|
|
22
|
+
exposition.append(f"# TYPE {self.name} {self.type_}")
|
|
23
|
+
|
|
24
|
+
for item in items:
|
|
25
|
+
label_exposition = []
|
|
26
|
+
for label in self.labels:
|
|
27
|
+
# label value missing
|
|
28
|
+
if label.value not in item:
|
|
29
|
+
continue
|
|
30
|
+
|
|
31
|
+
# label value is None
|
|
32
|
+
if item[label.value] is None:
|
|
33
|
+
continue
|
|
34
|
+
|
|
35
|
+
# label regex is not defined
|
|
36
|
+
if not label.regex:
|
|
37
|
+
label_exposition.append(f'{label.name}="{item[label.value]}"')
|
|
38
|
+
continue
|
|
39
|
+
|
|
40
|
+
match = label.regex.match(item[label.value])
|
|
41
|
+
# label regex is not hitting
|
|
42
|
+
if match is None:
|
|
43
|
+
continue
|
|
44
|
+
# label regex is hitting
|
|
45
|
+
else:
|
|
46
|
+
label_exposition.append(f'{label.name}="{match.group()}"')
|
|
47
|
+
|
|
48
|
+
if self.value not in item:
|
|
49
|
+
try:
|
|
50
|
+
# static value
|
|
51
|
+
exposition.append(
|
|
52
|
+
f"{self.name}{{{','.join(label_exposition)}}} {float(self.value)}"
|
|
53
|
+
)
|
|
54
|
+
except ValueError:
|
|
55
|
+
# value is not type change to float
|
|
56
|
+
exposition.append(
|
|
57
|
+
f"{self.name}{{{','.join(label_exposition)}}} NaN"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
elif self.value_transform:
|
|
61
|
+
exposition.append(
|
|
62
|
+
f"{self.name}{{{','.join(label_exposition)}}} {self.value_transform[item[self.value]]}"
|
|
63
|
+
)
|
|
64
|
+
else:
|
|
65
|
+
try:
|
|
66
|
+
exposition.append(
|
|
67
|
+
f"{self.name}{{{','.join(label_exposition)}}} {float(item[self.value])}"
|
|
68
|
+
)
|
|
69
|
+
except ValueError:
|
|
70
|
+
# value is not type change to float
|
|
71
|
+
exposition.append(
|
|
72
|
+
f"{self.name}{{{','.join(label_exposition)}}} NaN"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
return "\n".join(exposition) + "\n"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Exporter:
|
|
79
|
+
def __init__(self, converter: dict[str, list[MetricConverter]]) -> None:
|
|
80
|
+
self.converter = converter
|
|
81
|
+
|
|
82
|
+
def collect(self, connector: Connector) -> str:
|
|
83
|
+
exposition: list[str] = []
|
|
84
|
+
for name, metrics in self.converter.items():
|
|
85
|
+
exposition.append(
|
|
86
|
+
"\n".join(
|
|
87
|
+
[metric.convert(connector.collect(name)) for metric in metrics]
|
|
88
|
+
)
|
|
89
|
+
)
|
|
90
|
+
return "\n".join(exposition)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ExporterBuilder:
|
|
94
|
+
def __init__(self, config: Config) -> None:
|
|
95
|
+
self.converters = {}
|
|
96
|
+
for name, module in config.modules.items():
|
|
97
|
+
converter = {}
|
|
98
|
+
for table in module.tables:
|
|
99
|
+
converter[table] = [
|
|
100
|
+
MetricConverter(
|
|
101
|
+
metric,
|
|
102
|
+
labels=config.optables[table].labels,
|
|
103
|
+
prefix=config.prefix,
|
|
104
|
+
)
|
|
105
|
+
for metric in config.optables[table].metrics
|
|
106
|
+
]
|
|
107
|
+
self.converters[name] = converter
|
|
108
|
+
|
|
109
|
+
def build(self, module_name: str) -> Exporter:
|
|
110
|
+
if module_name not in self.converters:
|
|
111
|
+
raise HTTPException(
|
|
112
|
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
|
113
|
+
detail=f"module({module_name}) is not defined",
|
|
114
|
+
)
|
|
115
|
+
return Exporter(self.converters[module_name])
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: junos-exporter
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Prometheus Exporter for Junos using PyEZ Tables and Views
|
|
5
|
+
Project-URL: Repository, https://github.com/minefuto/junos-exporter.git
|
|
6
|
+
Author-email: minefuto <minefuto@gmail.com>
|
|
7
|
+
License: MIT License
|
|
8
|
+
|
|
9
|
+
Copyright (c) 2025 minefuto
|
|
10
|
+
|
|
11
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
12
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
13
|
+
in the Software without restriction, including without limitation the rights
|
|
14
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
15
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
16
|
+
furnished to do so, subject to the following conditions:
|
|
17
|
+
|
|
18
|
+
The above copyright notice and this permission notice shall be included in all
|
|
19
|
+
copies or substantial portions of the Software.
|
|
20
|
+
|
|
21
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
22
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
23
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
24
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
25
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
26
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
27
|
+
SOFTWARE.
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Requires-Python: <3.13,>=3.10
|
|
30
|
+
Requires-Dist: fastapi>=0.115.8
|
|
31
|
+
Requires-Dist: junos-eznc>=2.7.2
|
|
32
|
+
Requires-Dist: ntc-templates>=7.7.0
|
|
33
|
+
Requires-Dist: pyyaml>=6.0.2
|
|
34
|
+
Requires-Dist: uvicorn>=0.34.0
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# junos-exporter
|
|
38
|
+
|
|
39
|
+
## Overview
|
|
40
|
+
This is a Prometheus Exporter for Junos using PyEZ([Juniper/py-junos-eznc](https://github.com/Juniper/py-junos-eznc)) Tables and Views.
|
|
41
|
+
PyEZ can extract information from Junos operational command output and map it to a Python data structure via yaml.
|
|
42
|
+
`junos-exporter` converts the information provided by PyEZ into the Prometheus metrics format via yaml.
|
|
43
|
+
So, this exporter's metrics can be flexibly configured by simply editing yaml.
|
|
44
|
+
|
|
45
|
+
## Usage
|
|
46
|
+
1. Clone the repository:
|
|
47
|
+
```bash
|
|
48
|
+
git clone https://github.com/minefuto/junos-exporter.git
|
|
49
|
+
cd junos-exporter
|
|
50
|
+
```
|
|
51
|
+
2. Configure the exporter by editing the `config.yml`
|
|
52
|
+
3. Run the exporter:
|
|
53
|
+
```bash
|
|
54
|
+
uv run -m junos_exporter
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Configuration
|
|
58
|
+
Please see the `config.yml` for configuration example.
|
|
59
|
+
|
|
60
|
+
#### Create Exporter Config
|
|
61
|
+
```yaml
|
|
62
|
+
general:
|
|
63
|
+
port: 9326 # exporter's listen port
|
|
64
|
+
prefix: junos # prefix of the metrics
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
#### Create PyEZ Operational Tables
|
|
68
|
+
- [Parsing Structured Output](https://www.juniper.net/documentation/us/en/software/junos-pyez/junos-pyez-developer/topics/task/junos-pyez-tables-op-defining.html)
|
|
69
|
+
- [parsing Unstructured Output](https://www.juniper.net/documentation/us/en/software/junos-pyez/junos-pyez-developer/topics/topic-map/junos-pyez-tables-op-unstructured-output-defining.html)
|
|
70
|
+
- [Using TextFSM Template](https://www.juniper.net/documentation/us/en/software/junos-pyez/junos-pyez-developer/topics/concept/junos-pyez-tables-op-using-textfsm-templates.html)
|
|
71
|
+
|
|
72
|
+
Please store the following configured(config.yml) directory.
|
|
73
|
+
```yaml
|
|
74
|
+
general:
|
|
75
|
+
optables_dir: ./op/ # store the structured & unstructured tables and views configuration file
|
|
76
|
+
textfsm_dir: ./textfsm/ # store the textfsm template file
|
|
77
|
+
```
|
|
78
|
+
If using the following predefined operational table, you can skip this step.
|
|
79
|
+
- [Document](https://www.juniper.net/documentation/us/en/software/junos-pyez/junos-pyez-developer/topics/concept/junos-pyez-tables-op-predefined.html)
|
|
80
|
+
- [Source Code](https://github.com/Juniper/py-junos-eznc/tree/master/lib/jnpr/junos/op)
|
|
81
|
+
|
|
82
|
+
#### Create Convert Rule
|
|
83
|
+
```yaml
|
|
84
|
+
optables:
|
|
85
|
+
EthPortTable: # pyez table name
|
|
86
|
+
metrics:
|
|
87
|
+
- name: interface_link_status # metrics name
|
|
88
|
+
value: oper # metrics value
|
|
89
|
+
type: gauge # metrics type(gauge or count or untyped)
|
|
90
|
+
help: physical interface link status(up:2, down:1) # metrics help
|
|
91
|
+
value_transform: #(optional) if metrics value is str, can be transformed to float
|
|
92
|
+
up: 2
|
|
93
|
+
down: 1
|
|
94
|
+
labels:
|
|
95
|
+
- name: interface # label name
|
|
96
|
+
value: name # label value
|
|
97
|
+
- name: description
|
|
98
|
+
value: description
|
|
99
|
+
regex: .* #(optional) label values can be extracted by using regexp
|
|
100
|
+
- name: link_mode
|
|
101
|
+
value: link_mode
|
|
102
|
+
- name: mac
|
|
103
|
+
value: macaddr
|
|
104
|
+
```
|
|
105
|
+
`metrics value` and `label value` select from fields key of PyEZ View.
|
|
106
|
+
```yaml
|
|
107
|
+
EthPortView:
|
|
108
|
+
groups:
|
|
109
|
+
mac_stats: ethernet-mac-statistics
|
|
110
|
+
flags: if-device-flags
|
|
111
|
+
fields: <- !!
|
|
112
|
+
oper: oper-status
|
|
113
|
+
admin: admin-status
|
|
114
|
+
description: description
|
|
115
|
+
mtu: { mtu : int }
|
|
116
|
+
link_mode: link-mode
|
|
117
|
+
macaddr: current-physical-address
|
|
118
|
+
-snip-
|
|
119
|
+
```
|
|
120
|
+
PyEZ Table's key is automatically mapping to `key` and `name`.
|
|
121
|
+
```yaml
|
|
122
|
+
EthPortTable:
|
|
123
|
+
rpc: get-interface-information
|
|
124
|
+
args:
|
|
125
|
+
media: True
|
|
126
|
+
interface_name: '[afgxe][et]-*'
|
|
127
|
+
args_key: interface_name <- !!
|
|
128
|
+
item: physical-interface
|
|
129
|
+
view: EthPortView
|
|
130
|
+
```
|
|
131
|
+
If there are multiple keys, a number is assigned at the end such as `key.0`, `key.1`.
|
|
132
|
+
```yaml
|
|
133
|
+
IsisAdjacencyTable:
|
|
134
|
+
rpc: get-isis-adjacency-information
|
|
135
|
+
args:
|
|
136
|
+
extensive: True
|
|
137
|
+
item: isis-adjacency
|
|
138
|
+
key:
|
|
139
|
+
- interface-name <- key.0, name.0
|
|
140
|
+
- system-name <- key.1, name.1
|
|
141
|
+
view: IsisAdjacencyView
|
|
142
|
+
```
|
|
143
|
+
The metrics value can be a static value.
|
|
144
|
+
```yaml
|
|
145
|
+
optables:
|
|
146
|
+
ArpTable:
|
|
147
|
+
metrics:
|
|
148
|
+
- name: arp_entry_info
|
|
149
|
+
value: 1 <- !!
|
|
150
|
+
type: gauge
|
|
151
|
+
help: arp entry info
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
#### Create Junos Device Config
|
|
155
|
+
```yaml
|
|
156
|
+
modules:
|
|
157
|
+
router: # module name
|
|
158
|
+
username: admin # junos device's username
|
|
159
|
+
password: admin@123 # junos device's password
|
|
160
|
+
tables: # pyez table name(which pyez table information to retrieve in this module)
|
|
161
|
+
- ArpTable
|
|
162
|
+
- EthPortTable
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
#### Create Prometheus Config
|
|
166
|
+
```yaml
|
|
167
|
+
scrape_configs:
|
|
168
|
+
- job_name: "junos-exporter"
|
|
169
|
+
static_configs:
|
|
170
|
+
- targets:
|
|
171
|
+
- "192.168.1.1" # target device
|
|
172
|
+
- "192.168.1.2"
|
|
173
|
+
labels:
|
|
174
|
+
module: "router" # module name
|
|
175
|
+
- targets:
|
|
176
|
+
- "192.168.10.3"
|
|
177
|
+
labels:
|
|
178
|
+
module: "switch"
|
|
179
|
+
relabel_configs:
|
|
180
|
+
- source_labels: [module]
|
|
181
|
+
target_label: __param_module
|
|
182
|
+
- source_labels: [__address__]
|
|
183
|
+
target_label: __param_target
|
|
184
|
+
- source_labels: [__param_target]
|
|
185
|
+
target_label: instance
|
|
186
|
+
- target_label: __address__
|
|
187
|
+
replacement: 127.0.0.1:9326
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## License
|
|
191
|
+
MIT
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
junos_exporter/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
junos_exporter/__main__.py,sha256=8hDtWlaFZK24KhfNq_ZKgtXqYHsDQDetukOCMlsbW0Q,59
|
|
3
|
+
junos_exporter/cli.py,sha256=BL6UbT-hhnL8L6r_vG4Xb77sYCg5xXHyX_OYOrbB9mU,2045
|
|
4
|
+
junos_exporter/config.py,sha256=vbJRIBcHc6V0BZomIyIavSYwKY8NR6Lvred7PeYslMc,3399
|
|
5
|
+
junos_exporter/connector.py,sha256=XCeJua952V12FsKCw4lUVsdzCgYsHy32gh-weWBmHhY,5528
|
|
6
|
+
junos_exporter/exporter.py,sha256=69ndu98N73KMWQzm1Qw2lWjtsXNN9pLKQcktas2xh-E,4133
|
|
7
|
+
junos_exporter-0.0.1.dist-info/METADATA,sha256=Al69_JuMoJhwyKNcEfRbwT1YQg7GVxg1yk_8rY_UNbY,6640
|
|
8
|
+
junos_exporter-0.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
9
|
+
junos_exporter-0.0.1.dist-info/entry_points.txt,sha256=0H8mKxczyxx6rzzBXPOztkEHsuXj8XyRINK-1ZM2voE,58
|
|
10
|
+
junos_exporter-0.0.1.dist-info/licenses/LICENSE,sha256=xRD9dlVf-UUwOJ3TiQ-TMFFTUsE-3xq1K5ArEISC1SI,1065
|
|
11
|
+
junos_exporter-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 minefuto
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|