feat: перенос IoT managed service из sless в отдельную репу

Компоненты:
- iot-operator: controller-manager (IoTDevice CRD) + REST API (порт 9090)
- mqtt-bridge: MQTT (EMQX) → Kafka bridge
- kafka-consumer: Kafka → Postgres pipeline

Модуль: gitea.services.ngcloud.ru/Nail/IoT
Все 3 бинарника собираются, import paths адаптированы.
This commit is contained in:
Naeel
2026-04-12 14:29:43 +03:00
commit 1a94241c62
31 changed files with 7023 additions and 0 deletions
+27
View File
@@ -0,0 +1,27 @@
// Создано: 2026-04-06
// admin_embed.go — встраивает HTML страницы администратора IoT в бинарник через go:embed.
//
// Страница /iot-admin доступна без JWT — данные не содержит.
// Все данные загружаются через /iot-admin/stats (защищён ADMIN_STATS_TOKEN).
// Почему go:embed: единый деплой, нет отдельных pod-ов, нет nginx drift.
package api
import (
_ "embed"
"net/http"
)
// iotAdminHTML — бинарное содержимое страницы администратора IoT, встроенное при сборке.
//
//go:embed ui/iot-admin.html
var iotAdminHTML []byte
// ServeIoTAdmin обрабатывает GET /iot-admin — отдаёт HTML страницу администратора.
// Auth не нужен для HTML — сама страница ничего не содержит, только UI оболочка.
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)
}
+32
View File
@@ -0,0 +1,32 @@
// Создано: 2026-04-04
// console_embed.go — встраивает HTML-файл IoT консоли в бинарник оператора через go:embed.
//
// Файл ui/iot-console.html встраивается при компиляции и раздаётся по GET /console.
// Путь /console доступен без JWT — это публичная статическая страница.
// Авторизация в UI происходит через Bearer-токен который пользователь вводит сам.
//
// Почему go:embed а не отдельный nginx: нет лишних pod'ов, единый деплой, нет drift.
// Почему /console без auth: HTML файл не содержит секретов, токен вводит пользователь.
package api
import (
_ "embed"
"net/http"
)
// iotConsoleHTML — бинарное содержимое IoT консоли, встроенное при сборке.
// При изменении HTML-файла достаточно пересобрать оператор.
//
//go:embed ui/iot-console.html
var iotConsoleHTML []byte
// ServeIoTConsole обрабатывает GET /console — отдаёт HTML SPA без JWT-проверки.
// Браузер кэширует HTML; API-запросы из JS защищены Bearer-токеном.
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)
}
+61
View File
@@ -0,0 +1,61 @@
// Создано: 2026-04-12
// Handler — контейнер зависимостей для IoT REST handlers.
// Упрощённая версия из sless — только IoT-специфичные поля.
//
// Бизнес-логика:
// - iot_device_handler.go — CRUD устройств + MQTT auth
// - iot_telemetry_handler.go — чтение телеметрии
// - iot_admin_stats_handler.go — админ-статистика
package handler
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/gorilla/mux"
"k8s.io/apimachinery/pkg/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"gitea.services.ngcloud.ru/Nail/IoT/internal/storage/iotpg"
)
// defaultNamespace — fallback namespace для dev/тестов.
const defaultNamespace = "default"
// Handler содержит зависимости для всех IoT REST-обработчиков.
type Handler struct {
K8s client.Client
Scheme *runtime.Scheme
// IoTPG — хранилище IoT телеметрии (per-tenant Postgres). nil если IOT_PG_DSN не задан.
IoTPG *iotpg.IoTPostgresStore
// KafkaBrokers — адреса Kafka брокеров для чтения consumer lag на admin странице.
KafkaBrokers string
Log *slog.Logger
}
// 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]
}
// namespace читает {namespace} из пути URL.
func namespace(r *http.Request) string {
if ns := mux.Vars(r)["namespace"]; ns != "" {
return ns
}
return defaultNamespace
}
@@ -0,0 +1,214 @@
// Создано: 2026-04-06
// iot_admin_stats_handler.go — handler для страницы администратора IoT.
//
// Endpoints:
// GET /iot-admin/stats — JSON с агрегированной статистикой (защищён ADMIN_STATS_TOKEN)
//
// Источники данных:
// - PostgreSQL (IoTPG): counts per tenant, last 1h/24h, latest rows
// - Kafka: consumer lag (latest offset - committed offset для group iot-pg-consumer)
// - K8s: статус подов iot-mqtt-bridge и iot-kafka-consumer
//
// Авторизация: Bearer из env ADMIN_STATS_TOKEN.
// Если ADMIN_STATS_TOKEN не задан — endpoint возвращает 503.
package handler
import (
"context"
"fmt"
"net/http"
"os"
"strings"
"time"
kafka "github.com/segmentio/kafka-go"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
// iotAdminPodStatus — краткая информация о k8s pod для страницы администратора.
type iotAdminPodStatus struct {
Name string `json:"name"`
Phase string `json:"phase"`
Ready bool `json:"ready"`
Restarts int32 `json:"restarts"`
Age string `json:"age"`
}
// iotAdminKafkaStats — информация о Kafka топике и consumer lag.
type iotAdminKafkaStats struct {
LatestOffset int64 `json:"latest_offset"`
CommittedOffset int64 `json:"committed_offset"`
ConsumerLag int64 `json:"consumer_lag"`
Error string `json:"error,omitempty"`
}
// AdminStats обрабатывает GET /iot-admin/stats.
// Проверяет Bearer-токен из ADMIN_STATS_TOKEN, затем собирает и возвращает статистику.
func (h *Handler) AdminStats(w http.ResponseWriter, r *http.Request) {
adminToken := os.Getenv("ADMIN_STATS_TOKEN")
if adminToken == "" {
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 ") != adminToken {
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"}
}
// Kafka: consumer lag для топика iot.telemetry / группы iot-pg-consumer
result["kafka"] = h.collectIotKafkaLag(ctx)
// K8s: статус подов bridge и consumer
result["pods"] = h.collectIotPodStatuses(ctx)
writeJSON(w, http.StatusOK, result)
}
// collectIotKafkaLag получает latest offset топика и committed offset consumer group,
// вычисляет lag = latest - committed.
// Topic: "iot.telemetry", Consumer Group: "iot-pg-consumer".
func (h *Handler) collectIotKafkaLag(ctx context.Context) iotAdminKafkaStats {
if h.KafkaBrokers == "" {
return iotAdminKafkaStats{Error: "KAFKA_BROKERS not configured"}
}
brokers := strings.Split(h.KafkaBrokers, ",")
brokerAddr := kafka.TCP(brokers...)
kc := &kafka.Client{
Addr: brokerAddr,
Timeout: 5 * time.Second,
}
const topic = "iot.telemetry"
const group = "iot-pg-consumer"
// Получаем latest offset (конец лога — сколько всего сообщений прошло)
offsetsResp, err := kc.ListOffsets(ctx, &kafka.ListOffsetsRequest{
Addr: brokerAddr,
Topics: map[string][]kafka.OffsetRequest{
topic: {kafka.LastOffsetOf(0)},
},
})
if err != nil {
return iotAdminKafkaStats{Error: fmt.Sprintf("list offsets: %v", err)}
}
var latestOffset int64
if partitions, ok := offsetsResp.Topics[topic]; ok && len(partitions) > 0 {
if partitions[0].Error == nil {
latestOffset = partitions[0].LastOffset
}
}
// Получаем committed offset consumer group (что consumer уже обработал)
fetchResp, err := kc.OffsetFetch(ctx, &kafka.OffsetFetchRequest{
Addr: brokerAddr,
GroupID: group,
Topics: map[string][]int{topic: {0}},
})
if err != nil {
return iotAdminKafkaStats{
LatestOffset: latestOffset,
Error: fmt.Sprintf("offset fetch: %v", err),
}
}
var committedOffset int64
if partitions, ok := fetchResp.Topics[topic]; ok && len(partitions) > 0 {
if partitions[0].Error == nil {
committedOffset = partitions[0].CommittedOffset
}
}
lag := latestOffset - committedOffset
if lag < 0 {
lag = 0
}
return iotAdminKafkaStats{
LatestOffset: latestOffset,
CommittedOffset: committedOffset,
ConsumerLag: lag,
}
}
// collectIotPodStatuses собирает статус k8s pods для bridge и consumer по label app={name}.
func (h *Handler) collectIotPodStatuses(ctx context.Context) map[string]any {
result := map[string]any{}
for _, appLabel := range []string{"iot-mqtt-bridge", "iot-kafka-consumer"} {
podList := &corev1.PodList{}
if err := h.K8s.List(ctx, podList,
client.InNamespace("sless"),
client.MatchingLabels{"app": appLabel},
); err != nil {
result[appLabel] = map[string]any{"error": err.Error()}
continue
}
if len(podList.Items) == 0 {
result[appLabel] = map[string]any{"status": "not found"}
continue
}
pod := podList.Items[0]
var restarts int32
for _, cs := range pod.Status.ContainerStatuses {
restarts += cs.RestartCount
}
ready := false
for _, cond := range pod.Status.Conditions {
if cond.Type == corev1.PodReady && cond.Status == corev1.ConditionTrue {
ready = true
}
}
result[appLabel] = iotAdminPodStatus{
Name: pod.Name,
Phase: string(pod.Status.Phase),
Ready: ready,
Restarts: restarts,
Age: iotFormatAge(pod.CreationTimestamp.Time),
}
}
return result
}
// iotFormatAge возвращает человекочитаемый возраст (s/m/h/d) pod-а.
func iotFormatAge(created time.Time) string {
d := time.Since(created)
switch {
case d < time.Minute:
return fmt.Sprintf("%ds", int(d.Seconds()))
case d < time.Hour:
return fmt.Sprintf("%dm", int(d.Minutes()))
case d < 24*time.Hour:
return fmt.Sprintf("%dh", int(d.Hours()))
default:
return fmt.Sprintf("%dd", int(d.Hours()/24))
}
}
+454
View File
@@ -0,0 +1,454 @@
// Создано: 2026-04-04
// iot_device_handler.go — HTTP handlers для IoT-устройств (CRUD) и MQTT auth.
//
// Endpoints:
// POST /internal/mqtt/auth → MQTTAuth (без JWT, для EMQX)
// POST /v1/namespaces/{ns}/iot/devices → CreateIoTDevice
// GET /v1/namespaces/{ns}/iot/devices → ListIoTDevices
// GET /v1/namespaces/{ns}/iot/devices/{name} → GetIoTDevice (включает credentials)
// DELETE /v1/namespaces/{ns}/iot/devices/{name} → DeleteIoTDevice
// PATCH /v1/namespaces/{ns}/iot/devices/{name} → UpdateIoTDevice
//
// MQTTAuth вызывается EMQX при каждом MQTT CONNECT:
// - всегда возвращает HTTP 200 (non-200 = EMQX игнорирует backend)
// - {"result": "allow"|"deny"} в теле
//
// GetIoTDevice — единственный endpoint возвращающий mqtt-password.
// ListIoTDevices — без паролей (security by design).
package handler
import (
"crypto/subtle"
"encoding/json"
"net/http"
"strings"
"time"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
iotv1alpha1 "gitea.services.ngcloud.ru/Nail/IoT/api/v1alpha1"
)
// ——————————————————————————————————————————
// Типы запросов / ответов
// ——————————————————————————————————————————
// iotDeviceCreateRequest — тело POST при создании IoTDevice.
type iotDeviceCreateRequest struct {
// Name — имя k8s объекта IoTDevice (должно быть уникальным в namespace)
Name string `json:"name"`
// DeviceID — идентификатор устройства, используется в MQTT username и имени Secret
DeviceID string `json:"device_id"`
// Enabled — активно ли устройство с момента создания
Enabled *bool `json:"enabled"`
// Metadata — произвольные метаданные (модель, локация и т.д.)
Metadata map[string]string `json:"metadata,omitempty"`
}
// iotDeviceUpdateRequest — тело PATCH при обновлении IoTDevice.
type iotDeviceUpdateRequest struct {
// Enabled — включить/отключить устройство
Enabled *bool `json:"enabled"`
}
// iotDeviceResponse — ответ при чтении одного IoTDevice.
// MQTTPassword заполняется только из GetIoTDevice (чтение из Secret).
type iotDeviceResponse struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
DeviceID string `json:"device_id"`
Enabled bool `json:"enabled"`
Phase iotv1alpha1.IoTDevicePhase `json:"phase"`
MQTTUsername string `json:"mqtt_username,omitempty"`
MQTTPassword string `json:"mqtt_password,omitempty"` // только в GET /devices/{name}
SecretName string `json:"secret_name,omitempty"`
TopicPrefix string `json:"topic_prefix,omitempty"`
LastConnected string `json:"last_connected,omitempty"`
Message string `json:"message,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
CreatedAt string `json:"created_at,omitempty"`
}
// mqttAuthRequest — тело запроса от EMQX при MQTT CONNECT.
// EMQX 5.x посылает JSON: 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.
// result = "allow" | "deny"
// ACL — список правил pub/sub, изолирует топики по устройству.
type mqttAuthResponse struct {
Result string `json:"result"`
ACL []aclRule `json:"acl,omitempty"`
}
// aclRule — одно правило ACL для EMQX HTTP auth plugin.
// permission: "allow" | "deny"
// action: "publish" | "subscribe" | "all"
// topic: точный топик или wildcard (#, +)
type aclRule struct {
Permission string `json:"permission"`
Action string `json:"action"`
Topic string `json:"topic"`
}
// ——————————————————————————————————————————
// Вспомогательные функции
// ——————————————————————————————————————————
// deviceToResponse конвертирует IoTDevice CRD в ответ API.
// password передаётся отдельно — берётся из Secret только в GetIoTDevice.
func deviceToResponse(d *iotv1alpha1.IoTDevice, password string) iotDeviceResponse {
resp := iotDeviceResponse{
Name: d.Name,
Namespace: d.Namespace,
DeviceID: d.Spec.DeviceID,
Enabled: d.Spec.Enabled,
Phase: d.Status.Phase,
MQTTUsername: d.Status.MQTTUsername,
MQTTPassword: password,
SecretName: d.Status.SecretName,
TopicPrefix: d.Status.TopicPrefix,
Message: d.Status.Message,
Metadata: d.Spec.Metadata,
}
if d.Status.LastConnected != nil && !d.Status.LastConnected.IsZero() {
resp.LastConnected = d.Status.LastConnected.UTC().Format(time.RFC3339)
}
if !d.CreationTimestamp.IsZero() {
resp.CreatedAt = d.CreationTimestamp.UTC().Format("2006-01-02 15:04:05 UTC")
}
return resp
}
// ——————————————————————————————————————————
// MQTT Auth — Этап 2
// ——————————————————————————————————————————
// MQTTAuth — POST /internal/mqtt/auth
// Вызывается EMQX при каждом MQTT CONNECT.
// НЕ защищён JWT middleware — доступен только из кластера (путь /internal/).
//
// Логика аутентификации:
// 1. Распарсить username → namespace + deviceId
// 2. Получить Secret iot-{deviceId} в namespace
// 3. Constant-time сравнение пароля (защита от timing attacks)
// 4. Проверить что IoTDevice существует и enabled=true
// 5. Обновить status.lastConnected в IoTDevice
func (h *Handler) MQTTAuth(w http.ResponseWriter, r *http.Request) {
var req mqttAuthRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
// Плохой JSON от EMQX — deny, но не 400 (EMQX игнорирует non-200)
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
// Парсим username: "{namespace}_{deviceId}"
// Namespace содержит только [a-z0-9-], первый "_" — разделитель.
idx := strings.Index(req.Username, "_")
if idx < 0 {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
ns := req.Username[:idx]
deviceID := req.Username[idx+1:]
if ns == "" || deviceID == "" {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
// Читаем Secret с MQTT credentials
secretName := "iot-" + deviceID
secret := &corev1.Secret{}
if err := h.K8s.Get(r.Context(), client.ObjectKey{Namespace: ns, Name: secretName}, secret); err != nil {
// Secret не найден или ошибка k8s — deny
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
// Constant-time сравнение пароля — защита от timing attacks
storedPassword := secret.Data["mqtt-password"]
if subtle.ConstantTimeCompare(storedPassword, []byte(req.Password)) != 1 {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
// Проверяем что IoTDevice активно
device := &iotv1alpha1.IoTDevice{}
if err := h.K8s.Get(r.Context(), client.ObjectKey{Namespace: ns, Name: deviceID}, device); err != nil {
// IoTDevice не найден (или удалён) — deny
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
if !device.Spec.Enabled {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
// Обновляем lastConnected в статусе устройства (best-effort, ошибка не критична)
now := metav1.NewTime(time.Now().UTC())
device.Status.LastConnected = &now
if err := h.K8s.Status().Update(r.Context(), device); err != nil {
h.Log.Warn("mqtt auth: failed to update lastConnected", "device", deviceID, "err", err)
// Продолжаем — это некритично, устройство всё равно авторизовано
}
// Формируем ACL правила для этого подключения.
// Топик устройства: "{namespace}/telemetry/{deviceId}"
// Это то что строит эмулятор: topicPrefix + "telemetry/" + device_id
// topicPrefix = "{ns}/" → итого "{ns}/telemetry/{deviceId}"
deviceTopic := ns + "/telemetry/" + deviceID
var aclRules []aclRule
if req.ClientID == "sless-iot-bridge" {
// Bridge подписывается на "+/telemetry/+" (все тенанты) — разрешаем
// Bridge НЕ публикует через MQTT — только читает
aclRules = []aclRule{
{Permission: "allow", Action: "subscribe", Topic: "+/telemetry/+"},
{Permission: "deny", Action: "all", Topic: "#"},
}
} else {
// Обычное IoT устройство: только свой топик
aclRules = []aclRule{
{Permission: "allow", Action: "publish", Topic: deviceTopic},
{Permission: "allow", Action: "subscribe", Topic: deviceTopic},
{Permission: "deny", Action: "all", Topic: "#"},
}
}
writeJSON(w, http.StatusOK, mqttAuthResponse{
Result: "allow",
ACL: aclRules,
})
}
// ——————————————————————————————————————————
// IoT Device CRUD — Этап 4
// ——————————————————————————————————————————
// CreateIoTDevice — POST /v1/namespaces/{namespace}/iot/devices
// Создаёт IoTDevice CRD. Контроллер асинхронно сгенерирует MQTT credentials.
// credentials доступны через GET /devices/{name} после reconcile (phase=Active).
func (h *Handler) CreateIoTDevice(w http.ResponseWriter, r *http.Request) {
ns := namespace(r)
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
}
device := &iotv1alpha1.IoTDevice{
ObjectMeta: metav1.ObjectMeta{
Name: req.Name,
Namespace: ns,
},
Spec: iotv1alpha1.IoTDeviceSpec{
DeviceID: req.DeviceID,
Enabled: enabled,
Metadata: req.Metadata,
},
}
if err := h.K8s.Create(r.Context(), device); err != nil {
if errors.IsAlreadyExists(err) {
writeJSON(w, http.StatusConflict, errResp("iot device already exists"))
return
}
writeJSON(w, http.StatusInternalServerError, errResp(err.Error()))
return
}
writeJSON(w, http.StatusCreated, deviceToResponse(device, ""))
}
// ListIoTDevices — GET /v1/namespaces/{namespace}/iot/devices
// Возвращает список устройств БЕЗ паролей (security by design).
func (h *Handler) ListIoTDevices(w http.ResponseWriter, r *http.Request) {
ns := namespace(r)
list := &iotv1alpha1.IoTDeviceList{}
if err := h.K8s.List(r.Context(), list, client.InNamespace(ns)); err != nil {
writeJSON(w, http.StatusInternalServerError, errResp(err.Error()))
return
}
result := make([]iotDeviceResponse, 0, len(list.Items))
for i := range list.Items {
result = append(result, deviceToResponse(&list.Items[i], ""))
}
writeJSON(w, http.StatusOK, result)
}
// GetIoTDevice — GET /v1/namespaces/{namespace}/iot/devices/{name}
// Возвращает устройство включая mqtt_password из Secret.
// mqtt_password нужен пользователю для конфигурации физического устройства.
func (h *Handler) GetIoTDevice(w http.ResponseWriter, r *http.Request) {
ns := namespace(r)
name := pathVar(r, "name")
device := &iotv1alpha1.IoTDevice{}
if err := h.K8s.Get(r.Context(), client.ObjectKey{Namespace: ns, Name: name}, device); err != nil {
if errors.IsNotFound(err) {
writeJSON(w, http.StatusNotFound, errResp("iot device not found"))
return
}
writeJSON(w, http.StatusInternalServerError, errResp(err.Error()))
return
}
// Читаем пароль из Secret — если ещё не создан (phase=Pending), password будет пустым
password := ""
if device.Status.SecretName != "" {
secret := &corev1.Secret{}
err := h.K8s.Get(r.Context(), client.ObjectKey{Namespace: ns, Name: device.Status.SecretName}, secret)
if err == nil {
password = string(secret.Data["mqtt-password"])
}
// Если Secret не найден — просто передаём пустой пароль (устройство ещё provisioning)
}
writeJSON(w, http.StatusOK, deviceToResponse(device, password))
}
// DeleteIoTDevice — DELETE /v1/namespaces/{namespace}/iot/devices/{name}
// Удаляет IoTDevice CRD. Контроллер через finalizer удалит Secret каскадно.
func (h *Handler) DeleteIoTDevice(w http.ResponseWriter, r *http.Request) {
ns := namespace(r)
name := pathVar(r, "name")
device := &iotv1alpha1.IoTDevice{}
if err := h.K8s.Get(r.Context(), client.ObjectKey{Namespace: ns, Name: name}, device); err != nil {
if errors.IsNotFound(err) {
writeJSON(w, http.StatusNotFound, errResp("iot device not found"))
return
}
writeJSON(w, http.StatusInternalServerError, errResp(err.Error()))
return
}
if err := h.K8s.Delete(r.Context(), device); err != nil {
writeJSON(w, http.StatusInternalServerError, errResp(err.Error()))
return
}
w.WriteHeader(http.StatusNoContent)
}
// UpdateIoTDevice — PATCH /v1/namespaces/{namespace}/iot/devices/{name}
// Позволяет включить/отключить устройство (spec.enabled).
// Контроллер увидит изменение и обновит status.phase.
func (h *Handler) UpdateIoTDevice(w http.ResponseWriter, r *http.Request) {
ns := namespace(r)
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
}
device := &iotv1alpha1.IoTDevice{}
if err := h.K8s.Get(r.Context(), client.ObjectKey{Namespace: ns, Name: name}, device); err != nil {
if errors.IsNotFound(err) {
writeJSON(w, http.StatusNotFound, errResp("iot device not found"))
return
}
writeJSON(w, http.StatusInternalServerError, errResp(err.Error()))
return
}
device.Spec.Enabled = *req.Enabled
if err := h.K8s.Update(r.Context(), device); err != nil {
writeJSON(w, http.StatusInternalServerError, errResp(err.Error()))
return
}
writeJSON(w, http.StatusOK, deviceToResponse(device, ""))
}
// ——————————————————————————————————————————
// MQTT ACL — авторизация pub/sub
// ——————————————————————————————————————————
// mqttAclRequest — тело запроса от EMQX при каждом publish/subscribe.
type mqttAclRequest struct {
Username string `json:"username"`
ClientID string `json:"clientid"`
Action string `json:"action"` // "publish" | "subscribe"
Topic string `json:"topic"`
}
// MQTTAcl — POST /internal/mqtt/acl
// Вызывается EMQX для каждого pub/sub действия.
// НЕ защищён JWT — доступен только из кластера.
//
// Логика разрешений:
// 1. Bridge clientid "sless-iot-bridge" — subscribe на любой топик (нужен для "+/telemetry/+")
// 2. IoT Device (username "{ns}_{deviceId}") — publish/subscribe на "{ns}/telemetry/{deviceId}"
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
}
// Специальный случай: mqtt-bridge подписывается на "+/telemetry/+" (все тенанты).
// Публикация bridge НЕ разрешена — только чтение.
if req.ClientID == "sless-iot-bridge" {
if req.Action == "subscribe" {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "allow"})
} else {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
}
return
}
// Парсим username → namespace + deviceId (формат: "{ns}_{deviceId}")
// strings.Index находит ПЕРВЫЙ '_' — namespace содержит только дефисы
idx := strings.Index(req.Username, "_")
if idx < 0 {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
ns := req.Username[:idx]
deviceID := req.Username[idx+1:]
if ns == "" || deviceID == "" {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
return
}
// Разрешённый топик: "{ns}/telemetry/{deviceId}"
// Это то что эмулятор строит как: topicPrefix + "telemetry/" + device_id
// topicPrefix = "{ns}/" → итого "{ns}/telemetry/{deviceId}"
allowedTopic := ns + "/telemetry/" + deviceID
if req.Topic == allowedTopic {
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "allow"})
return
}
writeJSON(w, http.StatusOK, mqttAuthResponse{Result: "deny"})
}
@@ -0,0 +1,55 @@
// Создано: 2026-04-05
// iot_telemetry_handler.go — REST handler для чтения IoT телеметрии.
//
// Endpoint:
// GET /v1/namespaces/{namespace}/iot/telemetry?device={id}&limit={n}
//
// Авторизация: Bearer JWT → namespace validation (как все /v1/ маршруты).
// Данные берутся из per-tenant Postgres DB через IoTPostgresStore.
// Если IoTPG не инициализирован (IOT_PG_DSN не задан) — возвращает 503.
package handler
import (
"net/http"
"strconv"
"github.com/gorilla/mux"
"gitea.services.ngcloud.ru/Nail/IoT/internal/storage/iotpg"
)
// ListIoTTelemetry обрабатывает GET /v1/namespaces/{namespace}/iot/telemetry.
// Параметры: device (опционально), limit (default 50, max 1000).
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 := mux.Vars(r)["namespace"]
deviceID := r.URL.Query().Get("device")
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
}
// Возвращаем пустой массив вместо null — удобнее для JS
if rows == nil {
rows = []iotpg.TelemetryRow{}
}
writeJSON(w, http.StatusOK, map[string]any{
"items": rows,
"count": len(rows),
})
}
+165
View File
@@ -0,0 +1,165 @@
// Изменено: 2026-04-05
// Auth middleware — проверяет Bearer JWT-токен из заголовка Authorization.
//
// Архитектура аутентификации:
// - В v1 токен — это JWT облака (nubes), выданный при логине.
// - Оператор НЕ проверяет подпись JWT (публичный ключ nubes недоступен внутри кластера).
// - Проверяется только структура JWT и claim "sub" (не пустой) и "exp" (не истёк).
// - Полная проверка подлинности токена происходит в провайдере terraform через PingNubesAPI.
// - Такой подход называют "trusted perimeter": оператор доступен только внутри кластера,
// внешний доступ — через Ingress, где токен уже проверен на уровне API-шлюза.
//
// TODO v2: получать публичный ключ из nubes JWKS endpoint и проверять подпись RS256.
//
// ──────────────────────────────────────────────────────────────────────────────
// ТЕСТОВЫЙ РЕЖИМ (authTestMode = true):
// Принимается ЛЮБАЯ строка без пробелов — не обязательно JWT.
// Это позволяет тестировать UI/API без реального токена nubes.
// Строка используется как идентификатор пользователя (аналог JWT.sub),
// namespace выводится из неё так же: SHA256 → первые 16 байт hex → "sless-{hex}".
//
// ⚠️ ПЕРЕД ВЫХОДОМ В ПРОД: установить authTestMode = false.
// Для возврата к строгой JWT-валидации: одна строка ниже.
// ──────────────────────────────────────────────────────────────────────────────
package middleware
import (
"encoding/base64"
"encoding/json"
"log/slog"
"net/http"
"strings"
"time"
)
// authTestMode — ТЕСТОВЫЙ РЕЖИМ аутентификации.
//
// true → принимается любая строка без пробелов (не обязательно JWT).
//
// Используется при разработке UI когда реальный токен nubes не нужен.
//
// false → строгая проверка JWT (структура + sub + exp).
//
// Необходимо установить перед деплоем в прод.
//
// Чтобы вернуться к JWT: изменить на false.
const authTestMode = true
// Auth возвращает middleware которое требует заголовок:
//
// Authorization: Bearer <token>
//
// В тестовом режиме (authTestMode=true): принимает любую строку без пробелов.
// В боевом режиме (authTestMode=false): требует валидный JWT (sub + exp).
func Auth(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]
// ── ТЕСТОВЫЙ РЕЖИМ ───────────────────────────────────────────────────
// Если authTestMode=true и токен — просто строка без пробелов (не JWT),
// пропускаем JWT-валидацию. Строка обрабатывается как произвольный sub.
// Чтобы вернуть строгую проверку: установить authTestMode = false.
if authTestMode && isPlainToken(token) {
log.Info("auth: test mode — plain token accepted", "remote", r.RemoteAddr, "path", r.URL.Path)
next.ServeHTTP(w, r)
return
}
// ── БОЕВОЙ РЕЖИМ / JWT ───────────────────────────────────────────────
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 возвращает true если токен — непустая строка без пробелов и НЕ является JWT.
// JWT определяется по наличию ровно двух точек (xxx.yyy.zzz).
// Логика: если строка выглядит как JWT — проверять через validateJWT (даже в testMode).
func isPlainToken(token string) bool {
if token == "" || strings.ContainsAny(token, " \t\n\r") {
return false
}
// Если три части через точку — скорее всего JWT, проверять нормально
parts := strings.Split(token, ".")
return len(parts) != 3
}
// validateJWT проверяет структуру JWT и claim "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]
// JWT использует base64url без padding
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 int64 `json:"exp"`
}
if err := json.Unmarshal(decoded, &claims); err != nil {
return &jwtError{"cannot parse JWT claims"}
}
if claims.Sub == "" {
return &jwtError{"missing sub claim"}
}
if claims.Exp > 0 && claims.Exp < time.Now().Unix() {
return &jwtError{"token expired"}
}
return nil
}
type jwtError struct{ msg string }
func (e *jwtError) Error() string { return e.msg }
// verifySignature — точка вставки для проверки подписи JWT (v2).
//
// Текущее состояние (v1): подпись НЕ проверяется.
// Причина: публичный ключ nubes недоступен внутри кластера без JWKS endpoint.
// Безопасность обеспечивается "trusted perimeter" — оператор доступен только изнутри кластера.
//
// Когда nubes предоставит JWKS endpoint, реализация:
//
// func verifySignature(token string) error {
// // 1. Получить JWKS: GET {NUBES_JWKS_URL}/.well-known/jwks.json
// // 2. Найти ключ по "kid" из JWT header
// // 3. Проверить подпись RS256/ES256
// // Пример: github.com/lestrrat-go/jwx/v2/jwk + jwt.Parse
// return nil
// }
//
// После реализации добавить вызов в validateJWT после проверки структуры:
//
// if err := verifySignature(token); err != nil {
// return &jwtError{"signature verification failed: " + err.Error()}
// }
+38
View File
@@ -0,0 +1,38 @@
// Изменено: 2026-03-07
// Logging middleware — логирует каждый HTTP запрос через slog.
// Записывает метод, путь, статус и длительность.
package middleware
import (
"log/slog"
"net/http"
"time"
)
// responseWriter оборачивает http.ResponseWriter чтобы захватить статус ответа.
type responseWriter struct {
http.ResponseWriter
status int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.status = code
rw.ResponseWriter.WriteHeader(code)
}
// Logging возвращает middleware которое логирует все запросы через slog.
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,
)
})
}
+67
View File
@@ -0,0 +1,67 @@
// Создано: 2026-04-12
// router.go — регистрация IoT REST-маршрутов.
// Перенесено из sless — только IoT-специфичные маршруты.
// CORS для https://iot.kube5s.ru, JWT auth через middleware.Auth.
package api
import (
"log/slog"
"net/http"
"github.com/gorilla/mux"
"gitea.services.ngcloud.ru/Nail/IoT/internal/api/handler"
"gitea.services.ngcloud.ru/Nail/IoT/internal/api/middleware"
)
// corsMiddleware добавляет CORS-заголовки для IoT Консоли на https://iot.kube5s.ru.
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "https://iot.kube5s.ru")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
w.Header().Set("Access-Control-Max-Age", "600")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
// NewRouter собирает gorilla/mux роутер со всеми IoT маршрутами.
func NewRouter(h *handler.Handler, log *slog.Logger) http.Handler {
r := mux.NewRouter()
// IoT Консоль — публичный HTML
r.HandleFunc("/console", ServeIoTConsole).Methods(http.MethodGet)
// IoT Admin — страница администратора
r.HandleFunc("/iot-admin", ServeIoTAdmin).Methods(http.MethodGet)
r.HandleFunc("/iot-admin/stats", h.AdminStats).Methods(http.MethodGet)
// /v1 — API маршруты, защищены JWT
v1 := r.PathPrefix("/v1").Subrouter()
// IoT Devices CRUD
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)
// IoT Telemetry
v1.HandleFunc("/namespaces/{namespace}/iot/telemetry", h.ListIoTTelemetry).Methods(http.MethodGet)
// MQTT Auth — без JWT, вызывается EMQX из кластера
r.HandleFunc("/internal/mqtt/auth", h.MQTTAuth).Methods(http.MethodPost)
r.HandleFunc("/internal/mqtt/acl", h.MQTTAcl).Methods(http.MethodPost)
// JWT auth middleware для /v1/
v1.Use(func(next http.Handler) http.Handler {
return middleware.Auth(log, next)
})
return corsMiddleware(middleware.Logging(log, r))
}
+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