feat: монолит iot-service (Фаза 1) — config/store/api/bridge/consumer без k8s, устройства в PG, новые Dockerfile/Makefile

This commit is contained in:
“Naeel”
2026-08-16 10:07:51 +04:00
parent f0c36a11ee
commit 9d08473d5f
27 changed files with 3716 additions and 0 deletions
+20
View File
@@ -0,0 +1,20 @@
// admin_embed.go — встраивает HTML страницы администратора в бинарник.
package api
import (
_ "embed"
"net/http"
)
// iotAdminHTML — страница /iot-admin, встроена при сборке.
//
//go:embed ui/iot-admin.html
var iotAdminHTML []byte
// ServeIoTAdmin отдаёт HTML страницу администратора.
func ServeIoTAdmin(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(iotAdminHTML)
}
+20
View File
@@ -0,0 +1,20 @@
// console_embed.go — встраивает HTML IoT консоли в бинарник.
package api
import (
_ "embed"
"net/http"
)
// iotConsoleHTML — консоль /console, встроена при сборке.
//
//go:embed ui/iot-console.html
var iotConsoleHTML []byte
// ServeIoTConsole отдаёт HTML консоли.
func ServeIoTConsole(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-cache, must-revalidate")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(iotConsoleHTML)
}
+58
View File
@@ -0,0 +1,58 @@
// admin.go — статистика для страницы администратора.
//
// Endpoint: GET /iot-admin/stats (Bearer ADMIN_STATS_TOKEN).
// Источники: PostgreSQL (iotpg), shared-SQS (атрибуты очереди), рантайм процесса.
// k8s-статусы подов убраны — компоненты теперь в одном процессе.
package handler
import (
"context"
"net/http"
"strings"
"time"
)
// AdminStats — GET /iot-admin/stats.
func (h *Handler) AdminStats(w http.ResponseWriter, r *http.Request) {
if h.Cfg.AdminStatsToken == "" {
writeJSON(w, http.StatusServiceUnavailable, errResp("admin stats not configured: ADMIN_STATS_TOKEN not set"))
return
}
authHeader := r.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") || strings.TrimPrefix(authHeader, "Bearer ") != h.Cfg.AdminStatsToken {
writeJSON(w, http.StatusUnauthorized, errResp("unauthorized"))
return
}
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
defer cancel()
result := map[string]any{
"collected_at": time.Now().UTC(),
}
// PostgreSQL: статистика по всем tenant (как в старом коде).
if h.IoTPG != nil {
pgStats, err := h.IoTPG.GetAdminStats(ctx)
if err != nil {
result["postgres"] = map[string]any{"reachable": false, "error": err.Error()}
} else {
result["postgres"] = pgStats
}
} else {
result["postgres"] = map[string]any{"reachable": false, "error": "IoTPG not configured"}
}
// SQS: approximate counts очереди телеметрии.
result["sqs"] = h.collectSQSStats(ctx)
// Рантайм процесса (вместо статусов k8s-подов).
result["runtime"] = map[string]any{
"version": h.Version,
"uptime_sec": int64(time.Since(h.StartedAt).Seconds()),
"started_at": h.StartedAt.UTC().Format(time.RFC3339),
}
writeJSON(w, http.StatusOK, result)
}
+244
View File
@@ -0,0 +1,244 @@
// devices.go — CRUD устройств на PostgreSQL.
//
// Endpoints:
//
// POST /v1/namespaces/{ns}/iot/devices — создать
// GET /v1/namespaces/{ns}/iot/devices — список (без паролей)
// GET /v1/namespaces/{ns}/iot/devices/{name} — одно (с паролем)
// DELETE /v1/namespaces/{ns}/iot/devices/{name} — удалить
// PATCH /v1/namespaces/{ns}/iot/devices/{name} — enabled
package handler
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"time"
"gitea.services.ngcloud.ru/Nail/IoT/internal/service/store"
)
// iotDeviceCreateRequest — тело POST.
type iotDeviceCreateRequest struct {
Name string `json:"name"`
DeviceID string `json:"device_id"`
Enabled *bool `json:"enabled"`
Metadata map[string]string `json:"metadata,omitempty"`
}
// iotDeviceUpdateRequest — тело PATCH.
type iotDeviceUpdateRequest struct {
Enabled *bool `json:"enabled"`
}
// iotDeviceResponse — ответ API. MQTTPassword — только в GET по имени.
type iotDeviceResponse struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
DeviceID string `json:"device_id"`
Enabled bool `json:"enabled"`
Phase string `json:"phase"`
MQTTUsername string `json:"mqtt_username,omitempty"`
MQTTPassword string `json:"mqtt_password,omitempty"`
TopicPrefix string `json:"topic_prefix,omitempty"`
LastConnected string `json:"last_connected,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
}
// deviceToResponse конвертирует устройство из БД в ответ API.
// password отдаётся только если непустая (передаётся явно из Get).
func deviceToResponse(d *store.Device, password string) iotDeviceResponse {
resp := iotDeviceResponse{
Name: d.Name,
Namespace: d.Namespace,
DeviceID: d.DeviceID,
Enabled: d.Enabled,
Phase: d.Phase,
MQTTUsername: d.Namespace + "_" + d.DeviceID,
MQTTPassword: password,
TopicPrefix: d.Namespace + "/",
Metadata: d.Metadata,
}
if d.LastConnected != nil && !d.LastConnected.IsZero() {
resp.LastConnected = d.LastConnected.UTC().Format(time.RFC3339)
}
if !d.CreatedAt.IsZero() {
resp.CreatedAt = d.CreatedAt.UTC().Format("2006-01-02 15:04:05 UTC")
}
return resp
}
// generateMQTTPassword — 32 случайных байта в hex (как старый контроллер).
func generateMQTTPassword() (string, error) {
buf := make([]byte, 32)
if _, err := rand.Read(buf); err != nil {
return "", err
}
return hex.EncodeToString(buf), nil
}
// CreateIoTDevice — POST /v1/namespaces/{ns}/iot/devices.
func (h *Handler) CreateIoTDevice(w http.ResponseWriter, r *http.Request) {
ns := pathVar(r, "namespace")
if ns == "" {
ns = "default"
}
var req iotDeviceCreateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, errResp("invalid JSON: "+err.Error()))
return
}
if req.Name == "" {
writeJSON(w, http.StatusBadRequest, errResp("name is required"))
return
}
if req.DeviceID == "" {
writeJSON(w, http.StatusBadRequest, errResp("device_id is required"))
return
}
enabled := true
if req.Enabled != nil {
enabled = *req.Enabled
}
password, err := generateMQTTPassword()
if err != nil {
h.Log.Error("generate device password", "err", err)
writeJSON(w, http.StatusInternalServerError, errResp("failed to generate credentials"))
return
}
phase := "Active"
if !enabled {
phase = "Disabled"
}
device := &store.Device{
Namespace: ns,
Name: req.Name,
DeviceID: req.DeviceID,
Enabled: enabled,
MQTTPassword: password,
Metadata: req.Metadata,
Phase: phase,
}
if err := h.Devices.Create(r.Context(), device); err != nil {
if errors.Is(err, store.ErrAlreadyExists) {
writeJSON(w, http.StatusConflict, errResp("iot device already exists"))
return
}
h.Log.Error("create device", "namespace", ns, "name", req.Name, "err", err)
writeJSON(w, http.StatusInternalServerError, errResp("failed to create device"))
return
}
writeJSON(w, http.StatusCreated, deviceToResponse(device, ""))
}
// ListIoTDevices — GET /v1/namespaces/{ns}/iot/devices (без паролей).
func (h *Handler) ListIoTDevices(w http.ResponseWriter, r *http.Request) {
ns := pathVar(r, "namespace")
if ns == "" {
ns = "default"
}
devices, err := h.Devices.List(r.Context(), ns)
if err != nil {
h.Log.Error("list devices", "namespace", ns, "err", err)
writeJSON(w, http.StatusInternalServerError, errResp("failed to list devices"))
return
}
result := make([]iotDeviceResponse, 0, len(devices))
for i := range devices {
result = append(result, deviceToResponse(&devices[i], ""))
}
writeJSON(w, http.StatusOK, result)
}
// GetIoTDevice — GET /v1/namespaces/{ns}/iot/devices/{name} (с паролем).
func (h *Handler) GetIoTDevice(w http.ResponseWriter, r *http.Request) {
ns := pathVar(r, "namespace")
if ns == "" {
ns = "default"
}
name := pathVar(r, "name")
device, err := h.Devices.GetByName(r.Context(), ns, name)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
writeJSON(w, http.StatusNotFound, errResp("iot device not found"))
return
}
h.Log.Error("get device", "namespace", ns, "name", name, "err", err)
writeJSON(w, http.StatusInternalServerError, errResp("failed to get device"))
return
}
writeJSON(w, http.StatusOK, deviceToResponse(device, device.MQTTPassword))
}
// DeleteIoTDevice — DELETE /v1/namespaces/{ns}/iot/devices/{name}.
func (h *Handler) DeleteIoTDevice(w http.ResponseWriter, r *http.Request) {
ns := pathVar(r, "namespace")
if ns == "" {
ns = "default"
}
name := pathVar(r, "name")
err := h.Devices.Delete(r.Context(), ns, name)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
writeJSON(w, http.StatusNotFound, errResp("iot device not found"))
return
}
h.Log.Error("delete device", "namespace", ns, "name", name, "err", err)
writeJSON(w, http.StatusInternalServerError, errResp("failed to delete device"))
return
}
w.WriteHeader(http.StatusNoContent)
}
// UpdateIoTDevice — PATCH /v1/namespaces/{ns}/iot/devices/{name} (enabled).
func (h *Handler) UpdateIoTDevice(w http.ResponseWriter, r *http.Request) {
ns := pathVar(r, "namespace")
if ns == "" {
ns = "default"
}
name := pathVar(r, "name")
var req iotDeviceUpdateRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, errResp("invalid JSON: "+err.Error()))
return
}
if req.Enabled == nil {
writeJSON(w, http.StatusBadRequest, errResp("enabled field is required"))
return
}
err := h.Devices.UpdateEnabled(r.Context(), ns, name, *req.Enabled)
if err != nil {
if errors.Is(err, store.ErrNotFound) {
writeJSON(w, http.StatusNotFound, errResp("iot device not found"))
return
}
h.Log.Error("update device", "namespace", ns, "name", name, "err", err)
writeJSON(w, http.StatusInternalServerError, errResp("failed to update device"))
return
}
device, err := h.Devices.GetByName(r.Context(), ns, name)
if err != nil {
writeJSON(w, http.StatusInternalServerError, errResp("failed to reload device"))
return
}
writeJSON(w, http.StatusOK, deviceToResponse(device, ""))
}
+49
View File
@@ -0,0 +1,49 @@
// Package handler — HTTP-обработчики IoT REST API (новый монолит).
//
// Отличие от старого кода: устройства — в PostgreSQL (таблица iot_devices),
// без k8s-клиента и CRD. Телеметрия — через iotpg, как раньше.
package handler
import (
"encoding/json"
"log/slog"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/gorilla/mux"
"gitea.services.ngcloud.ru/Nail/IoT/internal/service/config"
"gitea.services.ngcloud.ru/Nail/IoT/internal/service/store"
"gitea.services.ngcloud.ru/Nail/IoT/internal/storage/iotpg"
)
// Handler — зависимости всех HTTP-обработчиков.
type Handler struct {
Devices *store.DeviceStore
IoTPG *iotpg.IoTPostgresStore
SQS *sqs.Client
Cfg *config.Config
Log *slog.Logger
// Version — версия бинарника (ldflags), StartedAt — для админ-статистики.
Version string
StartedAt time.Time
}
// writeJSON отправляет JSON-ответ с указанным статусом.
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}
// errResp возвращает структуру ошибки для JSON.
func errResp(msg string) map[string]string {
return map[string]string{"error": msg}
}
// pathVar читает переменную пути из gorilla/mux.
func pathVar(r *http.Request, key string) string {
return mux.Vars(r)[key]
}
+167
View File
@@ -0,0 +1,167 @@
// mqtt_auth.go — HTTP-auth и ACL для EMQX (MQTT CONNECT / pub-sub).
//
// Endpoints (без JWT, вызываются EMQX внутри платформы):
//
// POST /internal/mqtt/auth — аутентификация: всегда HTTP 200, {"result":"allow"|"deny"}
// POST /internal/mqtt/acl — авторизация pub/sub
//
// Источник устройств — таблица iot_devices (не k8s Secrets).
package handler
import (
"crypto/subtle"
"encoding/json"
"errors"
"net/http"
"strings"
"gitea.services.ngcloud.ru/Nail/IoT/internal/service/store"
)
// mqttAuthRequest — тело запроса от EMQX 5.x (username, password, clientid, peerhost).
type mqttAuthRequest struct {
Username string `json:"username"`
Password string `json:"password"`
ClientID string `json:"clientid"`
PeerHost string `json:"peerhost"`
}
// mqttAuthResponse — ответ для EMQX (всегда HTTP 200).
type mqttAuthResponse struct {
Result string `json:"result"`
ACL []aclRule `json:"acl,omitempty"`
}
// aclRule — правило ACL для EMQX HTTP auth.
type aclRule struct {
Permission string `json:"permission"`
Action string `json:"action"`
Topic string `json:"topic"`
}
// mqttAclRequest — тело запроса ACL от EMQX.
type mqttAclRequest struct {
Username string `json:"username"`
ClientID string `json:"clientid"`
Action string `json:"action"`
Topic string `json:"topic"`
}
// MQTTAuth — POST /internal/mqtt/auth.
//
// Логика:
// 1. bridge-креды (MQTT_USERNAME/MQTT_PASSWORD из env) — проверяются до парсинга;
// 2. username "{ns}_{deviceId}" → поиск устройства в iot_devices;
// 3. constant-time сравнение пароля; проверка enabled;
// 4. best-effort last_connected; ACL по топику устройства.
func (h *Handler) MQTTAuth(w http.ResponseWriter, r *http.Request) {
var req mqttAuthRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
// Внутренний bridge-клиент: фиксированные креды, ACL выдаётся ниже.
if h.Cfg.MQTTUsername != "" && req.Username == h.Cfg.MQTTUsername {
if subtle.ConstantTimeCompare([]byte(h.Cfg.MQTTPassword), []byte(req.Password)) == 1 {
writeJSON(w, http.StatusOK, mqttAuthResponse{
Result: "allow",
ACL: bridgeACLRules(),
})
return
}
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
// Парсим username: "{namespace}_{deviceId}" (первый '_' — разделитель).
idx := strings.Index(req.Username, "_")
if idx <= 0 || idx == len(req.Username)-1 {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
ns := req.Username[:idx]
deviceID := req.Username[idx+1:]
device, err := h.Devices.GetByDeviceID(r.Context(), ns, deviceID)
if err != nil {
if !errors.Is(err, store.ErrNotFound) {
h.Log.Error("mqtt auth: device lookup", "namespace", ns, "device", deviceID, "err", err)
}
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
if !device.Enabled {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
if subtle.ConstantTimeCompare([]byte(device.MQTTPassword), []byte(req.Password)) != 1 {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
// best-effort: обновляем время последнего подключения
h.Devices.TouchLastConnected(r.Context(), ns, deviceID)
writeJSON(w, http.StatusOK, mqttAuthResponse{
Result: "allow",
ACL: deviceACLRules(ns, deviceID),
})
}
// MQTTAcl — POST /internal/mqtt/acl.
//
// Bridge (clientID из env MQTT_CLIENT_ID): только subscribe.
// Устройство ({ns}_{deviceId}): pub/sub в своём топике.
func (h *Handler) MQTTAcl(w http.ResponseWriter, r *http.Request) {
var req mqttAclRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
if req.ClientID == h.Cfg.MQTTClientID {
if req.Action == "subscribe" {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "allow"})
return
}
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
idx := strings.Index(req.Username, "_")
if idx <= 0 || idx == len(req.Username)-1 {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
ns := req.Username[:idx]
deviceID := req.Username[idx+1:]
deviceTopic := ns + "/telemetry/" + deviceID
switch {
case req.Action == "publish" && req.Topic == deviceTopic:
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "allow"})
case req.Action == "subscribe" && (req.Topic == deviceTopic || req.Topic == "#"):
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "allow"})
default:
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
}
}
// bridgeACLRules — ACL для внутреннего bridge: subscribe на все telemetry-топики.
func bridgeACLRules() []aclRule {
return []aclRule{
{Permission: "allow", Action: "subscribe", Topic: "+/telemetry/+"},
{Permission: "deny", Action: "all", Topic: "#"},
}
}
// deviceACLRules — ACL для устройства: только свой топик телеметрии.
func deviceACLRules(ns, deviceID string) []aclRule {
topic := ns + "/telemetry/" + deviceID
return []aclRule{
{Permission: "allow", Action: "publish", Topic: topic},
{Permission: "allow", Action: "subscribe", Topic: topic},
{Permission: "deny", Action: "all", Topic: "#"},
}
}
+52
View File
@@ -0,0 +1,52 @@
// sqsstats.go — сбор статистики очереди shared-SQS для админ-страницы.
package handler
import (
"context"
"fmt"
"strconv"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/sqs"
sqstypes "github.com/aws/aws-sdk-go-v2/service/sqs/types"
)
// iotAdminSQSStats — информация об очереди для мониторинга.
type iotAdminSQSStats struct {
ApproximateMessages int64 `json:"approximate_messages"`
ApproximateMessagesNotVisible int64 `json:"approximate_messages_not_visible"`
Error string `json:"error,omitempty"`
}
// collectSQSStats получает ApproximateNumberOfMessages из очереди телеметрии.
func (h *Handler) collectSQSStats(ctx context.Context) iotAdminSQSStats {
if h.SQS == nil {
return iotAdminSQSStats{Error: "SQS client not configured"}
}
queueUrlOut, err := h.SQS.GetQueueUrl(ctx, &sqs.GetQueueUrlInput{
QueueName: aws.String(h.Cfg.SQSQueueName),
})
if err != nil {
return iotAdminSQSStats{Error: fmt.Sprintf("GetQueueUrl: %v", err)}
}
attrsOut, err := h.SQS.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{
QueueUrl: queueUrlOut.QueueUrl,
AttributeNames: []sqstypes.QueueAttributeName{
sqstypes.QueueAttributeNameApproximateNumberOfMessages,
sqstypes.QueueAttributeNameApproximateNumberOfMessagesNotVisible,
},
})
if err != nil {
return iotAdminSQSStats{Error: fmt.Sprintf("GetQueueAttributes: %v", err)}
}
approxMsg, _ := strconv.ParseInt(attrsOut.Attributes["ApproximateNumberOfMessages"], 10, 64)
approxNotVisible, _ := strconv.ParseInt(attrsOut.Attributes["ApproximateNumberOfMessagesNotVisible"], 10, 64)
return iotAdminSQSStats{
ApproximateMessages: approxMsg,
ApproximateMessagesNotVisible: approxNotVisible,
}
}
+43
View File
@@ -0,0 +1,43 @@
// telemetry.go — REST-чтение телеметрии из per-tenant PostgreSQL.
//
// Endpoint: GET /v1/namespaces/{ns}/iot/telemetry?device_id={id}&limit={n}
package handler
import (
"net/http"
"strconv"
"gitea.services.ngcloud.ru/Nail/IoT/internal/storage/iotpg"
)
// ListIoTTelemetry — GET /v1/namespaces/{ns}/iot/telemetry.
func (h *Handler) ListIoTTelemetry(w http.ResponseWriter, r *http.Request) {
if h.IoTPG == nil {
writeJSON(w, http.StatusServiceUnavailable, errResp("IoT telemetry storage not configured"))
return
}
ns := pathVar(r, "namespace")
deviceID := r.URL.Query().Get("device_id")
limit := 50
if ls := r.URL.Query().Get("limit"); ls != "" {
if n, err := strconv.Atoi(ls); err == nil && n > 0 {
limit = n
}
}
rows, err := h.IoTPG.QueryTelemetry(r.Context(), ns, deviceID, limit)
if err != nil {
h.Log.Error("query IoT telemetry", "namespace", ns, "device", deviceID, "err", err)
writeJSON(w, http.StatusInternalServerError, errResp("failed to query telemetry"))
return
}
if rows == nil {
rows = []iotpg.TelemetryRow{}
}
writeJSON(w, http.StatusOK, map[string]any{
"items": rows,
"count": len(rows),
})
}
+101
View File
@@ -0,0 +1,101 @@
// Package middleware — HTTP-промежуточные слои API.
package middleware
import (
"encoding/base64"
"log/slog"
"net/http"
"strings"
)
// Auth — проверка Bearer-токена.
//
// authTestMode (env AUTH_TEST_MODE, дефолт false):
// - true — принимается любая строка без пробелов (для локальных тестов);
// - false — структурная проверка JWT (sub + exp), как в старом коде.
//
// В новой архитектуре подпись JWT не проверяется (как и раньше): внешний
// периметр обеспечивает платформа, полная валидация — на стороне шлюза.
func Auth(authTestMode bool, log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
header := r.Header.Get("Authorization")
if header == "" {
log.Warn("auth: missing authorization header", "remote", r.RemoteAddr, "path", r.URL.Path)
http.Error(w, `{"error":"authorization required"}`, http.StatusUnauthorized)
return
}
parts := strings.SplitN(header, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "bearer") {
log.Warn("auth: invalid authorization format", "remote", r.RemoteAddr)
http.Error(w, `{"error":"invalid authorization format, use Bearer <token>"}`, http.StatusUnauthorized)
return
}
token := parts[1]
if authTestMode && isPlainToken(token) {
log.Info("auth: test mode — plain token accepted", "remote", r.RemoteAddr, "path", r.URL.Path)
next.ServeHTTP(w, r)
return
}
if err := validateJWT(token); err != nil {
log.Warn("auth: invalid token", "remote", r.RemoteAddr, "path", r.URL.Path, "reason", err.Error())
http.Error(w, `{"error":"invalid token"}`, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// isPlainToken — непустая строка без пробелов, не похожая на JWT (три части через точку).
func isPlainToken(token string) bool {
if token == "" || strings.ContainsAny(token, " \t\n\r") {
return false
}
return len(strings.Split(token, ".")) != 3
}
// jwtError — структурная ошибка JWT.
type jwtError struct{ msg string }
func (e *jwtError) Error() string { return e.msg }
// validateJWT проверяет структуру JWT: три части, корректный payload, sub и exp.
// Подпись НЕ проверяется — см. комментарий пакета.
func validateJWT(token string) error {
jwtParts := strings.Split(token, ".")
if len(jwtParts) != 3 {
return &jwtError{"not a JWT: expected 3 parts"}
}
payload := jwtParts[1]
switch len(payload) % 4 {
case 2:
payload += "=="
case 3:
payload += "="
}
decoded, err := base64.URLEncoding.DecodeString(payload)
if err != nil {
decoded, err = base64.StdEncoding.DecodeString(payload)
}
if err != nil {
return &jwtError{"cannot decode JWT payload"}
}
var claims struct {
Sub string `json:"sub"`
Exp float64 `json:"exp"`
}
if err := jsonUnmarshal(decoded, &claims); err != nil {
return &jwtError{"cannot parse JWT payload"}
}
if claims.Sub == "" {
return &jwtError{"JWT missing sub claim"}
}
if claims.Exp > 0 {
if now := float64(timeNow().Unix()); claims.Exp < now {
return &jwtError{"JWT expired"}
}
}
return nil
}
@@ -0,0 +1,15 @@
package middleware
import (
"encoding/json"
"time"
)
// jsonUnmarshal и timeNow вынесены для простоты тестирования.
func jsonUnmarshal(data []byte, v any) error {
return json.Unmarshal(data, v)
}
func timeNow() time.Time {
return time.Now()
}
@@ -0,0 +1,35 @@
// Package middleware — HTTP-промежуточные слои API.
package middleware
import (
"log/slog"
"net/http"
"time"
)
// responseWriter перехватывает статус ответа для логирования.
type responseWriter struct {
http.ResponseWriter
status int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.status = code
rw.ResponseWriter.WriteHeader(code)
}
// Logging логирует каждый HTTP-запрос: метод, путь, статус, длительность.
func Logging(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rw := &responseWriter{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(rw, r)
log.Info("http",
"method", r.Method,
"path", r.URL.Path,
"status", rw.status,
"duration_ms", time.Since(start).Milliseconds(),
"remote", r.RemoteAddr,
)
})
}
+70
View File
@@ -0,0 +1,70 @@
// Package api — HTTP-сервер монолита: маршруты, CORS, health.
package api
import (
"log/slog"
"net/http"
"github.com/gorilla/mux"
"gitea.services.ngcloud.ru/Nail/IoT/internal/service/api/handler"
"gitea.services.ngcloud.ru/Nail/IoT/internal/service/api/middleware"
)
// corsMiddleware добавляет CORS-заголовки (консоль и API на одном домене платформы).
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
// NewRouter собирает все маршруты сервиса.
func NewRouter(h *handler.Handler, log *slog.Logger, authTestMode bool, version string) http.Handler {
r := mux.NewRouter()
// Health — для платформенных проверок контейнера.
r.HandleFunc("/health", healthHandler(version)).Methods(http.MethodGet)
r.HandleFunc("/healthz", healthHandler(version)).Methods(http.MethodGet)
// UI — публичные страницы (без данных).
r.HandleFunc("/console", ServeIoTConsole).Methods(http.MethodGet)
r.HandleFunc("/iot-admin", ServeIoTAdmin).Methods(http.MethodGet)
// Админ-статистика — свой Bearer-токен.
r.HandleFunc("/iot-admin/stats", h.AdminStats).Methods(http.MethodGet)
// MQTT auth/acl — для EMQX, без JWT.
r.HandleFunc("/internal/mqtt/auth", h.MQTTAuth).Methods(http.MethodPost)
r.HandleFunc("/internal/mqtt/acl", h.MQTTAcl).Methods(http.MethodPost)
// /v1 — под JWT.
v1 := r.PathPrefix("/v1").Subrouter()
v1.HandleFunc("/namespaces/{namespace}/iot/devices", h.ListIoTDevices).Methods(http.MethodGet)
v1.HandleFunc("/namespaces/{namespace}/iot/devices", h.CreateIoTDevice).Methods(http.MethodPost)
v1.HandleFunc("/namespaces/{namespace}/iot/devices/{name}", h.GetIoTDevice).Methods(http.MethodGet)
v1.HandleFunc("/namespaces/{namespace}/iot/devices/{name}", h.DeleteIoTDevice).Methods(http.MethodDelete)
v1.HandleFunc("/namespaces/{namespace}/iot/devices/{name}", h.UpdateIoTDevice).Methods(http.MethodPatch)
v1.HandleFunc("/namespaces/{namespace}/iot/telemetry", h.ListIoTTelemetry).Methods(http.MethodGet)
v1.Use(func(next http.Handler) http.Handler {
return middleware.Auth(authTestMode, log, next)
})
return corsMiddleware(middleware.Logging(log, r))
}
// healthHandler отдаёт статус сервиса и версию (для платформы).
func healthHandler(version string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok","version":"` + version + `"}`))
}
}
+547
View File
@@ -0,0 +1,547 @@
<!DOCTYPE html>
<!-- Создано: 2026-04-06
iot-admin.html — страница администратора IoT pipeline.
Показывает: PostgreSQL stats per tenant, Kafka consumer lag, K8s pod statuses.
Auth: ADMIN_STATS_TOKEN вводится вручную и хранится в sessionStorage.
Раздаётся по GET /iot-admin (go:embed в бинарнике оператора).
НЕ для конечных пользователей — только для администратора платформы. -->
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nubes IoT Admin</title>
<link rel="icon" href="https://terra.k8c.ru/docs/nubes/nubes/2.0.2/30_registry/assets/favicon.png">
<style>
/* Nubes brand palette — те же цвета что в iot-console.html */
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif;
background: #001120; color: #e2ecf6; min-height: 100vh;
}
/* Navbar */
.navbar {
background: #001C34; border-bottom: 1px solid #0b2d50;
padding: 0 28px; height: 58px;
display: flex; align-items: center; gap: 14px;
}
.navbar-logo { display: flex; align-items: center; gap: 10px; text-decoration: none; }
.navbar-logo img { height: 18px; filter: brightness(0) invert(1); }
.navbar-logo-sep { width: 1px; height: 18px; background: #1a4a73; margin: 0 4px; }
.navbar-title { font-size: 15px; font-weight: 600; color: #e2ecf6; }
.navbar-badge {
background: #2d1a00; border: 1px solid #7a3a00; color: #f0a030;
font-size: 10px; font-weight: 700; padding: 2px 7px; border-radius: 4px;
letter-spacing: 0.5px; text-transform: uppercase;
}
.navbar-spacer { flex: 1; }
.navbar-refresh {
background: #0f3a60; border: 1px solid #1a5a8a; color: #7fc8f8;
padding: 6px 14px; border-radius: 6px; font-size: 13px; cursor: pointer;
transition: background 0.15s;
}
.navbar-refresh:hover { background: #1a5080; }
.navbar-refresh:disabled { opacity: 0.4; cursor: not-allowed; }
/* Layout */
.container { max-width: 1280px; margin: 0 auto; padding: 28px 24px; }
/* Auth box */
.auth-box {
background: #001929; border: 1px solid #0b2d50; border-radius: 12px;
padding: 40px; max-width: 480px; margin: 80px auto;
display: flex; flex-direction: column; gap: 16px;
}
.auth-box h2 { font-size: 20px; font-weight: 600; color: #7fc8f8; }
.auth-box p { font-size: 13px; color: #6b8eaa; }
.auth-input {
background: #001120; border: 1px solid #1a4a73; color: #e2ecf6;
padding: 10px 14px; border-radius: 8px; font-size: 14px; font-family: monospace;
width: 100%; outline: none;
}
.auth-input:focus { border-color: #1a7fd4; }
.auth-btn {
background: #1a7fd4; border: none; color: #fff;
padding: 10px 20px; border-radius: 8px; font-size: 14px; cursor: pointer;
font-weight: 600; transition: background 0.15s;
}
.auth-btn:hover { background: #1a6ab8; }
.auth-error { color: #f87171; font-size: 13px; }
/* Section header */
.section-header {
display: flex; align-items: center; gap: 10px;
margin-bottom: 16px; padding-bottom: 10px;
border-bottom: 1px solid #0b2d50;
}
.section-icon { width: 20px; height: 20px; opacity: 0.7; }
.section-title { font-size: 16px; font-weight: 600; color: #a0c4e8; }
.section { margin-bottom: 32px; }
/* Cards grid */
.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 16px; }
/* Stat card */
.card {
background: #001929; border: 1px solid #0b2d50; border-radius: 10px;
padding: 20px;
}
.card-title { font-size: 12px; color: #6b8eaa; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 8px; }
.card-value { font-size: 28px; font-weight: 700; color: #e2ecf6; }
.card-sub { font-size: 12px; color: #6b8eaa; margin-top: 4px; }
.card-accent { color: #1a7fd4; }
.card-warn { color: #f59e0b; }
.card-ok { color: #34d399; }
.card-err { color: #f87171; }
/* Pod status card */
.pod-card {
background: #001929; border: 1px solid #0b2d50; border-radius: 10px;
padding: 20px; display: flex; flex-direction: column; gap: 8px;
}
.pod-name { font-size: 13px; font-weight: 600; color: #7fc8f8; font-family: monospace; }
.pod-row { display: flex; justify-content: space-between; font-size: 12px; }
.pod-label { color: #6b8eaa; }
.pod-val { color: #e2ecf6; }
.badge {
display: inline-block; padding: 2px 8px; border-radius: 4px;
font-size: 11px; font-weight: 700;
}
.badge-ok { background: #052e16; color: #34d399; border: 1px solid #064e3b; }
.badge-warn { background: #2d1c00; color: #f59e0b; border: 1px solid #4d3000; }
.badge-err { background: #300; color: #f87171; border: 1px solid #500; }
/* Tenant table */
.tenant-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.tenant-table th {
text-align: left; padding: 8px 12px; color: #6b8eaa;
border-bottom: 1px solid #0b2d50; font-weight: 600; font-size: 11px;
text-transform: uppercase; letter-spacing: 0.3px;
}
.tenant-table td { padding: 10px 12px; border-bottom: 1px solid #071a28; vertical-align: top; }
.tenant-table tr:last-child td { border-bottom: none; }
.tenant-table tr:hover td { background: rgba(26,127,212,0.05); }
.ns-tag {
font-family: monospace; font-size: 12px; color: #7fc8f8;
background: #0b2d50; padding: 2px 6px; border-radius: 4px;
}
.num-big { font-size: 16px; font-weight: 600; color: #e2ecf6; }
.num-small { font-size: 12px; color: #6b8eaa; }
/* Latest msgs mini list */
.latest-list { display: flex; flex-direction: column; gap: 4px; }
.latest-item {
background: #001120; border: 1px solid #0b2d50; border-radius: 6px;
padding: 6px 10px; font-size: 11px;
}
.latest-dev { color: #7fc8f8; font-weight: 600; }
.latest-ts { color: #6b8eaa; margin-left: 6px; }
.latest-payload { color: #a0c4e8; margin-top: 2px; word-break: break-all; font-family: monospace; }
/* Last updated */
.last-updated { font-size: 12px; color: #2d5070; text-align: center; margin-top: 16px; }
/* Status dot */
.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; }
.dot-ok { background: #34d399; }
.dot-warn { background: #f59e0b; }
.dot-err { background: #f87171; }
/* Kafka lag bar */
.lag-bar-wrap { background: #001120; border-radius: 4px; height: 6px; margin-top: 8px; overflow: hidden; }
.lag-bar { height: 100%; border-radius: 4px; transition: width 0.5s; min-width: 2px; }
.lag-bar-ok { background: #34d399; }
.lag-bar-warn { background: #f59e0b; }
/* Spinner */
.spinner {
border: 3px solid #0b2d50; border-top-color: #1a7fd4;
border-radius: 50%; width: 32px; height: 32px;
animation: spin 0.8s linear infinite;
margin: 60px auto;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* Error banner */
.error-banner {
background: #1a0000; border: 1px solid #5a0000; color: #f87171;
padding: 12px 16px; border-radius: 8px; font-size: 13px; margin-bottom: 20px;
}
/* Auto-refresh indicator */
.refresh-timer {
font-size: 11px; color: #2d5070; display: flex; align-items: center; gap: 6px;
}
.refresh-progress {
width: 60px; height: 2px; background: #0b2d50; border-radius: 2px; overflow: hidden;
}
.refresh-bar {
height: 100%; background: #1a7fd4; border-radius: 2px;
transition: width 1s linear;
}
</style>
</head>
<body>
<!-- Navbar -->
<nav class="navbar">
<a class="navbar-logo" href="#" aria-label="Nubes">
<img src="https://terra.k8c.ru/docs/nubes/nubes/2.0.2/30_registry/assets/logo.svg" alt="Nubes">
</a>
<div class="navbar-logo-sep"></div>
<span class="navbar-title">IoT Admin</span>
<span class="navbar-badge">Admin Only</span>
<div class="navbar-spacer"></div>
<div class="refresh-timer" id="refreshTimer" style="display:none">
<span id="refreshCountdown">30</span>s
<div class="refresh-progress"><div class="refresh-bar" id="refreshBar" style="width:100%"></div></div>
</div>
<button class="navbar-refresh" id="btnRefresh" onclick="loadStats()" disabled>Обновить</button>
</nav>
<!-- Main content -->
<div class="container">
<!-- Auth box (показывается до ввода токена) -->
<div class="auth-box" id="authBox">
<h2>Доступ для администратора</h2>
<p>Введите ADMIN_STATS_TOKEN для просмотра статистики IoT pipeline.</p>
<input class="auth-input" id="tokenInput" type="password"
placeholder="Bearer token..." autocomplete="off"
onkeydown="if(event.key==='Enter') doAuth()">
<button class="auth-btn" onclick="doAuth()">Войти</button>
<div class="auth-error" id="authError" style="display:none"></div>
</div>
<!-- Контент (показывается после авторизации) -->
<div id="mainContent" style="display:none">
<div class="error-banner" id="errorBanner" style="display:none"></div>
<!-- Spinner при загрузке -->
<div class="spinner" id="spinner"></div>
<!-- Данные -->
<div id="dataContent" style="display:none">
<!-- Kafka -->
<div class="section">
<div class="section-header">
<svg class="section-icon" viewBox="0 0 24 24" fill="none" stroke="#7fc8f8" stroke-width="2">
<path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/>
</svg>
<span class="section-title">Kafka</span>
</div>
<div class="cards" id="kafkaCards"></div>
</div>
<!-- K8s Pods -->
<div class="section">
<div class="section-header">
<svg class="section-icon" viewBox="0 0 24 24" fill="none" stroke="#7fc8f8" stroke-width="2">
<rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/>
</svg>
<span class="section-title">Pods</span>
</div>
<div class="cards" id="podCards"></div>
</div>
<!-- PostgreSQL per tenant -->
<div class="section">
<div class="section-header">
<svg class="section-icon" viewBox="0 0 24 24" fill="none" stroke="#7fc8f8" stroke-width="2">
<ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14c0 1.66 4.03 3 9 3s9-1.34 9-3V5"/>
<path d="M3 12c0 1.66 4.03 3 9 3s9-1.34 9-3"/>
</svg>
<span class="section-title">PostgreSQL — Telemetry</span>
</div>
<div class="cards" style="margin-bottom:16px" id="pgSummaryCards"></div>
<div style="background:#001929;border:1px solid #0b2d50;border-radius:10px;overflow:auto">
<table class="tenant-table" id="tenantTable">
<thead>
<tr>
<th>Namespace</th>
<th>Total</th>
<th>Last 1h</th>
<th>Last 24h</th>
<th>Последние сообщения</th>
</tr>
</thead>
<tbody id="tenantTableBody"></tbody>
</table>
</div>
</div>
<div class="last-updated" id="lastUpdated"></div>
</div>
</div>
</div>
<script>
// ── State ──────────────────────────────────────────────────────────────────
const API_BASE = window.location.origin;
let adminToken = sessionStorage.getItem('iot_admin_token') || '';
let refreshInterval = null;
let refreshCountdown = 30;
// ── Auth ───────────────────────────────────────────────────────────────────
function doAuth() {
const input = document.getElementById('tokenInput').value.trim();
if (!input) return;
adminToken = input;
sessionStorage.setItem('iot_admin_token', adminToken);
document.getElementById('authBox').style.display = 'none';
document.getElementById('mainContent').style.display = 'block';
loadStats();
}
function showAuthError(msg) {
const el = document.getElementById('authError');
el.textContent = msg;
el.style.display = 'block';
// Сбрасываем токен — он не подошёл
adminToken = '';
sessionStorage.removeItem('iot_admin_token');
document.getElementById('authBox').style.display = 'block';
document.getElementById('mainContent').style.display = 'none';
if (refreshInterval) { clearInterval(refreshInterval); refreshInterval = null; }
document.getElementById('refreshTimer').style.display = 'none';
}
// Если токен уже в sessionStorage — пропускаем auth box
if (adminToken) {
document.getElementById('authBox').style.display = 'none';
document.getElementById('mainContent').style.display = 'block';
document.getElementById('spinner').style.display = 'block';
}
// ── Load stats ─────────────────────────────────────────────────────────────
async function loadStats() {
if (!adminToken) return;
document.getElementById('btnRefresh').disabled = true;
document.getElementById('spinner').style.display = 'block';
document.getElementById('dataContent').style.display = 'none';
document.getElementById('errorBanner').style.display = 'none';
resetRefreshTimer();
try {
const resp = await fetch(`${API_BASE}/iot-admin/stats`, {
headers: { 'Authorization': `Bearer ${adminToken}` }
});
if (resp.status === 401 || resp.status === 503) {
const body = await resp.json().catch(() => ({}));
showAuthError(body.error || 'Ошибка авторизации');
document.getElementById('spinner').style.display = 'none';
return;
}
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}`);
}
const data = await resp.json();
renderAll(data);
document.getElementById('spinner').style.display = 'none';
document.getElementById('dataContent').style.display = 'block';
document.getElementById('refreshTimer').style.display = 'flex';
document.getElementById('lastUpdated').textContent =
'Обновлено: ' + new Date(data.collected_at).toLocaleTimeString('ru-RU');
setupAutoRefresh();
} catch (e) {
document.getElementById('spinner').style.display = 'none';
showBanner('Ошибка загрузки данных: ' + e.message);
document.getElementById('dataContent').style.display = 'block';
} finally {
document.getElementById('btnRefresh').disabled = false;
}
}
function showBanner(msg) {
const el = document.getElementById('errorBanner');
el.textContent = msg;
el.style.display = 'block';
}
// ── Auto-refresh ───────────────────────────────────────────────────────────
function setupAutoRefresh() {
if (refreshInterval) return; // уже запущен
refreshInterval = setInterval(() => {
refreshCountdown--;
document.getElementById('refreshCountdown').textContent = refreshCountdown;
const pct = (refreshCountdown / 30) * 100;
document.getElementById('refreshBar').style.width = pct + '%';
if (refreshCountdown <= 0) {
clearInterval(refreshInterval);
refreshInterval = null;
loadStats();
}
}, 1000);
}
function resetRefreshTimer() {
if (refreshInterval) { clearInterval(refreshInterval); refreshInterval = null; }
refreshCountdown = 30;
document.getElementById('refreshCountdown').textContent = '30';
document.getElementById('refreshBar').style.width = '100%';
}
// ── Render ─────────────────────────────────────────────────────────────────
function renderAll(data) {
renderKafka(data.kafka || {});
renderPods(data.pods || {});
renderPostgres(data.postgres || {});
}
// Kafka section
function renderKafka(kafka) {
const el = document.getElementById('kafkaCards');
if (kafka.error) {
el.innerHTML = `<div class="card"><div class="card-title">Ошибка</div>
<div class="card-value card-err" style="font-size:14px">${esc(kafka.error)}</div></div>`;
return;
}
const lag = kafka.consumer_lag || 0;
const latest = kafka.latest_offset || 0;
const committed = kafka.committed_offset || 0;
const lagClass = lag === 0 ? 'card-ok' : lag < 100 ? 'card-warn' : 'card-err';
const barClass = lag === 0 ? 'lag-bar-ok' : 'lag-bar-warn';
const barWidth = latest > 0 ? Math.max(2, Math.round((committed / latest) * 100)) : 100;
el.innerHTML = `
<div class="card">
<div class="card-title">Consumer Lag</div>
<div class="card-value ${lagClass}">${lag}</div>
<div class="card-sub">iot-pg-consumer / iot.telemetry</div>
<div class="lag-bar-wrap"><div class="lag-bar ${barClass}" style="width:${barWidth}%"></div></div>
</div>
<div class="card">
<div class="card-title">Latest Offset (всего прошло)</div>
<div class="card-value card-accent">${latest.toLocaleString()}</div>
<div class="card-sub">Kafka log end offset</div>
</div>
<div class="card">
<div class="card-title">Committed Offset</div>
<div class="card-value">${committed.toLocaleString()}</div>
<div class="card-sub">Consumer обработал</div>
</div>`;
}
// Pods section
function renderPods(pods) {
const el = document.getElementById('podCards');
el.innerHTML = '';
const labels = {
'iot-mqtt-bridge': 'MQTT Bridge',
'iot-kafka-consumer': 'Kafka Consumer'
};
for (const [key, pod] of Object.entries(pods)) {
const title = labels[key] || key;
if (pod.error || pod.status === 'not found') {
el.innerHTML += `
<div class="pod-card">
<div class="pod-name">${esc(title)}</div>
<div style="color:#f87171;font-size:12px">${esc(pod.error || 'Pod not found')}</div>
</div>`;
continue;
}
const readyBadge = pod.ready
? '<span class="badge badge-ok">Ready</span>'
: '<span class="badge badge-warn">Not Ready</span>';
const restartColor = pod.restarts > 5 ? 'card-err' : pod.restarts > 0 ? 'card-warn' : 'card-ok';
el.innerHTML += `
<div class="pod-card">
<div class="pod-name">
<span class="dot dot-${pod.ready ? 'ok' : 'warn'}"></span>${esc(title)}
</div>
<div class="pod-row"><span class="pod-label">Pod</span><span class="pod-val" style="font-family:monospace;font-size:11px">${esc(pod.name)}</span></div>
<div class="pod-row"><span class="pod-label">Phase</span><span class="pod-val">${esc(pod.phase)} ${readyBadge}</span></div>
<div class="pod-row"><span class="pod-label">Restarts</span><span class="pod-val ${restartColor}">${pod.restarts}</span></div>
<div class="pod-row"><span class="pod-label">Age</span><span class="pod-val">${esc(pod.age)}</span></div>
</div>`;
}
}
// Postgres section
function renderPostgres(pg) {
const summaryEl = document.getElementById('pgSummaryCards');
const tbodyEl = document.getElementById('tenantTableBody');
if (!pg.reachable) {
summaryEl.innerHTML = `<div class="card"><div class="card-title">Ошибка</div>
<div class="card-value card-err" style="font-size:14px">${esc(pg.error || 'Unreachable')}</div></div>`;
tbodyEl.innerHTML = '';
return;
}
const tenants = pg.tenants || [];
const totalAll = pg.total_all || 0;
summaryEl.innerHTML = `
<div class="card">
<div class="card-title">Всего записей</div>
<div class="card-value card-accent">${totalAll.toLocaleString()}</div>
<div class="card-sub">Все tenant, iot_telemetry</div>
</div>
<div class="card">
<div class="card-title">Tenant-ов</div>
<div class="card-value">${tenants.length}</div>
<div class="card-sub">Активных namespace</div>
</div>`;
tbodyEl.innerHTML = tenants.map(t => {
if (t.error) {
return `<tr><td><span class="ns-tag">${esc(t.namespace)}</span></td>
<td colspan="4" style="color:#f87171">${esc(t.error)}</td></tr>`;
}
const latest = (t.latest || []).slice(0, 3);
const latestHtml = latest.length === 0
? '<span style="color:#2d5070">нет данных</span>'
: `<div class="latest-list">${latest.map(row => `
<div class="latest-item">
<span class="latest-dev">${esc(row.device_id)}</span>
<span class="latest-ts">${formatTs(row.ts)}</span>
<div class="latest-payload">${esc(truncate(JSON.stringify(row.payload), 80))}</div>
</div>`).join('')}</div>`;
return `<tr>
<td><span class="ns-tag">${esc(t.namespace)}</span><br>
<span style="font-size:11px;color:#2d5070">${esc(t.db_name)}</span></td>
<td><span class="num-big">${(t.total||0).toLocaleString()}</span></td>
<td><span class="num-small">${(t.last_1h||0).toLocaleString()}</span></td>
<td><span class="num-small">${(t.last_24h||0).toLocaleString()}</span></td>
<td>${latestHtml}</td>
</tr>`;
}).join('');
}
// ── Utils ──────────────────────────────────────────────────────────────────
function esc(str) {
if (str == null) return '';
return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
function truncate(str, len) {
if (!str) return '';
return str.length > len ? str.slice(0, len) + '…' : str;
}
function formatTs(ts) {
if (!ts) return '';
try {
const d = new Date(ts);
return d.toLocaleTimeString('ru-RU', {hour:'2-digit', minute:'2-digit', second:'2-digit'});
} catch { return ts; }
}
// ── Init ───────────────────────────────────────────────────────────────────
if (adminToken) {
loadStats();
}
</script>
</body>
</html>
File diff suppressed because it is too large Load Diff