update_manager.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import subprocess
  2. import logging
  3. import os
  4. from pathlib import Path
  5. from datetime import datetime
  6. # Configure logging
  7. logger = logging.getLogger(__name__)
  8. # Trigger file location - visible to both container (/app) and host
  9. TRIGGER_FILE = Path("/app/.update-trigger")
  10. def check_git_updates():
  11. """Check for available Git updates."""
  12. try:
  13. logger.debug("Checking for Git updates")
  14. subprocess.run(["git", "fetch", "--tags", "--force"], check=True)
  15. latest_remote_tag = subprocess.check_output(
  16. ["git", "describe", "--tags", "--abbrev=0", "origin/main"]
  17. ).strip().decode()
  18. latest_local_tag = subprocess.check_output(
  19. ["git", "describe", "--tags", "--abbrev=0"]
  20. ).strip().decode()
  21. tag_behind_count = 0
  22. if latest_local_tag != latest_remote_tag:
  23. tags = subprocess.check_output(
  24. ["git", "tag", "--merged", "origin/main"], text=True
  25. ).splitlines()
  26. found_local = False
  27. for tag in tags:
  28. if tag == latest_local_tag:
  29. found_local = True
  30. elif found_local:
  31. tag_behind_count += 1
  32. if tag == latest_remote_tag:
  33. break
  34. updates_available = latest_remote_tag != latest_local_tag
  35. logger.info(f"Updates available: {updates_available}, {tag_behind_count} versions behind")
  36. return {
  37. "updates_available": updates_available,
  38. "tag_behind_count": tag_behind_count,
  39. "latest_remote_tag": latest_remote_tag,
  40. "latest_local_tag": latest_local_tag,
  41. }
  42. except subprocess.CalledProcessError as e:
  43. logger.error(f"Error checking Git updates: {e}")
  44. return {
  45. "updates_available": False,
  46. "tag_behind_count": 0,
  47. "latest_remote_tag": None,
  48. "latest_local_tag": None,
  49. }
  50. def is_update_watcher_available() -> bool:
  51. """Check if the update watcher service is running on the host.
  52. The watcher service monitors the trigger file and runs 'dw update'
  53. when it detects a trigger.
  54. """
  55. # The watcher is available if we can write to the trigger file location
  56. # and the parent directory exists (indicating proper volume mount)
  57. try:
  58. return TRIGGER_FILE.parent.exists() and os.access(TRIGGER_FILE.parent, os.W_OK)
  59. except Exception:
  60. return False
  61. def trigger_host_update(message: str = None) -> tuple[bool, str | None]:
  62. """Signal the host to run 'dw update' by creating a trigger file.
  63. The update watcher service on the host monitors this file and
  64. executes the full update process when triggered.
  65. Args:
  66. message: Optional message to include in the trigger file
  67. Returns:
  68. Tuple of (success, error_message)
  69. """
  70. try:
  71. # Write trigger file with timestamp and optional message
  72. trigger_content = f"triggered_at={datetime.now().isoformat()}\n"
  73. if message:
  74. trigger_content += f"message={message}\n"
  75. TRIGGER_FILE.write_text(trigger_content)
  76. logger.info(f"Update trigger created at {TRIGGER_FILE}")
  77. return True, None
  78. except Exception as e:
  79. error_msg = f"Failed to create update trigger: {e}"
  80. logger.error(error_msg)
  81. return False, error_msg
  82. def update_software():
  83. """Trigger a software update on the host machine.
  84. When running in Docker, this creates a trigger file that the host's
  85. update-watcher service monitors. The watcher then runs 'dw update'
  86. on the host, which properly handles:
  87. - Git pull for latest code
  88. - Docker image pulls
  89. - Container recreation with new images
  90. - Cleanup of old images
  91. Returns:
  92. Tuple of (success, error_message, error_log)
  93. """
  94. logger.info("Initiating software update...")
  95. # Check if we can trigger host update
  96. if not is_update_watcher_available():
  97. error_msg = (
  98. "Update watcher not available. The update-watcher service may not be "
  99. "installed or the volume mount is not configured correctly. "
  100. "Please run 'dw update' manually from the host machine."
  101. )
  102. logger.error(error_msg)
  103. return False, error_msg, [error_msg]
  104. # Trigger the host update
  105. success, error = trigger_host_update("Triggered from web UI")
  106. if success:
  107. logger.info("Update triggered successfully - host will process shortly")
  108. return True, None, None
  109. else:
  110. return False, error, [error]