Skip to content

Commit

Permalink
web - updated update-handling
Browse files Browse the repository at this point in the history
  • Loading branch information
superstes committed Oct 26, 2021
1 parent 31b7ba4 commit bf9a262
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 61 deletions.
3 changes: 0 additions & 3 deletions code/web/base/ga/config/shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,5 @@
LOG_SERVICE_LOG_JOURNAL = "/bin/journalctl -u %s --no-pager -n %s"

# update
UPDATE_PATH_BACKUP = '/var/backups/ga/update'
UPDATE_PATH_CLONE = '/tmp/ga/update'
UPDATE_SERVICE = 'ga_update'
UPDATE_CONFIG_FILE = '/tmp/ga_update.conf'
UPDATE_TIMESTAMP = '%Y-%m-%d_%H-%M'
95 changes: 37 additions & 58 deletions code/web/base/ga/subviews/system/update.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import user_passes_test
import requests
from datetime import datetime
from threading import Thread

from core.utils.test import test_tcp_stream

from ...user import authorized_to_read, authorized_to_write
from ..handlers import Pseudo404, Pseudo500
from ..handlers import Pseudo404
from ...config import shared as config
from ...utils.helper import get_server_config, web_subprocess, develop_log
from ...utils.helper import get_server_config, web_subprocess
from ...utils.basic import str_to_list

FORCE_UPDATE = False
Expand All @@ -18,6 +16,7 @@
@user_passes_test(authorized_to_read, login_url=config.DENIED_URL)
def update_view(request):
current_version = get_server_config(setting='version')
# todo: let user supply 'migrate-db' and other flags

if request.method == 'GET':
if 'type' in request.GET:
Expand Down Expand Up @@ -55,66 +54,46 @@ def update_view(request):

@user_passes_test(authorized_to_write, login_url=config.DENIED_URL)
def update_start(request, current_version):
config_type = request.POST['type']
clone_directory = f"{config.UPDATE_PATH_CLONE}/{datetime.now().strftime(config.UPDATE_TIMESTAMP)}"
backup_directory = f"{config.UPDATE_PATH_BACKUP}/{datetime.now().strftime(config.UPDATE_TIMESTAMP)}"
try:
update_method = request.POST['type']
repo_path = request.POST['path'] if 'path' in request.POST else None

def start_update_service(clone_dir: str):
with open(config.UPDATE_CONFIG_FILE, 'w') as file:
file.write(
f"METHOD={config_type}\n"
f"VERSION={update_release}\n"
f"COMMIT={update_commit}\n"
f"FORCE={FORCE_UPDATE}\n"
f"PATH_BACKUP={backup_directory}\n"
f"PATH_UPDATE={clone_dir}\n"
f"PATH_CORE={get_server_config(setting='path_core')}\n"
f"PATH_HOME_CORE={get_server_config(setting='path_home_core')}\n"
f"PATH_WEB={get_server_config(setting='path_web')}\n"
f"PATH_WEB_STATIC={get_server_config(setting='path_web_static')}\n"
f"PATH_HOME_WEB={get_server_config(setting='path_home_web')}\n"
f"PATH_LOG={get_server_config(setting='path_log')}\n"
f"SQL_DB={get_server_config(setting='sql_database')}\n"
)
web_subprocess(f'sudo systemctl start {config.UPDATE_SERVICE}.service')
if update_method not in ['online', 'offline']:
raise KeyError('Got unsupported update method')

if config_type == 'online':
update_release = request.POST['release']
update_commit = request.POST['commit'] if request.POST['commit'] != config.WEBUI_EMPTY_CHOICE else None
update = False
update_fail_msg = 'Unable to download source code.'

if update_commit is not None:
_clone = web_subprocess(f"git clone https://github.com/superstes/growautomation.git --single-branch {clone_directory}", out_error=True)[1]
develop_log(request, f"Downloading source-code: \"{_clone}\"")
if _clone.find('fatal') == -1 and _clone.find('error') == -1:
_set_commit = web_subprocess(f"cd {clone_directory} && git reset --hard {update_commit}")
develop_log(request, f"Setting commit: \"{_set_commit}\"")
if _set_commit.startswith('HEAD is now'):
update = True

else:
update_fail_msg = f"Unable to get commit {update_commit}."

elif float(update_release) != float(current_version):
_clone = web_subprocess(f"git clone https://github.com/superstes/growautomation.git --depth 1 --branch {update_release} --single-branch {clone_directory}", out_error=True)[1]
develop_log(request, f"Downloading source-code: \"{_clone}\"")
if _clone.find('fatal') == -1 and _clone.find('error') == -1:
update = True

if update:
Thread(target=start_update_service(clone_dir=clone_directory)).start()
return redirect('/system/update/status/')

if request.POST['commit'] != config.WEBUI_EMPTY_CHOICE:
update_type = 'commit'
update_commit = request.POST['commit']

else:
raise Pseudo500(ga={'request': request, 'msg': update_fail_msg})
update_type = 'release'
update_commit = None

if float(update_release) <= float(current_version):
raise KeyError('Got unsupported target version!')

elif config_type == 'offline':
Thread(target=start_update_service(clone_dir=request.POST['path'])).start()
with open(config.UPDATE_CONFIG_FILE, 'w') as file:
file.write(
f"ga_update_type={update_type}\n"
f"ga_update_method={update_method}\n"
f"ga_update_release={update_release}\n"
f"ga_update_commit={update_commit}\n"
f"ga_update_path_repo={repo_path}\n"
f"ga_update_path_core={get_server_config(setting='path_core')}\n"
f"ga_update_path_home_core={get_server_config(setting='path_home_core')}\n"
f"ga_update_path_web={get_server_config(setting='path_web')}\n"
f"ga_update_path_web_static={get_server_config(setting='path_web_static')}\n"
f"ga_update_path_home_web={get_server_config(setting='path_home_web')}\n"
f"ga_update_path_log={get_server_config(setting='path_log')}\n"
)

web_subprocess(f'sudo systemctl start {config.UPDATE_SERVICE}.service')
return redirect('/system/update/status/')

else:
raise Pseudo404(ga={'request': request, 'msg': "Got unsupported update method."})
except KeyError as error:
raise Pseudo404(ga={'request': request, 'msg': str(error)})


@user_passes_test(authorized_to_read, login_url=config.DENIED_URL)
Expand All @@ -124,15 +103,15 @@ def update_status_view(request):
redirect_time = 30
log_data = str_to_list(web_subprocess(config.LOG_SERVICE_LOG_STATUS % config.UPDATE_SERVICE))

if log_data[2].find('inactive') != -1:
if log_data[2].find('activating') == -1:
reload_time = 0
redirect_time = 0
status = 'Finished'

if log_data[-3].find('Succeeded') != -1:
status = 'Finished successfully!'

elif log_data[-3].find('Failed') != -1:
elif log_data[2].find('failed') != -1 or log_data[-3].find('Failed') != -1:
status = 'Failed!'

return render(request, 'system/update/status.html', context={
Expand Down
4 changes: 4 additions & 0 deletions code/web/base/ga/templates/system/update/status.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ <h2>Log data:</h2>
<li class="ga-file-content-line">{{ line }}</li>
{% endfor %}
</ol>
<div class="alert alert-warning">
If the update fails hard you might need to read the update logs via:<br>
'journalctl -u ga_update.service --no-pager --full -n{LINECOUNT}'
</div>
{% include "../../js/auto_reload.html" %}
{% if redirect_time != 0 %}
<script>
Expand Down

0 comments on commit bf9a262

Please sign in to comment.