Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13f6155096 | ||
|
|
97598a48ad | ||
|
|
01c07658c0 | ||
|
|
4ba4d461db | ||
|
|
45c7b8c168 | ||
|
|
b39c7e5279 | ||
|
|
2e5562fb3e |
@@ -162,8 +162,11 @@ GET /api/v1/health
|
|||||||
GET /api/v1/status
|
GET /api/v1/status
|
||||||
GET /api/v1/logs?limit=200
|
GET /api/v1/logs?limit=200
|
||||||
GET /api/v1/config
|
GET /api/v1/config
|
||||||
|
GET /api/v1/services
|
||||||
```
|
```
|
||||||
|
|
||||||
|
日志接口支持 `since`、`until` Unix 时间戳,`severity`、`event`、`search` 筛选,`timestamp` / `severity` / `event` / `message` 排序,以及 `limit` / `offset` 分页。Web 提供今天、昨天、本周、本月和全部快捷范围。日志直接读取 systemd journal 的现有保留数据,不建立重复的 SQLite 日志副本。
|
||||||
|
|
||||||
配置写入接口:
|
配置写入接口:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
@@ -174,6 +177,8 @@ Content-Type: application/json
|
|||||||
{"updates":{"led":{"service_b":"96"},"api":{"port":"6001"}}}
|
{"updates":{"led":{"service_b":"96"},"api":{"port":"6001"}}}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
服务监控页面会列出本机 systemd 服务,并标识“已监控/未监控”。添加、编辑或删除监控使用 `PUT /api/v1/services`;启动或停止服务使用 `PUT /api/v1/services/control`,两者均要求 Bearer Token。API 服务不能通过自己的请求停止自身,其他服务由用户自行管理。监控备注保存在配置文件的 `[service_notes]`,不会参与硬件 Agent 的监控判断。
|
||||||
|
|
||||||
读取 token:
|
读取 token:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+3
-3
@@ -1,10 +1,10 @@
|
|||||||
a182abe8c1f188b9e9b47fdc24802fedd6a569b462a85254185521fe68936a76 README.md
|
ce6123a9d39b1c552774a4b02062abbf4e223ff8f4c93212c9ea6e0bef412c85 README.md
|
||||||
72c46162c33f9587c6ccb01ad53fbaaf4ecec8cd21014b909e87e8707e253e36 app/oled_font_5x7.bin
|
72c46162c33f9587c6ccb01ad53fbaaf4ecec8cd21014b909e87e8707e253e36 app/oled_font_5x7.bin
|
||||||
d71d949643d31461f2e62ded3818e1a0f1711d1420756ad0cc32eb04cde0fad3 app/pigway_pi_control.py
|
d71d949643d31461f2e62ded3818e1a0f1711d1420756ad0cc32eb04cde0fad3 app/pigway_pi_control.py
|
||||||
3a13b4e8f9d306e77f82eba78b78fe9b1932488884d6f3f976754bfa94f0153d app/pigway_pi_control_api.py
|
93aff38477658c1517eac6a2d6a0bdf23b9fb372fa0b1b578ab32b649be1f1f2 app/pigway_pi_control_api.py
|
||||||
75fa662ed21138a8e394de83e46281dab039433cc0d7a8f787e1a049f4b47ec8 config/pigway-pi-control.conf
|
75fa662ed21138a8e394de83e46281dab039433cc0d7a8f787e1a049f4b47ec8 config/pigway-pi-control.conf
|
||||||
f34eac1df180a3da3a6998d650c06435fd89728c10b090f6162df82e53986dd0 install.sh
|
f34eac1df180a3da3a6998d650c06435fd89728c10b090f6162df82e53986dd0 install.sh
|
||||||
4f6e8db3698a62f57823d3298a0e6814593de6fa3d31e4751b7ea4a76e553e35 systemd/pigway-pi-control.service
|
4f6e8db3698a62f57823d3298a0e6814593de6fa3d31e4751b7ea4a76e553e35 systemd/pigway-pi-control.service
|
||||||
aa21cef9a06593371ccff005335b6c0c826fbf4b5c48e4255b5f4b75ce6e9217 systemd/pigway-pi-control-api.service
|
aa21cef9a06593371ccff005335b6c0c826fbf4b5c48e4255b5f4b75ce6e9217 systemd/pigway-pi-control-api.service
|
||||||
9f59e7313ee58e687ae6dd29d175c67082674254ac5c5f54168b2735b64c20a4 uninstall.sh
|
9f59e7313ee58e687ae6dd29d175c67082674254ac5c5f54168b2735b64c20a4 uninstall.sh
|
||||||
53a1cbbef49d1300c5d79ab2dda9d57d6743fe8d34cbae60d0c81d7d6e6f561c web/index.html
|
63a5e7a21d16f7f0e72845798be3b858b641f9d886dc06a013821100ccb1f3f4 web/index.html
|
||||||
|
|||||||
+129
-10
@@ -12,10 +12,12 @@ TOKEN=Path("/etc/pigway-pi-control-api.token")
|
|||||||
WEB=Path("/usr/local/share/pigway-pi-control/web/index.html")
|
WEB=Path("/usr/local/share/pigway-pi-control/web/index.html")
|
||||||
ALLOWED_SECTIONS={"services","processes","alerts","fan","led","timing","dark_mode","display","api"}
|
ALLOWED_SECTIONS={"services","processes","alerts","fan","led","timing","dark_mode","display","api"}
|
||||||
NAME_RE=re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
|
NAME_RE=re.compile(r"^[A-Za-z0-9_.-]{1,64}$")
|
||||||
|
UNIT_RE=re.compile(r"^[A-Za-z0-9_.@:-]{1,128}\.service$")
|
||||||
RGB_KEY_RE=re.compile(r"^(cpu|power|memory|storage|network|service|normal)_[rgb]$")
|
RGB_KEY_RE=re.compile(r"^(cpu|power|memory|storage|network|service|normal)_[rgb]$")
|
||||||
FLASH_KEY_RE=re.compile(r"^(warning|critical|emergency|normal)_flash_(on|off)_ms$")
|
FLASH_KEY_RE=re.compile(r"^(warning|critical|emergency|normal)_flash_(on|off)_ms$")
|
||||||
NORMAL_MODES={"off","solid","flash","flow","breathe","marquee","rainbow","colorful"}
|
NORMAL_MODES={"off","solid","flash","flow","breathe","marquee","rainbow","colorful"}
|
||||||
EFFECT_COLORS={"red","green","blue","yellow","purple","cyan","white"}
|
EFFECT_COLORS={"red","green","blue","yellow","purple","cyan","white"}
|
||||||
|
PROTECTED_UNITS={"pigway-pi-control-api.service"}
|
||||||
|
|
||||||
def load_cfg():
|
def load_cfg():
|
||||||
cfg=configparser.ConfigParser(); cfg.read(CFG)
|
cfg=configparser.ConfigParser(); cfg.read(CFG)
|
||||||
@@ -89,18 +91,109 @@ def update_ini(updates):
|
|||||||
temporary.write_text(text); temporary.chmod(0o644); temporary.replace(CFG)
|
temporary.write_text(text); temporary.chmod(0o644); temporary.replace(CFG)
|
||||||
return str(backup)
|
return str(backup)
|
||||||
|
|
||||||
def journal(limit):
|
def journal_query(since=None,until=None,severity="",event="",search="",sort="timestamp",order="desc",limit=100,offset=0):
|
||||||
result=subprocess.run(["journalctl","-u","pigway-pi-control.service","-n",str(limit),
|
command=["journalctl","-u","pigway-pi-control.service","--no-pager","-o","json"]
|
||||||
"--no-pager","-o","json"],capture_output=True,text=True,timeout=5)
|
if since is not None: command.extend(["--since",f"@{since}"])
|
||||||
|
if until is not None: command.extend(["--until",f"@{until}"])
|
||||||
|
result=subprocess.run(command,capture_output=True,text=True,timeout=15)
|
||||||
if result.returncode: raise RuntimeError(result.stderr.strip() or "journalctl failed")
|
if result.returncode: raise RuntimeError(result.stderr.strip() or "journalctl failed")
|
||||||
rows=[]
|
rows=[]
|
||||||
for line in result.stdout.splitlines():
|
for line in result.stdout.splitlines():
|
||||||
try:
|
try:
|
||||||
item=json.loads(line)
|
item=json.loads(line)
|
||||||
rows.append({"timestamp":item.get("__REALTIME_TIMESTAMP"),"priority":item.get("PRIORITY"),
|
message=item.get("MESSAGE","")
|
||||||
"message":item.get("MESSAGE","")})
|
level_match=re.search(r"(?:^|\s)level=([A-Z]+)(?:\s|$)",message)
|
||||||
|
event_match=re.search(r"(?:^|\s)event=([^ ]+)",message)
|
||||||
|
priority=str(item.get("PRIORITY","6"))
|
||||||
|
level=(level_match.group(1) if level_match else
|
||||||
|
{"0":"EMERGENCY","1":"ALERT","2":"CRITICAL","3":"ERROR","4":"WARN","5":"NOTICE","6":"INFO","7":"DEBUG"}.get(priority,"INFO"))
|
||||||
|
rows.append({"timestamp":int(item.get("__REALTIME_TIMESTAMP",0)),"priority":priority,
|
||||||
|
"severity":level,"event":event_match.group(1) if event_match else "SYSTEM",
|
||||||
|
"message":message})
|
||||||
except json.JSONDecodeError: pass
|
except json.JSONDecodeError: pass
|
||||||
return rows
|
severities={x.strip().upper() for x in severity.split(",") if x.strip()}
|
||||||
|
if severities: rows=[x for x in rows if x["severity"] in severities]
|
||||||
|
event_types=sorted({x["event"] for x in rows})
|
||||||
|
if event: rows=[x for x in rows if x["event"]==event]
|
||||||
|
if search:
|
||||||
|
needle=search.casefold(); rows=[x for x in rows if needle in x["message"].casefold()]
|
||||||
|
severity_rank={"EMERGENCY":0,"ALERT":1,"CRITICAL":2,"ERROR":3,"WARN":4,"NOTICE":5,"INFO":6,"DEBUG":7}
|
||||||
|
keys={"timestamp":lambda x:x["timestamp"],"severity":lambda x:severity_rank.get(x["severity"],99),
|
||||||
|
"event":lambda x:x["event"],"message":lambda x:x["message"]}
|
||||||
|
rows.sort(key=keys[sort],reverse=order=="desc")
|
||||||
|
total=len(rows)
|
||||||
|
return {"logs":rows[offset:offset+limit],"total":total,"offset":offset,"limit":limit,
|
||||||
|
"event_types":event_types,"retention":"systemd-journal"}
|
||||||
|
|
||||||
|
def service_inventory():
|
||||||
|
cfg=load_cfg()
|
||||||
|
monitored={target.lower():(name,target) for name,target in cfg.items("services")} if cfg.has_section("services") else {}
|
||||||
|
notes=dict(cfg.items("service_notes")) if cfg.has_section("service_notes") else {}
|
||||||
|
files=subprocess.run(["systemctl","list-unit-files","--type=service","--no-legend","--no-pager"],
|
||||||
|
capture_output=True,text=True,timeout=10,check=True)
|
||||||
|
units={}
|
||||||
|
for line in files.stdout.splitlines():
|
||||||
|
parts=line.split()
|
||||||
|
if len(parts)>=2 and UNIT_RE.fullmatch(parts[0]):
|
||||||
|
units[parts[0]]={"unit":parts[0],"enabled":parts[1],"active":"inactive","description":""}
|
||||||
|
states=subprocess.run(["systemctl","list-units","--all","--type=service","--no-legend","--no-pager","--plain"],
|
||||||
|
capture_output=True,text=True,timeout=10,check=True)
|
||||||
|
for line in states.stdout.splitlines():
|
||||||
|
parts=line.split(None,4)
|
||||||
|
if len(parts)>=4 and UNIT_RE.fullmatch(parts[0]):
|
||||||
|
item=units.setdefault(parts[0],{"unit":parts[0],"enabled":"unknown"})
|
||||||
|
item.update({"active":parts[2],"description":parts[4] if len(parts)>4 else ""})
|
||||||
|
for name,target in monitored.values():
|
||||||
|
item=units.setdefault(target,{"unit":target,"enabled":"not-found","active":"inactive","description":""})
|
||||||
|
item.update({"monitored":True,"monitor_name":name.upper(),"note":notes.get(name,"")})
|
||||||
|
for item in units.values():
|
||||||
|
item.setdefault("monitored",False); item.setdefault("monitor_name",""); item.setdefault("note","")
|
||||||
|
item["protected"]=item["unit"] in PROTECTED_UNITS
|
||||||
|
return sorted(units.values(),key=lambda x:(not x["monitored"],x["unit"]))
|
||||||
|
|
||||||
|
def edit_service_monitor(operation,name,target,note="",previous_name=""):
|
||||||
|
if operation not in {"save","delete"}: raise ValueError("operation must be save or delete")
|
||||||
|
if not NAME_RE.fullmatch(name): raise ValueError("invalid monitor name")
|
||||||
|
if not UNIT_RE.fullmatch(target): raise ValueError("invalid systemd service name")
|
||||||
|
if len(note)>120 or any(c in note for c in "\r\n\x00"): raise ValueError("invalid note")
|
||||||
|
if previous_name and not NAME_RE.fullmatch(previous_name): raise ValueError("invalid previous monitor name")
|
||||||
|
cfg=load_cfg(); old_target=cfg.get("services",name,fallback=None)
|
||||||
|
text=CFG.read_text()
|
||||||
|
def change(section,key,value):
|
||||||
|
nonlocal text
|
||||||
|
section_match=re.search(rf"(?mi)^\[{re.escape(section)}\]\s*$",text)
|
||||||
|
if not section_match:
|
||||||
|
if value is not None: text=text.rstrip()+f"\n\n[{section}]\n{key} = {value}\n"
|
||||||
|
return
|
||||||
|
next_section=re.search(r"(?m)^\[.+\]\s*$",text[section_match.end():])
|
||||||
|
end=section_match.end()+(next_section.start() if next_section else len(text)-section_match.end())
|
||||||
|
chunk=text[section_match.end():end]
|
||||||
|
key_match=re.search(rf"(?mi)^\s*{re.escape(key)}\s*=.*(?:\n|$)",chunk)
|
||||||
|
if key_match:
|
||||||
|
start=section_match.end()+key_match.start(); stop=section_match.end()+key_match.end()
|
||||||
|
text=text[:start]+((f"{key} = {value}\n") if value is not None else "")+text[stop:]
|
||||||
|
elif value is not None:
|
||||||
|
text=text[:end].rstrip()+f"\n{key} = {value}\n\n"+text[end:].lstrip("\n")
|
||||||
|
if operation=="delete":
|
||||||
|
if old_target is None: raise ValueError("monitor not found")
|
||||||
|
change("services",name,None); change("service_notes",name,None)
|
||||||
|
else:
|
||||||
|
if previous_name and previous_name.lower()!=name.lower():
|
||||||
|
change("services",previous_name,None); change("service_notes",previous_name,None)
|
||||||
|
change("services",name,target); change("service_notes",name,note or None)
|
||||||
|
parsed=configparser.ConfigParser(); parsed.read_string(text)
|
||||||
|
backup=CFG.with_name(f"{CFG.name}.bak.api-{time.strftime('%Y%m%d-%H%M%S')}")
|
||||||
|
shutil.copy2(CFG,backup)
|
||||||
|
temporary=CFG.with_suffix(".tmp"); temporary.write_text(text); temporary.chmod(0o644); temporary.replace(CFG)
|
||||||
|
subprocess.run(["systemctl","restart","pigway-pi-control.service"],check=True,timeout=10)
|
||||||
|
return str(backup)
|
||||||
|
|
||||||
|
def control_service(unit,action):
|
||||||
|
if not UNIT_RE.fullmatch(unit): raise ValueError("invalid systemd service name")
|
||||||
|
if action not in {"start","stop"}: raise ValueError("action must be start or stop")
|
||||||
|
if unit in PROTECTED_UNITS and action=="stop": raise ValueError("protected remote-management service cannot be stopped here")
|
||||||
|
result=subprocess.run(["systemctl",action,unit],capture_output=True,text=True,timeout=20)
|
||||||
|
if result.returncode: raise RuntimeError(result.stderr.strip() or f"systemctl {action} failed")
|
||||||
|
|
||||||
class Handler(BaseHTTPRequestHandler):
|
class Handler(BaseHTTPRequestHandler):
|
||||||
server_version="PIGWayAPI/3.6"
|
server_version="PIGWayAPI/3.6"
|
||||||
@@ -142,18 +235,44 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if not STATUS.exists(): self.send_json(503,{"error":"agent status unavailable"}); return
|
if not STATUS.exists(): self.send_json(503,{"error":"agent status unavailable"}); return
|
||||||
self.send_json(200,json.loads(STATUS.read_text())); return
|
self.send_json(200,json.loads(STATUS.read_text())); return
|
||||||
if parsed.path=="/api/v1/logs":
|
if parsed.path=="/api/v1/logs":
|
||||||
limit=min(max(int(parse_qs(parsed.query).get("limit",[api_setting("log_limit",200,int)])[0]),1),1000)
|
query=parse_qs(parsed.query)
|
||||||
self.send_json(200,{"logs":journal(limit)}); return
|
value=lambda key,default="":query.get(key,[default])[0]
|
||||||
|
limit=min(max(int(value("limit",api_setting("log_limit",200,int))),1),500)
|
||||||
|
offset=max(int(value("offset",0)),0)
|
||||||
|
since=int(value("since")) if value("since") else None
|
||||||
|
until=int(value("until")) if value("until") else None
|
||||||
|
if since is not None and until is not None and since>until: raise ValueError("since must not be after until")
|
||||||
|
sort=value("sort","timestamp"); order=value("order","desc")
|
||||||
|
if sort not in {"timestamp","severity","event","message"}: raise ValueError("invalid log sort")
|
||||||
|
if order not in {"asc","desc"}: raise ValueError("invalid log order")
|
||||||
|
severity=value("severity").upper(); event=value("event"); search=value("search")
|
||||||
|
if len(event)>80 or len(search)>120: raise ValueError("log filter is too long")
|
||||||
|
self.send_json(200,journal_query(since,until,severity,event,search,sort,order,limit,offset)); return
|
||||||
if parsed.path=="/api/v1/config":
|
if parsed.path=="/api/v1/config":
|
||||||
self.send_json(200,{"config":config_json(),"write_requires_token":True}); return
|
self.send_json(200,{"config":config_json(),"write_requires_token":True}); return
|
||||||
|
if parsed.path=="/api/v1/services":
|
||||||
|
self.send_json(200,{"services":service_inventory()}); return
|
||||||
self.send_json(404,{"error":"not found"})
|
self.send_json(404,{"error":"not found"})
|
||||||
|
except ValueError as e: self.send_json(400,{"error":str(e)})
|
||||||
except Exception as e: self.send_json(500,{"error":str(e)})
|
except Exception as e: self.send_json(500,{"error":str(e)})
|
||||||
|
|
||||||
def do_PUT(self):
|
def do_PUT(self):
|
||||||
if urlparse(self.path).path!="/api/v1/config": self.send_json(404,{"error":"not found"}); return
|
path=urlparse(self.path).path
|
||||||
|
if path not in {"/api/v1/config","/api/v1/services","/api/v1/services/control"}: self.send_json(404,{"error":"not found"}); return
|
||||||
if not self.authorized(): self.send_json(401,{"error":"bearer token required"}); return
|
if not self.authorized(): self.send_json(401,{"error":"bearer token required"}); return
|
||||||
try:
|
try:
|
||||||
body=self.read_json(); updates=body.get("updates")
|
body=self.read_json()
|
||||||
|
if path=="/api/v1/services/control":
|
||||||
|
control_service(str(body.get("unit","")),str(body.get("action","")))
|
||||||
|
print(f"SERVICE_CONTROL action={body.get('action')} unit={body.get('unit')}",flush=True)
|
||||||
|
self.send_json(200,{"ok":True}); return
|
||||||
|
if path=="/api/v1/services":
|
||||||
|
backup=edit_service_monitor(str(body.get("operation","")),str(body.get("name","")),
|
||||||
|
str(body.get("target","")),str(body.get("note","")),
|
||||||
|
str(body.get("previous_name","")))
|
||||||
|
print(f"SERVICE_MONITOR_UPDATED operation={body.get('operation')} target={body.get('target')} backup={backup}",flush=True)
|
||||||
|
self.send_json(200,{"ok":True,"backup":backup}); return
|
||||||
|
updates=body.get("updates")
|
||||||
backup=update_ini(updates)
|
backup=update_ini(updates)
|
||||||
subprocess.run(["systemctl","restart","pigway-pi-control.service"],check=True,timeout=10)
|
subprocess.run(["systemctl","restart","pigway-pi-control.service"],check=True,timeout=10)
|
||||||
restart_api="api" in updates
|
restart_api="api" in updates
|
||||||
|
|||||||
+27
-8
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user