Chủ động đẩy cảnh báo từ router về server (Telmetry MDT)

1. Sơ đồ mạng

Dùng Router chủ động đẩy dữ liệu về máy chủ giám sát theo chu kỳ, thay vì bị hỏi (poll) như SNMP truyền thống.


Router cần ping được đến máy chủ qua port 57000/TCP

2. CẤU HÌNH TRÊN ROUTER (Cisco IOS-XE)
Đầu tiên, đảm bảo Router có IP và bật NETCONF:


enable
configure terminal
interface GigabitEthernet1
 ip address 192.168.199.136 255.255.255.0
 no shutdown
 exit
netconf-yang

 

2.1 Cấu hình Subscription giám sát trạng thái cổng

telemetry ietf subscription 105
 encoding encode-kvgpb
 filter xpath /interfaces-ios-xe-oper:interfaces/interface/oper-status
 source-address 192.168.199.136 ##IP của router local
 stream yang-push
 update-policy periodic 1000 ##là 10s
 receiver ip address 192.168.199.135 57000 protocol grpc-tcp
 exit

Ngoài chế độ "periodic" (đẩy theo chu kỳ 10s như trên), Telemetry còn hỗ trợ chế độ "on-change" (đẩy dữ liệu NGAY LẬP TỨC khi có sự cố, không có độ trễ).
Tuy nhiên, trên môi trường lab ảo (CSR1000v), test thử thấy ko đổ dữ liệu về server, nên ta xài chế độ on-change .

Trên thiết bị thật ta nên ưu tiên dùng on-change thay cho periodic bằng cú pháp sau:
update-policy on-change

Show lại kiểm tra thấy valid là OK

CSRv-1612#show telemetry ietf subscription all

3. CẤU HÌNH MÁY CHỦ GIÁM SÁT 

Ta bảo AI cho file config telegraf.conf để nhận dữ liệu telmetry từ router đẩy lên, tương tự như này

[agent]

  interval = "10s"

  flush_interval = "10s"

[[inputs.cisco_telemetry_mdt]]

  transport = "grpc"

  service_address = ":57000"

[[processors.enum]]

  [[processors.enum.mapping]]

    field = "oper_status"

    dest = "oper_status_code"

    [processors.enum.mapping.value_mappings]

      if-oper-state-ready = 1

      if-oper-state-up = 1

      if-oper-state-no-pass = 0

      if-oper-state-down = 0

[[outputs.prometheus_client]]

  listen = ":9273"

  metric_version = 2

  export_timestamp = true

  string_as_label = false ##Chỗ này để cảnh báo hiện ngay lên webgui khi có sự kiện như down/up, bảo AI lưu ý 

Đây là mẫu dữ liệu router đẩy lên, nếu xài tự code app hiển thị thì cho AI xem mấu này:

Cisco_IOS_XE_interfaces_oper:interfaces_interface_oper_status_code{name="GigabitEthernet2",source="CSRv"} 0   ## 0 nghĩa là down, 1 là up

4. CẤU HÌNH TỰ ĐỘNG TẠO GIAO DIỆN GRAFANA & CẢNH BÁO BẰNG SCRIPT

Copy đoạn dưới cho AI của bạn đọc; rồi bảo AI tạo giao diện theo nhu cầu giám sát (ví dụ bảng router, bảng event up/down) , nó sẽ sinh ra file ví dụ bên dưới:

import urllib.request, json, base64

grafana_url = 'http://localhost:3000'
auth = base64.b64encode(b'admin:admin').decode()
headers = {'Content-Type': 'application/json', 'Authorization': 'Basic ' + auth}

print("[*] 1. Dang tao Prometheus Data Source...")
ds_payload = {"name": "Prometheus", "type": "prometheus", "url": "http://prometheus:9090", "access": "proxy", "isDefault": True}
try:
    urllib.request.urlopen(urllib.request.Request(f"{grafana_url}/api/datasources", data=json.dumps(ds_payload).encode(), headers=headers))
except:
    pass

req = urllib.request.Request(f"{grafana_url}/api/datasources", headers=headers)
ds_uid = json.loads(urllib.request.urlopen(req).read().decode())[0]['uid']

print("[*] 2. Dang tao NOC Dashboard...")
dashboard = {
  "dashboard": {
    "uid": "noc-overview", "title": "NOC Overview Dashboard", "timezone": "browser", "refresh": "10s",
    "panels": [
      {
        "title": "Trang thai cac cong mang", "type": "table", "gridPos": {"h": 10, "w": 24, "x": 0, "y": 0},
        "datasource": {"uid": ds_uid},
        "targets": [{"expr": 'Cisco_IOS_XE_interfaces_oper:interfaces_interface_oper_status_code{name!="Control Plane"}', "format": "table", "instant": True}],
        "transformations": [{"id": "sortBy", "options": {"sort": [{"field": "Value", "desc": False}]}}]
      },
      {
        "title": "Timeline", "type": "state-timeline", "gridPos": {"h": 8, "w": 24, "x": 0, "y": 10},
        "datasource": {"uid": ds_uid},
        "targets": [{"expr": 'Cisco_IOS_XE_interfaces_oper:interfaces_interface_oper_status_code{name!="Control Plane"}'}]
      }
    ]
  },
  "overwrite": True
}
urllib.request.urlopen(urllib.request.Request(f"{grafana_url}/api/dashboards/db", data=json.dumps(dashboard).encode(), headers=headers))

print("[*] 3. Dang tao Telegram Contact Point...")
BOT_TOKEN = "5453362950:AAG79EYrDC0xvghfxxpH8XSTZLg" ##thay của bạn
CHAT_ID = "135133982" ##thay sang của bạn

cp_payload = {"name": "Telegram NOC", "type": "telegram", "settings": {"bottoken": BOT_TOKEN, "chatid": CHAT_ID}}
try:
    urllib.request.urlopen(urllib.request.Request(f"{grafana_url}/api/v1/provisioning/contact-points", data=json.dumps(cp_payload).encode(), headers=headers))
except:
    pass

print("[*] 4. Dang tao Alert Rule...")
try:
    urllib.request.urlopen(urllib.request.Request(f"{grafana_url}/api/folders", data=json.dumps({"uid": "NetworkAlerts", "title": "Network Alerts"}).encode(), headers=headers))
except:
    pass

alert_payload = {
    "title": "Cổng mạng bị sập", "condition": "C", "folderUID": "NetworkAlerts", "ruleGroup": "InterfaceStatus", "for": "0s",
    "annotations": {"summary": "Cổng mạng bị sập, check gấp!"},
    "data": [
        {"refId": "A", "datasourceUid": ds_uid, "model": {"expr": 'Cisco_IOS_XE_interfaces_oper:interfaces_interface_oper_status_code{name!="Control Plane"}', "refId": "A"}},
        {"refId": "B", "datasourceUid": "__expr__", "model": {"type": "reduce", "reducer": "last", "expression": "A", "refId": "B"}},
        {"refId": "C", "datasourceUid": "__expr__", "model": {"type": "math", "expression": "$B nhỏ hơn 1", "refId": "C"}}
    ]
}
try:
    urllib.request.urlopen(urllib.request.Request(f"{grafana_url}/api/v1/provisioning/alert-rules", data=json.dumps(alert_payload).encode(), headers=headers))
except:
    pass
print("[*] 4. XONG! Toan bo cau hinh da duoc day len Grafana.")

 


Sau đó chạy python3 auto_grafana.py là xong, lỗi gì paste AI check.


5. KIỂM TRA LẠI

Vào các đường link này để xem (với 199.135 là IP server giám sát)

Dashboard vừa tạo bằng code             http://192.168.199.135:3000/d/noc-overview
Data Source (Prometheus)                  http://192.168.199.135:3000/connections/datasources
Alert Rules (Bắn cảnh báo)                 http://192.168.199.135:3000/alerting/list
Contact Points (Bắn tin Telegram)      http://192.168.199.135:3000/alerting/notifications

Trên Router, thử shutdown 1 cổng Gi3:

interface GigabitEthernet3
 shutdown
end


Mở link Dashboard , trong vòng 10 giây, ta thấy:
- Cổng GigabitEthernet3 chuyển sang trạng thái DOWN (Đỏ), nhanh hơn hẳn SNMP:

- Telegram nhận được tin nhắn cảnh báo.

Bài viết cùng danh mục