From 594a62a9f6026f9e07970cc1747489e5ff026e5b Mon Sep 17 00:00:00 2001 From: Maxim Date: Tue, 23 Jun 2026 15:28:10 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=BA=D0=B0=20=D1=81=D0=B1=D0=BE=D1=80=D0=BA=D0=B8=20deb=20?= =?UTF-8?q?=D0=BF=D0=B0=D0=BA=D0=B5=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 114 +++++++++++++++++++-- Makefile.backup | 159 +++++++++++++++++++++++++++++ debian/changelog | 9 ++ debian/control | 14 +++ debian/copyright | 29 ++++++ debian/dirs | 5 + debian/gpio-monitor-server.conf | 15 +++ debian/gpio-monitor-server.service | 39 +++++++ debian/install | 2 + debian/postinst | 33 ++++++ debian/postrm | 19 ++++ debian/preinst | 24 +++++ debian/prerm | 15 +++ debian/rules | 24 +++++ debian/usr/bin/gpio-logs | 31 ++++++ internal/logger/paths.go | 47 ++++++++- 16 files changed, 565 insertions(+), 14 deletions(-) create mode 100644 Makefile.backup create mode 100644 debian/changelog create mode 100644 debian/control create mode 100644 debian/copyright create mode 100644 debian/dirs create mode 100644 debian/gpio-monitor-server.conf create mode 100644 debian/gpio-monitor-server.service create mode 100644 debian/install create mode 100644 debian/postinst create mode 100644 debian/postrm create mode 100644 debian/preinst create mode 100644 debian/prerm create mode 100644 debian/rules create mode 100644 debian/usr/bin/gpio-logs diff --git a/Makefile b/Makefile index 3204ea8..7add5e2 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ # Makefile для GPIO Monitor Server -.PHONY: all build clean run test fmt lint help install dev +.PHONY: all build clean run test fmt lint help install dev deb prepare-debian # Переменные APP_NAME := gpio-monitor-server @@ -8,6 +8,8 @@ CMD_PATH := ./cmd/server BUILD_DIR := ./build BINARY := $(BUILD_DIR)/$(APP_NAME) WEB_DIR := ./cmd/server/web +DEB_DIR := ./debian +DEB_PACKAGE := $(DEB_DIR)/$(APP_NAME) # Целевая платформа (по умолчанию) GOOS ?= linux @@ -43,15 +45,15 @@ build-frontend: fi && \ echo " Компиляция TypeScript..." && \ npm run build && \ - echo "$(GREEN) TypeScript скомпилирован успешно!$(NC)" + echo "$(GREEN)TypeScript скомпилирован успешно!$(NC)" ## build-backend - Сборка Go сервера build-backend: - @echo "$(YELLOW)🔧 Сборка Go сервера...$(NC)" + @echo "$(YELLOW)Сборка Go сервера...$(NC)" @mkdir -p $(BUILD_DIR) @echo " Целевая платформа: $(GOOS)/$(GOARCH)" @GOOS=$(GOOS) GOARCH=$(GOARCH) go build $(LDFLAGS) -o $(BINARY) $(CMD_PATH) - @echo "$(GREEN) Go сервер скомпилирован успешно!$(NC)" + @echo "$(GREEN)Go сервер скомпилирован успешно!$(NC)" ## run - Запуск сервера (сборка + запуск) run: build @@ -60,7 +62,7 @@ run: build ## dev - Режим разработки (без оптимизации, с hot-reload) dev: - @echo "$(YELLOW) Режим разработки...$(NC)" + @echo "$(YELLOW)Режим разработки...$(NC)" @go run $(CMD_PATH) -port :8080 ## clean - Очистка артефактов сборки @@ -69,7 +71,9 @@ clean: @rm -rf $(BUILD_DIR) @rm -rf $(WEB_DIR)/dist @rm -rf $(WEB_DIR)/node_modules - @echo "$(GREEN) Очищено$(NC)" + @rm -rf $(DEB_PACKAGE) + @rm -f *.deb + @echo "$(GREEN)Очищено$(NC)" ## test - Запуск тестов test: @@ -78,18 +82,18 @@ test: ## fmt - Форматирование кода fmt: - @echo "$(YELLOW) Форматирование кода...$(NC)" + @echo "$(YELLOW)Форматирование кода...$(NC)" @go fmt ./... @cd $(WEB_DIR) && npm run format 2>/dev/null || true ## lint - Проверка кода lint: - @echo "$(YELLOW) Проверка кода...$(NC)" + @echo "$(YELLOW)Проверка кода...$(NC)" @golangci-lint run ./... 2>/dev/null || echo " Установите golangci-lint: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest" ## deps - Установка зависимостей deps: - @echo "$(YELLOW) Установка зависимостей...$(NC)" + @echo "$(YELLOW)Установка зависимостей...$(NC)" @go mod download @go mod tidy @cd $(WEB_DIR) && npm install @@ -98,11 +102,11 @@ deps: install: build @echo "$(YELLOW)Установка $(APP_NAME)...$(NC)" @sudo cp $(BINARY) /usr/local/bin/$(APP_NAME) - @echo "$(GREEN) Установлено в /usr/local/bin/$(APP_NAME)$(NC)" + @echo "$(GREEN)Установлено в /usr/local/bin/$(APP_NAME)$(NC)" ## uninstall - Удаление из системы uninstall: - @echo "$(YELLOW)Удаление $(APP_NAME)...$(NC)" + @echo "$(YELLOW)🗑Удаление $(APP_NAME)...$(NC)" @sudo rm -f /usr/local/bin/$(APP_NAME) @echo "$(GREEN)Удалено$(NC)" @@ -123,6 +127,71 @@ help: @echo " make dev - Запуск в режиме разработки" @echo " make clean - Очистка" @echo " make install - Установка в систему" + @echo " make deb - Сборка DEB пакета" + +# ============================================ +# СБОРКА DEB ПАКЕТА +# ============================================ + +## prepare-debian - Подготовка структуры для deb-пакета +prepare-debian: + @echo "$(YELLOW)Подготовка структуры DEB пакета...$(NC)" + @# Создаем основную структуру + @mkdir -p $(DEB_PACKAGE)/DEBIAN + @mkdir -p $(DEB_PACKAGE)/usr/bin + @mkdir -p $(DEB_PACKAGE)/usr/share/doc/$(APP_NAME) + @mkdir -p $(DEB_PACKAGE)/opt/gpio-monitoring/web + @mkdir -p $(DEB_PACKAGE)/etc/gpio-monitoring + @mkdir -p $(DEB_PACKAGE)/etc/systemd/system + @# Копируем DEBIAN файлы + @if [ -f $(DEB_DIR)/control ]; then cp $(DEB_DIR)/control $(DEB_PACKAGE)/DEBIAN/; fi + @if [ -f $(DEB_DIR)/preinst ]; then cp $(DEB_DIR)/preinst $(DEB_PACKAGE)/DEBIAN/; fi + @if [ -f $(DEB_DIR)/postinst ]; then cp $(DEB_DIR)/postinst $(DEB_PACKAGE)/DEBIAN/; fi + @if [ -f $(DEB_DIR)/prerm ]; then cp $(DEB_DIR)/prerm $(DEB_PACKAGE)/DEBIAN/; fi + @if [ -f $(DEB_DIR)/postrm ]; then cp $(DEB_DIR)/postrm $(DEB_PACKAGE)/DEBIAN/; fi + @# Копируем документацию + @if [ -f $(DEB_DIR)/copyright ]; then cp $(DEB_DIR)/copyright $(DEB_PACKAGE)/usr/share/doc/$(APP_NAME)/; fi + @if [ -f $(DEB_DIR)/changelog ]; then \ + cp $(DEB_DIR)/changelog $(DEB_PACKAGE)/usr/share/doc/$(APP_NAME)/; \ + gzip -9 -n $(DEB_PACKAGE)/usr/share/doc/$(APP_NAME)/changelog 2>/dev/null || true; \ + fi + @# Устанавливаем права + @chmod 755 $(DEB_PACKAGE)/DEBIAN/* 2>/dev/null || true + @echo "$(GREEN)Структура подготовлена$(NC)" + +## deb - Сборка DEB пакета +deb: clean build-frontend build-backend prepare-debian + @echo "$(YELLOW)Сборка DEB пакета...$(NC)" + @# Копируем бинарник + @cp $(BINARY) $(DEB_PACKAGE)/usr/bin/ + @# Копируем веб-файлы + @if [ -d "$(WEB_DIR)/dist" ]; then cp -r $(WEB_DIR)/dist $(DEB_PACKAGE)/opt/gpio-monitoring/web/; fi + @if [ -d "$(WEB_DIR)/css" ]; then cp -r $(WEB_DIR)/css $(DEB_PACKAGE)/opt/gpio-monitoring/web/; fi + @if [ -d "$(WEB_DIR)/fonts" ]; then cp -r $(WEB_DIR)/fonts $(DEB_PACKAGE)/opt/gpio-monitoring/web/; fi + @if ls $(WEB_DIR)/*.html 1>/dev/null 2>&1; then cp $(WEB_DIR)/*.html $(DEB_PACKAGE)/opt/gpio-monitoring/web/ 2>/dev/null || true; fi + @if [ -f "$(WEB_DIR)/favicon.png" ]; then cp $(WEB_DIR)/favicon.png $(DEB_PACKAGE)/opt/gpio-monitoring/web/ 2>/dev/null || true; fi + @# Копируем systemd сервис + @if [ -f "$(DEB_DIR)/$(APP_NAME).service" ]; then cp $(DEB_DIR)/$(APP_NAME).service $(DEB_PACKAGE)/etc/systemd/system/; fi + @# Копируем конфиг + @if [ -f "$(DEB_DIR)/$(APP_NAME).conf" ]; then cp $(DEB_DIR)/$(APP_NAME).conf $(DEB_PACKAGE)/etc/gpio-monitoring/config; fi + @# Копируем скрипт для логов + @if [ -f "$(DEB_DIR)/usr/bin/gpio-logs" ]; then \ + cp $(DEB_DIR)/usr/bin/gpio-logs $(DEB_PACKAGE)/usr/bin/; \ + chmod +x $(DEB_PACKAGE)/usr/bin/gpio-logs; \ + fi + @# Устанавливаем правильные права + @chown -R root:root $(DEB_PACKAGE) 2>/dev/null || true + @# Создаем архив с контрольными суммами + @cd $(DEB_PACKAGE) && find . -type f ! -path "./DEBIAN/*" -exec md5sum {} \; > DEBIAN/md5sums 2>/dev/null || true + @# Собираем пакет + @dpkg-deb --root-owner-group --build $(DEB_PACKAGE) . + @mkdir -p $(BUILD_DIR) + @mv *.deb $(BUILD_DIR)/ + @echo "$(GREEN)DEB пакет создан: $(BUILD_DIR)/$(APP_NAME).deb$(NC)" + @ls -lh $(BUILD_DIR)/*.deb + @echo "" + @echo "$(GREEN)Информация о пакете:$(NC)" + @dpkg-deb -I $(BUILD_DIR)/*.deb | head -15 # ============================================ # ДОПОЛНИТЕЛЬНЫЕ ЦЕЛИ @@ -157,3 +226,26 @@ docker-build: docker-run: @echo "$(YELLOW)Запуск в Docker...$(NC)" @docker run -p 8080:8080 gpio-monitor:latest + +## deb-clean - Очистка временных файлов deb-пакета +deb-clean: + @echo "$(YELLOW)Очистка deb-временных файлов...$(NC)" + @rm -rf $(DEB_PACKAGE) + @rm -f $(BUILD_DIR)/$(APP_NAME).deb + @echo "$(GREEN)Очищено$(NC)" + +## deb-info - Показать информацию о deb-пакете +deb-info: + @if [ -f "$(BUILD_DIR)/$(APP_NAME).deb" ]; then \ + dpkg-deb -I $(BUILD_DIR)/$(APP_NAME).deb; \ + else \ + echo "$(RED)Пакет не найден. Сначала выполните: make deb$(NC)"; \ + fi + +## deb-contents - Показать содержимое deb-пакета +deb-contents: + @if [ -f "$(BUILD_DIR)/$(APP_NAME).deb" ]; then \ + dpkg-deb -c $(BUILD_DIR)/$(APP_NAME).deb; \ + else \ + echo "$(RED)Пакет не найден. Сначала выполните: make deb$(NC)"; \ + fi diff --git a/Makefile.backup b/Makefile.backup new file mode 100644 index 0000000..3204ea8 --- /dev/null +++ b/Makefile.backup @@ -0,0 +1,159 @@ +# Makefile для GPIO Monitor Server + +.PHONY: all build clean run test fmt lint help install dev + +# Переменные +APP_NAME := gpio-monitor-server +CMD_PATH := ./cmd/server +BUILD_DIR := ./build +BINARY := $(BUILD_DIR)/$(APP_NAME) +WEB_DIR := ./cmd/server/web + +# Целевая платформа (по умолчанию) +GOOS ?= linux +GOARCH ?= arm64 + +# Флаги сборки +LDFLAGS := -ldflags="-s -w" + +# Цвета для вывода +RED := \033[0;31m +GREEN := \033[0;32m +YELLOW := \033[0;33m +NC := \033[0m # No Color + +# ============================================ +# ОСНОВНЫЕ ЦЕЛИ +# ============================================ + +all: help + +## build - Полная сборка проекта (фронтенд + бекенд) +build: build-frontend build-backend + @echo "$(GREEN)Сборка завершена!$(NC)" + @ls -lh $(BINARY) + +## build-frontend - Сборка TypeScript фронтенда +build-frontend: + @echo "$(YELLOW)Сборка TypeScript фронтенда...$(NC)" + @cd $(WEB_DIR) && \ + if [ ! -d "node_modules" ]; then \ + echo " Установка npm зависимостей..."; \ + npm install; \ + fi && \ + echo " Компиляция TypeScript..." && \ + npm run build && \ + echo "$(GREEN) TypeScript скомпилирован успешно!$(NC)" + +## build-backend - Сборка Go сервера +build-backend: + @echo "$(YELLOW)🔧 Сборка Go сервера...$(NC)" + @mkdir -p $(BUILD_DIR) + @echo " Целевая платформа: $(GOOS)/$(GOARCH)" + @GOOS=$(GOOS) GOARCH=$(GOARCH) go build $(LDFLAGS) -o $(BINARY) $(CMD_PATH) + @echo "$(GREEN) Go сервер скомпилирован успешно!$(NC)" + +## run - Запуск сервера (сборка + запуск) +run: build + @echo "$(YELLOW)Запуск сервера...$(NC)" + @$(BINARY) + +## dev - Режим разработки (без оптимизации, с hot-reload) +dev: + @echo "$(YELLOW) Режим разработки...$(NC)" + @go run $(CMD_PATH) -port :8080 + +## clean - Очистка артефактов сборки +clean: + @echo "$(YELLOW)Очистка...$(NC)" + @rm -rf $(BUILD_DIR) + @rm -rf $(WEB_DIR)/dist + @rm -rf $(WEB_DIR)/node_modules + @echo "$(GREEN) Очищено$(NC)" + +## test - Запуск тестов +test: + @echo "$(YELLOW)Запуск тестов...$(NC)" + @go test -v ./... + +## fmt - Форматирование кода +fmt: + @echo "$(YELLOW) Форматирование кода...$(NC)" + @go fmt ./... + @cd $(WEB_DIR) && npm run format 2>/dev/null || true + +## lint - Проверка кода +lint: + @echo "$(YELLOW) Проверка кода...$(NC)" + @golangci-lint run ./... 2>/dev/null || echo " Установите golangci-lint: go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest" + +## deps - Установка зависимостей +deps: + @echo "$(YELLOW) Установка зависимостей...$(NC)" + @go mod download + @go mod tidy + @cd $(WEB_DIR) && npm install + +## install - Установка бинарника в систему +install: build + @echo "$(YELLOW)Установка $(APP_NAME)...$(NC)" + @sudo cp $(BINARY) /usr/local/bin/$(APP_NAME) + @echo "$(GREEN) Установлено в /usr/local/bin/$(APP_NAME)$(NC)" + +## uninstall - Удаление из системы +uninstall: + @echo "$(YELLOW)Удаление $(APP_NAME)...$(NC)" + @sudo rm -f /usr/local/bin/$(APP_NAME) + @echo "$(GREEN)Удалено$(NC)" + +## help - Показать справку +help: + @echo "$(GREEN)GPIO Monitor Server - команды Makefile$(NC)" + @echo "" + @echo "Доступные команды:" + @awk '/^##/ { \ + cmd = $$0; \ + gsub(/^## /, "", cmd); \ + printf " $(GREEN)%-20s$(NC) %s\n", $$2, cmd \ + }' $(MAKEFILE_LIST) | sort + @echo "" + @echo "Примеры:" + @echo " make build - Полная сборка" + @echo " make run - Сборка и запуск" + @echo " make dev - Запуск в режиме разработки" + @echo " make clean - Очистка" + @echo " make install - Установка в систему" + +# ============================================ +# ДОПОЛНИТЕЛЬНЫЕ ЦЕЛИ +# ============================================ + +## build-arm64 - Сборка для ARM64 (Raspberry Pi) +build-arm64: + @$(MAKE) build GOOS=linux GOARCH=arm64 + +## build-amd64 - Сборка для AMD64 +build-amd64: + @$(MAKE) build GOOS=linux GOARCH=amd64 + +## build-mac - Сборка для macOS +build-mac: + @$(MAKE) build GOOS=darwin GOARCH=amd64 + +## build-windows - Сборка для Windows +build-windows: + @$(MAKE) build GOOS=windows GOARCH=amd64 + +## build-all - Сборка для всех платформ +build-all: build-arm64 build-amd64 build-mac build-windows + @echo "$(GREEN)Все платформы собраны$(NC)" + +## docker-build - Сборка Docker образа +docker-build: + @echo "$(YELLOW)Сборка Docker образа...$(NC)" + @docker build -t gpio-monitor:latest . + +## docker-run - Запуск в Docker +docker-run: + @echo "$(YELLOW)Запуск в Docker...$(NC)" + @docker run -p 8080:8080 gpio-monitor:latest diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..17f5450 --- /dev/null +++ b/debian/changelog @@ -0,0 +1,9 @@ +gpio-monitor-server (1.0.0-1) stable; urgency=medium + + * Initial release + * GPIO monitoring with web interface + * Systemd service with auto-restart + * Log rotation and retention + * Support for Raspberry Pi GPIO + + -- НТЦ200 Mon, 23 Jun 2026 12:00:00 +0300 diff --git a/debian/control b/debian/control new file mode 100644 index 0000000..959489e --- /dev/null +++ b/debian/control @@ -0,0 +1,14 @@ +Source: gpio-monitor-server +Section: utils +Priority: optional +Maintainer: НТЦ200 +Build-Depends: debhelper (>= 11), dh-golang, golang-go, npm +Standards-Version: 4.5.0 +Homepage: https://example.com/gpio-monitor +Package: gpio-monitor-server +Version: 1.0.0-1 +Architecture: arm64 +Depends: systemd +Description: GPIO Monitor Server + Сервер для мониторинга GPIO с веб-интерфейсом + и системой логирования. diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000..0350ada --- /dev/null +++ b/debian/copyright @@ -0,0 +1,29 @@ +Format: +Upstream-Name: gpio-monitor-server +Source: +Files: * +Copyright: 2024 НТЦ200 +License: MIT + +Files: debian/* +Copyright: 2024 НТЦ200 +License: MIT + +License: MIT + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + . + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + . + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. diff --git a/debian/dirs b/debian/dirs new file mode 100644 index 0000000..94a6646 --- /dev/null +++ b/debian/dirs @@ -0,0 +1,5 @@ +usr/bin +opt/gpio-monitoring/web +etc/gpio-monitoring +var/log/gpio-monitoring +var/lib/gpio-monitoring diff --git a/debian/gpio-monitor-server.conf b/debian/gpio-monitor-server.conf new file mode 100644 index 0000000..36a7cad --- /dev/null +++ b/debian/gpio-monitor-server.conf @@ -0,0 +1,15 @@ +# Конфигурация GPIO Monitor Server +# Файл: /etc/gpio-monitoring/config + +# Параметры запуска +PIPE_PATH=/tmp/gpio_pipe +RETENTION_HOURS=72 +RETENTION_MB=2000 +RETENTION_INTERVAL=60 +ROTATION_CHECK_INTERVAL=1 +BUFFER_SIZE=10240 +HUMAN_LOG_INTERVAL=5 +PORT=8080 + +# Настройки камеры (если используется) +CAMERA_URL=http://127.0.0.1:1984/api/stream.mjpeg?src=cam_mjpeg diff --git a/debian/gpio-monitor-server.service b/debian/gpio-monitor-server.service new file mode 100644 index 0000000..cff0984 --- /dev/null +++ b/debian/gpio-monitor-server.service @@ -0,0 +1,39 @@ +[Unit] +Description=GPIO Monitor Server +After=network.target +Wants=network.target + +[Service] +Type=simple +User=gpio-monitor +Group=gpio-monitor +WorkingDirectory=/opt/gpio-monitoring + +# Запуск сервера с параметрами +ExecStart=/usr/bin/gpio-monitor-server \ + -pipe /tmp/gpio_pipe \ + -retention-hours=72 \ + -retention-mb=2000 \ + -retention-interval=60 \ + -rotation-check-interval=1 \ + -buffer-size=10240 \ + -human-log-interval=5 + +# Перезапуск при падении +Restart=on-failure +RestartSec=10s + +# Лимиты и безопасность +LimitNOFILE=4096 +NoNewPrivileges=yes + +# Логирование +StandardOutput=journal +StandardError=journal +SyslogIdentifier=gpio-monitor + +# Настройки для доступа к GPIO +AmbientCapabilities=CAP_SYS_RAWIO + +[Install] +WantedBy=multi-user.target diff --git a/debian/install b/debian/install new file mode 100644 index 0000000..11b963d --- /dev/null +++ b/debian/install @@ -0,0 +1,2 @@ +# Бинарник будет установлен в /usr/bin автоматически +debian/usr/bin/gpio-logs usr/bin/ diff --git a/debian/postinst b/debian/postinst new file mode 100644 index 0000000..b8171ae --- /dev/null +++ b/debian/postinst @@ -0,0 +1,33 @@ +#!/bin/bash +# chmod +x debian/postinst + +set -e + +case "$1" in + configure) + # Создаем директории + mkdir -p /var/log/gpio-monitoring + mkdir -p /var/lib/gpio-monitoring + mkdir -p /opt/gpio-monitoring/web + + # Устанавливаем права + chown -R gpio-monitor:gpio-monitor /var/log/gpio-monitoring + chown -R gpio-monitor:gpio-monitor /var/lib/gpio-monitoring + chown -R gpio-monitor:gpio-monitor /opt/gpio-monitoring + + # Перезагружаем systemd + systemctl daemon-reload 2>/dev/null || true + + # Включаем сервис, но не запускаем автоматически + systemctl enable gpio-monitor-server.service 2>/dev/null || true + systemctl start gpio-monitor-server.service + + # Создаем symlink для логов + ln -sf /var/log/gpio-monitoring /opt/gpio-monitoring/logs 2>/dev/null || true + + echo "GPIO Monitor Server установлен" + echo "Для запуска: sudo systemctl start gpio-monitor-server" + ;; +esac + +exit 0 diff --git a/debian/postrm b/debian/postrm new file mode 100644 index 0000000..5b28f4e --- /dev/null +++ b/debian/postrm @@ -0,0 +1,19 @@ +#!/bin/bash +#chmod +x debian/postrm + +set -e + +case "$1" in + purge) + # Удаляем пользователя только при полной очистке + userdel gpio-monitor 2>/dev/null || true + groupdel gpio-monitor 2>/dev/null || true + + # Удаляем директории + rm -rf /var/log/gpio-monitoring + rm -rf /var/lib/gpio-monitoring + rm -rf /opt/gpio-monitoring + ;; +esac + +exit 0 diff --git a/debian/preinst b/debian/preinst new file mode 100644 index 0000000..e41c319 --- /dev/null +++ b/debian/preinst @@ -0,0 +1,24 @@ +#!/bin/bash + +#chmod +x debian/preinst + +set -e + +# Создаем пользователя и группу +if ! getent group gpio-monitor >/dev/null; then + groupadd --system gpio-monitor +fi + +if ! getent passwd gpio-monitor >/dev/null; then + useradd --system \ + --gid gpio-monitor \ + --home /var/lib/gpio-monitoring \ + --shell /usr/sbin/nologin \ + --comment "GPIO Monitor Service" \ + gpio-monitor +fi + +# Добавляем пользователя в нужные группы для доступа к GPIO +usermod -a -G gpio,dialout,gpio-monitor gpio-monitor 2>/dev/null || true + +exit 0 diff --git a/debian/prerm b/debian/prerm new file mode 100644 index 0000000..d5a8416 --- /dev/null +++ b/debian/prerm @@ -0,0 +1,15 @@ +#!/bin/bash +#chmod +x debian/prerm + +set -e + +case "$1" in + remove|upgrade|deconfigure) + # Останавливаем сервис + systemctl stop gpio-monitor-server.service 2>/dev/null || true + systemctl disable gpio-monitor-server.service 2>/dev/null || true + systemctl daemon-reload 2>/dev/null || true + ;; +esac + +exit 0 diff --git a/debian/rules b/debian/rules new file mode 100644 index 0000000..be77094 --- /dev/null +++ b/debian/rules @@ -0,0 +1,24 @@ +#!/usr/bin/make -f + +# chmod +x debian/rules +# Удаляем стандартные правила +%: + dh $@ --buildsystem=golang --with=golang + +# Переопределяем сборку +override_dh_auto_build: + # Сборка фронтенда + cd cmd/server/web && npm install && npm run build + # Сборка бекенда + GOOS=linux GOARCH=arm64 go build -ldflags="-s -w" -o debian/gpio-monitor-server/usr/bin/gpio-monitor-server ./cmd/server + +# Установка файлов +override_dh_install: + dh_install + # Копируем статические файлы для веба + mkdir -p debian/gpio-monitor-server/opt/gpio-monitoring/web + cp -r cmd/server/web/dist debian/gpio-monitor-server/opt/gpio-monitoring/web/ + cp -r cmd/server/web/css debian/gpio-monitor-server/opt/gpio-monitoring/web/ + cp -r cmd/server/web/fonts debian/gpio-monitor-server/opt/gpio-monitoring/web/ + cp cmd/server/web/*.html debian/gpio-monitor-server/opt/gpio-monitoring/web/ 2>/dev/null || true + cp cmd/server/web/favicon.png debian/gpio-monitor-server/opt/gpio-monitoring/web/ 2>/dev/null || true diff --git a/debian/usr/bin/gpio-logs b/debian/usr/bin/gpio-logs new file mode 100644 index 0000000..7cccc86 --- /dev/null +++ b/debian/usr/bin/gpio-logs @@ -0,0 +1,31 @@ +#!/bin/bash +# Просмотр логов GPIO Monitor + +if [ "$1" = "-f" ]; then + sudo journalctl -u gpio-monitor-server -f +elif [ "$1" = "-e" ]; then + sudo tail -f /var/log/gpio-monitoring/events_human.log +elif [ "$1" = "-g" ]; then + sudo tail -f /var/log/gpio-monitoring/gpio_human.log +elif [ "$1" = "-d" ]; then + sudo tail -f /var/log/gpio-monitoring/data/*.bin 2>/dev/null | xxd +elif [ "$1" = "-h" ] || [ "$1" = "--help" ]; then + echo "Использование: gpio-logs [OPTION]" + echo " -f Просмотр логов сервиса (journalctl)" + echo " -e Просмотр логов событий" + echo " -g Просмотр GPIO логов (human-readable)" + echo " -d Просмотр бинарных данных (raw)" + echo " -h Показать эту справку" +else + echo "Использование: gpio-logs [OPTION]" + echo " -f Просмотр логов сервиса (journalctl)" + echo " -e Просмотр логов событий" + echo " -g Просмотр GPIO логов (human-readable)" + echo " -d Просмотр бинарных данных (raw)" + echo " -h Показать эту справку" + echo "" + echo "Примеры:" + echo " gpio-logs -f # следить за логами сервиса" + echo " gpio-logs -e # смотреть события" + echo " gpio-logs -g # смотреть GPIO логи" +fi diff --git a/internal/logger/paths.go b/internal/logger/paths.go index cc1e906..12a1e9e 100644 --- a/internal/logger/paths.go +++ b/internal/logger/paths.go @@ -7,7 +7,17 @@ import ( // GetDataDir возвращает стандартную директорию для данных приложения func GetDataDir() (string, error) { - // Используем XDG Base Directory Specification + // Проверяем, установлен ли пакет (существует ли /opt/gpio-monitoring) + if _, err := os.Stat("/opt/gpio-monitoring"); err == nil { + // Используем стандартную директорию для deb пакета + dataDir := "/var/lib/gpio-monitoring" + if err := os.MkdirAll(dataDir, 0755); err != nil { + return "", err + } + return dataDir, nil + } + + // Для разработки - используем XDG Base Directory Specification homeDir, err := os.UserHomeDir() if err != nil { return "", err @@ -15,8 +25,6 @@ func GetDataDir() (string, error) { // ~/.local/share/gpio-monitoring dataDir := filepath.Join(homeDir, ".local", "share", "gpio-monitoring") - - // Создаём директорию если её нет if err := os.MkdirAll(dataDir, 0755); err != nil { return "", err } @@ -26,6 +34,16 @@ func GetDataDir() (string, error) { // GetLogsDir возвращает директорию для логов func GetLogsDir() (string, error) { + // Проверяем, установлен ли пакет + if _, err := os.Stat("/opt/gpio-monitoring"); err == nil { + logsDir := "/var/log/gpio-monitoring" + if err := os.MkdirAll(logsDir, 0755); err != nil { + return "", err + } + return logsDir, nil + } + + // Для разработки dataDir, err := GetDataDir() if err != nil { return "", err @@ -82,4 +100,27 @@ func GetGPIOLogPath() (string, error) { } return filepath.Join(logsDir, "gpio_human.log"), nil +} + +// GetWebDir возвращает директорию с веб-файлами +func GetWebDir() string { + // Проверяем стандартные пути + possiblePaths := []string{ + "/opt/gpio-monitoring/web", + "/usr/share/gpio-monitoring/web", + "./cmd/server/web", + "../cmd/server/web", + } + + for _, path := range possiblePaths { + if _, err := os.Stat(path); err == nil { + // Проверяем, что есть index.html + if _, err := os.Stat(filepath.Join(path, "index.html")); err == nil { + return path + } + } + } + + // Fallback для разработки + return "./cmd/server/web" } \ No newline at end of file