Przeglądaj źródła

add docker compose restart

tuanchris 2 miesięcy temu
rodzic
commit
96a00c733d
3 zmienionych plików z 119 dodań i 1 usunięć
  1. 22 1
      dune-weaver-touch/backend.py
  2. 30 0
      main.py
  3. 67 0
      templates/base.html

+ 22 - 1
dune-weaver-touch/backend.py

@@ -671,7 +671,28 @@ class Backend(QObject):
     @Slot()
     def sendHome(self):
         print("🏠 Sending home command...")
-        asyncio.create_task(self._api_call("/send_home"))
+        asyncio.create_task(self._send_home())
+
+    async def _send_home(self):
+        """Send home command without timeout - homing can take up to 90 seconds."""
+        if not self.session:
+            self.errorOccurred.emit("Backend not ready")
+            return
+
+        try:
+            print("🏠 Calling /send_home (no timeout - homing can take up to 90s)...")
+            async with self.session.post(f"{self.base_url}/send_home") as resp:
+                print(f"🏠 Home command response status: {resp.status}")
+                if resp.status == 200:
+                    response_data = await resp.json()
+                    print(f"✅ Home command successful: {response_data}")
+                else:
+                    print(f"❌ Home command failed with status: {resp.status}")
+                    response_text = await resp.text()
+                    self.errorOccurred.emit(f"Home failed: {resp.status} - {response_text}")
+        except Exception as e:
+            print(f"💥 Exception in home command: {e}")
+            self.errorOccurred.emit(str(e))
     
     @Slot()
     def moveToCenter(self):

+ 30 - 0
main.py

@@ -2100,6 +2100,36 @@ async def shutdown_system():
             status_code=500
         )
 
+@app.post("/api/system/restart")
+async def restart_system():
+    """Restart the Docker containers using docker compose"""
+    try:
+        logger.warning("Restart initiated via API")
+
+        # Schedule restart command after a short delay to allow response to be sent
+        def delayed_restart():
+            time.sleep(2)  # Give time for response to be sent
+            try:
+                # Use docker compose restart to restart the containers
+                subprocess.run(["docker", "compose", "restart"], check=True)
+                logger.info("Docker compose restart command executed successfully")
+            except FileNotFoundError:
+                logger.error("docker command not found")
+            except Exception as e:
+                logger.error(f"Error executing docker compose restart: {e}")
+
+        import threading
+        restart_thread = threading.Thread(target=delayed_restart)
+        restart_thread.start()
+
+        return {"success": True, "message": "System restart initiated"}
+    except Exception as e:
+        logger.error(f"Error initiating restart: {e}")
+        return JSONResponse(
+            content={"success": False, "message": str(e)},
+            status_code=500
+        )
+
 def entrypoint():
     import uvicorn
     logger.info("Starting FastAPI server on port 8080...")

+ 67 - 0
templates/base.html

@@ -116,6 +116,9 @@
       .dark #shutdown-button:hover {
         background-color: #404040;
       }
+      .dark #restart-button:hover {
+        background-color: #404040;
+      }
       .dark #theme-toggle:hover {
         background-color: #404040;
       }
@@ -289,6 +292,14 @@
             >
               <span class="material-icons" id="theme-toggle-icon">dark_mode</span>
             </button>
+            <button
+              id="restart-button"
+              class="p-1.5 flex rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-amber-500"
+              aria-label="Restart system"
+              title="Restart Docker Containers"
+            >
+              <span class="material-icons text-amber-600">restart_alt</span>
+            </button>
             <button
               id="shutdown-button"
               class="p-1.5 flex rounded-lg hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-red-500"
@@ -733,6 +744,62 @@
         });
       });
 
+      // Restart button functionality
+      document.addEventListener('DOMContentLoaded', function() {
+        const restartButton = document.getElementById('restart-button');
+
+        // Restart button click handler
+        restartButton.addEventListener('click', async () => {
+          const confirmed = confirm('Are you sure you want to restart the application?\n\nThis will restart the Docker containers.\nThe page will reload automatically when the service is back online.');
+
+          if (!confirmed) return;
+
+          try {
+            showStatusMessage('Initiating restart...', 'warning');
+
+            const response = await fetch('/api/system/restart', { method: 'POST' });
+            const data = await response.json();
+
+            if (data.success) {
+              showStatusMessage('System is restarting... Page will reload when ready.', 'success');
+
+              // Start checking if the server is back online
+              setTimeout(() => {
+                checkServerAndReload();
+              }, 3000);
+            } else {
+              showStatusMessage('Restart failed: ' + data.message, 'error');
+            }
+          } catch (error) {
+            showStatusMessage('Failed to restart: ' + error.message, 'error');
+          }
+        });
+
+        // Function to check if server is back online and reload
+        function checkServerAndReload() {
+          const checkInterval = setInterval(async () => {
+            try {
+              const response = await fetch('/api/version', { method: 'GET' });
+              if (response.ok) {
+                clearInterval(checkInterval);
+                showStatusMessage('Server is back online. Reloading...', 'success');
+                setTimeout(() => {
+                  window.location.reload();
+                }, 1000);
+              }
+            } catch (error) {
+              // Server not ready yet, keep checking
+              console.log('Server not ready yet, retrying...');
+            }
+          }, 2000);
+
+          // Stop checking after 60 seconds
+          setTimeout(() => {
+            clearInterval(checkInterval);
+          }, 60000);
+        }
+      });
+
       // Update indicator functionality
       document.addEventListener('DOMContentLoaded', async function() {
         const updateIndicator = document.getElementById('update-indicator');