Sfoglia il codice sorgente

add updatetime service

xuqiang 4 mesi fa
parent
commit
8eab7a85c0

+ 24 - 0
services/updatetime/Makefile

@@ -0,0 +1,24 @@
+build:
+	pyinstaller updatetime.spec
+
+release:
+	mkdir -p ./release/updatetime
+	rm -rf ./release/updatetime/*
+	pyinstaller updatetime.spec
+	cp -f ./run.sh ./release/updatetime
+	cp -f ./install.sh ./release/updatetime
+	cp -r ./dist ./release/updatetime/bin
+	cp -f ./updatetime.service ./release/updatetime
+
+install:
+	mkdir -p /usr/local/updatetime
+	cp -r ./dist /usr/local/updatetime/bin
+	cp -f ./run.sh /usr/local/updatetime
+	cp updatetime.service  /usr/lib/systemd/system
+	systemctl enable updatetime
+	systemctl start updatetime
+
+.PHONY:clean
+clean:
+	rm -rf build
+	rm -rf dist

+ 5 - 0
services/updatetime/init.sh

@@ -0,0 +1,5 @@
+#!bin/bash
+
+python -m venv .venv
+source .venv/bin/activate
+pip install -r requirements.txt

+ 9 - 0
services/updatetime/install.sh

@@ -0,0 +1,9 @@
+#!/bin/bash
+
+mkdir -p /usr/local/updatetime/bin
+cp -f ./bin/updatetime /usr/local/updatetime/bin
+cp -f ./run.sh /usr/local/updatetime
+cp -f ./updatetime.service /usr/lib/systemd/system
+
+systemctl daemon-reload
+systemctl enable --now updatetime

+ 65 - 0
services/updatetime/main.py

@@ -0,0 +1,65 @@
+from gevent import pywsgi
+from flask import Flask, request, send_from_directory, render_template, jsonify
+import os
+import pytz
+import systime
+
+app = Flask(__name__)
+
+@app.route('/update/time', methods=['POST'])
+def update_time():
+    if request.is_json:
+        try:
+            json_data = request.get_json()
+            print("update time:", json_data)
+            ret = systime.update_system_datetime(json_data["timezone"], json_data["year"], json_data["month"], json_data["date"], json_data["hour"], json_data["minute"])
+            if(ret == 0):
+                response = jsonify({'message': 'Successfully update time'})
+                response.status_code = 200
+                return response
+            else:
+                response = jsonify({'message': 'Failed update time'})
+                response.status_code = 400
+                return response
+        except:
+            response = jsonify({'message': 'Invalid json'})
+            response.status_code = 400
+            return response
+    else:
+        response = jsonify({'message': 'Required json'})
+        response.status_code = 400
+        return response
+
+@app.route('/timezones', methods=['GET'])
+def timezones():
+    try:
+        timezones_list = list(pytz.all_timezones)
+        response = jsonify({
+            'message': 'Successfully',
+            'timezones': timezones_list
+        })
+        response.status_code = 200
+        return response
+    except Exception as e:
+        response = jsonify({"message": str(e)})
+        response.status_code = 500
+        return response
+
+@app.route('/heartbeat', methods=['GET'])
+def heartbeat():
+    response = jsonify({'message': 'Connected'})
+    response.status_code = 200
+    return response
+
+def main():
+    print("Starting server, listen on 18001...")
+    # app.run(host='0.0.0.0', port=8000, debug=True)
+    server = pywsgi.WSGIServer(('0.0.0.0', 18001), app)
+    try:
+        server.serve_forever()
+    except KeyboardInterrupt:
+        print("Server stopped by user")
+        server.stop()
+
+if __name__ == '__main__':
+    main()

+ 4 - 0
services/updatetime/requirements.txt

@@ -0,0 +1,4 @@
+Flask==3.1.2
+gevent==25.9.1
+pytz==2025.2
+pyinstaller==6.17.0

+ 7 - 0
services/updatetime/run.sh

@@ -0,0 +1,7 @@
+#/bin/bash
+
+# disable ntp
+timedatectl set-ntp false
+# start service
+chmod +x /usr/local/updatetime/bin/updatetime
+/usr/local/updatetime/bin/updatetime

+ 44 - 0
services/updatetime/systime.py

@@ -0,0 +1,44 @@
+import subprocess
+
+def set_timezone(timezone: str) -> int:
+    """使用 timedatectl 设置系统时区"""
+    try:
+        ret = subprocess.run(
+            ["timedatectl", "set-timezone", timezone],
+            check=True,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            text=True
+        )
+        return 0
+    except subprocess.CalledProcessError as e:
+        print("设置时区失败:", e.stderr)
+        return -1
+
+
+def set_system_time(year, month, day, hour, minute, second=0) -> int:
+    """使用 timedatectl 设置系统时间"""
+    time_str = f"{year}-{month:02d}-{day:02d} {hour:02d}:{minute:02d}:{second:02d}"
+    try:
+        ret = subprocess.run(
+            ["timedatectl", "set-time", time_str],
+            check=True,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            text=True
+        )
+        return 0
+    except subprocess.CalledProcessError as e:
+        print("设置时间失败:", e.stderr)
+        return -1
+
+def update_system_datetime(timezone, year, month, day, hour, minute, second=0):
+    # 先设置时区
+    if set_timezone(timezone) != 0:
+        return -1
+
+    # 再设置时间
+    if set_system_time(year, month, day, hour, minute, second) != 0:
+        return -2
+
+    return 0

+ 6 - 0
services/updatetime/uninstall.sh

@@ -0,0 +1,6 @@
+#!/bin/bash
+
+systemctl disable --now updatetime.service
+rm -r /usr/local/updatetime
+rm /usr/lib/systemd/system/updatetime.service
+systemctl daemon-reload

+ 20 - 0
services/updatetime/updatetime.service

@@ -0,0 +1,20 @@
+[Unit]
+Description=Update-System-Time
+After=network.target
+Wants=network.target
+
+[Service]
+Type=simple
+User=root
+Group=root
+WorkingDirectory=/usr/local/updatetime
+ExecStart=bash run.sh
+Restart=always
+RestartSec=3
+
+# 如果需要日志
+StandardOutput=journal
+StandardError=journal
+
+[Install]
+WantedBy=multi-user.target

+ 38 - 0
services/updatetime/updatetime.spec

@@ -0,0 +1,38 @@
+# -*- mode: python ; coding: utf-8 -*-
+
+
+a = Analysis(
+    ['main.py'],
+    pathex=[],
+    binaries=[],
+    datas=[],
+    hiddenimports=[],
+    hookspath=[],
+    hooksconfig={},
+    runtime_hooks=[],
+    excludes=[],
+    noarchive=False,
+    optimize=0,
+)
+pyz = PYZ(a.pure)
+
+exe = EXE(
+    pyz,
+    a.scripts,
+    a.binaries,
+    a.datas,
+    [],
+    name='updatetime',
+    debug=False,
+    bootloader_ignore_signals=False,
+    strip=False,
+    upx=True,
+    upx_exclude=[],
+    runtime_tmpdir=None,
+    console=True,
+    disable_windowed_traceback=False,
+    argv_emulation=False,
+    target_arch=None,
+    codesign_identity=None,
+    entitlements_file=None,
+)