-
-
Notifications
You must be signed in to change notification settings - Fork 277
/
app.py
3326 lines (2749 loc) · 118 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright (c) 2024 YunoHost Contributors
#
# This file is part of YunoHost (see https://yunohost.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import time
import glob
import os
import shutil
import yaml
import re
import subprocess
import tempfile
import copy
from typing import TYPE_CHECKING, List, Tuple, Dict, Any, Iterator, Optional, Union
from packaging import version
from logging import getLogger
from pathlib import Path
from moulinette import Moulinette, m18n
from moulinette.utils.process import run_commands, check_output
from moulinette.utils.filesystem import (
read_file,
read_json,
read_toml,
write_to_file,
write_to_json,
cp,
rm,
chown,
chmod,
)
from yunohost.utils.i18n import _value_for_locale
from yunohost.utils.error import YunohostError, YunohostValidationError
from yunohost.utils.system import (
free_space_in_directory,
dpkg_is_broken,
get_ynh_package_version,
system_arch,
debian_version,
human_to_binary,
binary_to_human,
ram_available,
)
from yunohost.log import is_unit_operation, OperationLogger
from yunohost.app_catalog import ( # noqa
app_catalog,
app_search,
_load_apps_catalog,
APPS_CATALOG_LOGOS,
)
if TYPE_CHECKING:
from pydantic.typing import AbstractSetIntStr, MappingIntStrAny
from yunohost.utils.configpanel import RawSettings
from yunohost.utils.form import FormModel
logger = getLogger("yunohost.app")
APPS_SETTING_PATH = "/etc/yunohost/apps/"
APP_TMP_WORKDIRS = "/var/cache/yunohost/app_tmp_work_dirs"
re_app_instance_name = re.compile(
r"^(?P<appid>[\w-]+?)(__(?P<appinstancenb>[1-9][0-9]*))?$"
)
APP_REPO_URL = re.compile(
r"^https://[a-zA-Z0-9-_.]+/[a-zA-Z0-9-_./~]+/[a-zA-Z0-9-_.]+_ynh(/?(-/)?(tree|src/(branch|tag|commit))/[a-zA-Z0-9-_.]+)?(\.git)?/?$"
)
APP_FILES_TO_COPY = [
"manifest.json",
"manifest.toml",
"actions.json",
"actions.toml",
"config_panel.toml",
"scripts",
"conf",
"hooks",
"doc",
]
PORTAL_SETTINGS_DIR = "/etc/yunohost/portal"
def app_list(full=False, upgradable=False):
"""
List installed apps
"""
out = []
for app_id in sorted(_installed_apps()):
try:
app_info_dict = app_info(app_id, full=full, upgradable=upgradable)
except Exception as e:
logger.error(f"Failed to read info for {app_id} : {e}")
continue
app_info_dict["id"] = app_id
if upgradable and app_info_dict.get("upgradable") != "yes":
continue
out.append(app_info_dict)
return {"apps": out}
def app_info(app, full=False, upgradable=False):
"""
Get info for a specific app
"""
from yunohost.domain import _get_raw_domain_settings
from yunohost.permission import user_permission_list
_assert_is_installed(app)
setting_path = os.path.join(APPS_SETTING_PATH, app)
local_manifest = _get_manifest_of_app(setting_path)
permissions = user_permission_list(full=True, absolute_urls=True, apps=[app])[
"permissions"
]
settings = _get_app_settings(app)
ret = {
"description": _value_for_locale(local_manifest["description"]),
"name": permissions.get(app + ".main", {}).get("label", local_manifest["name"]),
"version": local_manifest.get("version", "-"),
}
if "domain" in settings and "path" in settings:
ret["domain_path"] = settings["domain"] + settings["path"]
if not upgradable and not full:
return ret
absolute_app_name, _ = _parse_app_instance_name(app)
from_catalog = _load_apps_catalog()["apps"].get(absolute_app_name, {})
# Check if $app.png exists in the app logo folder, this is a trick to be able to easily customize the logo
# of an app just by creating $app.png (instead of the hash.png) in the corresponding folder
ret["logo"] = (
app
if os.path.exists(f"{APPS_CATALOG_LOGOS}/{app}.png")
else from_catalog.get("logo_hash")
)
ret["upgradable"] = _app_upgradable({**ret, "from_catalog": from_catalog})
if ret["upgradable"] == "yes":
ret["current_version"] = ret.get("version", "?")
ret["new_version"] = from_catalog.get("manifest", {}).get("version", "?")
if ret["current_version"] == ret["new_version"]:
current_revision = settings.get("current_revision", "?")[:7]
new_revision = from_catalog.get("git", {}).get("revision", "?")[:7]
ret["current_version"] = f" ({current_revision})"
ret["new_version"] = f" ({new_revision})"
ret["settings"] = settings
if not full:
return ret
ret["setting_path"] = setting_path
ret["manifest"] = local_manifest
# FIXME: maybe this is not needed ? default ask questions are
# already set during the _get_manifest_of_app earlier ?
ret["manifest"]["install"] = _set_default_ask_questions(
ret["manifest"].get("install", {})
)
ret["from_catalog"] = from_catalog
# Hydrate app notifications and doc
rendered_doc = {}
for pagename, content_per_lang in ret["manifest"]["doc"].items():
for lang, content in content_per_lang.items():
rendered_content = _hydrate_app_template(content, settings)
# Rendered content may be empty because of conditional blocks
if not rendered_content:
continue
if pagename not in rendered_doc:
rendered_doc[pagename] = {}
rendered_doc[pagename][lang] = rendered_content
ret["manifest"]["doc"] = rendered_doc
# Filter dismissed notification
ret["manifest"]["notifications"] = {
k: v
for k, v in ret["manifest"]["notifications"].items()
if not _notification_is_dismissed(k, settings)
}
# Hydrate notifications (also filter uneeded post_upgrade notification based on version)
for step, notifications in ret["manifest"]["notifications"].items():
rendered_notifications = {}
for name, content_per_lang in notifications.items():
for lang, content in content_per_lang.items():
rendered_content = _hydrate_app_template(content, settings)
if not rendered_content:
continue
if name not in rendered_notifications:
rendered_notifications[name] = {}
rendered_notifications[name][lang] = rendered_content
ret["manifest"]["notifications"][step] = rendered_notifications
ret["is_webapp"] = "domain" in settings and settings["domain"] and "path" in settings
if ret["is_webapp"]:
ret["is_default"] = (
_get_raw_domain_settings(settings["domain"]).get("default_app") == app
)
ret["supports_change_url"] = os.path.exists(
os.path.join(setting_path, "scripts", "change_url")
)
ret["supports_backup_restore"] = os.path.exists(
os.path.join(setting_path, "scripts", "backup")
) and os.path.exists(os.path.join(setting_path, "scripts", "restore"))
ret["supports_multi_instance"] = local_manifest.get("integration", {}).get(
"multi_instance", False
)
ret["supports_config_panel"] = os.path.exists(
os.path.join(setting_path, "config_panel.toml")
)
ret["supports_purge"] = (
local_manifest["packaging_format"] >= 2
and local_manifest["resources"].get("data_dir") is not None
)
ret["permissions"] = permissions
ret["label"] = permissions.get(app + ".main", {}).get("label")
if not ret["label"]:
logger.warning(f"Failed to get label for app {app} ?")
ret["label"] = local_manifest["name"]
return ret
def _app_upgradable(app_infos):
# Determine upgradability
app_in_catalog = app_infos.get("from_catalog")
installed_version = _parse_app_version(app_infos.get("version", "0~ynh0"))
version_in_catalog = _parse_app_version(
app_infos.get("from_catalog", {}).get("manifest", {}).get("version", "0~ynh0")
)
if not app_in_catalog:
return "url_required"
# Do not advertise upgrades for bad-quality apps
level = app_in_catalog.get("level", -1)
if (
not (isinstance(level, int) and level >= 5)
or app_in_catalog.get("state") != "working"
):
return "bad_quality"
if installed_version < version_in_catalog:
return "yes"
else:
return "no"
def app_map(app=None, raw=False, user=None):
"""
Returns a map of url <-> app id such as :
{
"domain.tld/foo": "foo__2",
"domain.tld/mail: "rainloop",
"other.tld/": "bar",
"sub.other.tld/pwet": "pwet",
}
When using "raw", the structure changes to :
{
"domain.tld": {
"/foo": {"label": "App foo", "id": "foo__2"},
"/mail": {"label": "Rainloop", "id: "rainloop"},
},
"other.tld": {
"/": {"label": "Bar", "id": "bar"},
},
"sub.other.tld": {
"/pwet": {"label": "Pwet", "id": "pwet"}
}
}
"""
from yunohost.permission import user_permission_list
apps = []
result = {}
if app is not None:
_assert_is_installed(app)
apps = [
app,
]
else:
apps = _installed_apps()
permissions = user_permission_list(full=True, absolute_urls=True, apps=apps)[
"permissions"
]
for app in apps:
app_settings = _get_app_settings(app)
if not app_settings:
continue
if "domain" not in app_settings:
continue
if "path" not in app_settings:
# we assume that an app that doesn't have a path doesn't have an HTTP api
continue
# This 'no_sso' settings sound redundant to not having $path defined ....
# At least from what I can see, all apps using it don't have a path defined ...
if (
"no_sso" in app_settings
): # I don't think we need to check for the value here
continue
# Users must at least have access to the main permission to have access to extra permissions
if user:
if not app + ".main" in permissions:
logger.warning(
f"Uhoh, no main permission was found for app {app} ... sounds like an app was only partially removed due to another bug :/"
)
continue
main_perm = permissions[app + ".main"]
if user not in main_perm["corresponding_users"]:
continue
this_app_perms = {
p: i
for p, i in permissions.items()
if p.startswith(app + ".") and (i["url"] or i["additional_urls"])
}
for perm_name, perm_info in this_app_perms.items():
# If we're building the map for a specific user, check the user
# actually is allowed for this specific perm
if user and user not in perm_info["corresponding_users"]:
continue
perm_label = perm_info["label"]
perm_all_urls = (
[]
+ ([perm_info["url"]] if perm_info["url"] else [])
+ perm_info["additional_urls"]
)
for url in perm_all_urls:
# Here, we decide to completely ignore regex-type urls ...
# Because :
# - displaying them in regular "yunohost app map" output creates
# a pretty big mess when there are multiple regexes for the same
# app ? (c.f. for example lufi)
# - it doesn't really make sense when checking app conflicts to
# compare regexes ? (Or it could in some cases but ugh ?)
#
if url.startswith("re:"):
continue
if not raw:
result[url] = perm_label
else:
if "/" in url:
perm_domain, perm_path = url.split("/", 1)
perm_path = "/" + perm_path
else:
perm_domain = url
perm_path = "/"
if perm_domain not in result:
result[perm_domain] = {}
result[perm_domain][perm_path] = {"label": perm_label, "id": app}
return result
@is_unit_operation()
def app_change_url(operation_logger, app, domain, path):
"""
Modify the URL at which an application is installed.
Keyword argument:
app -- Taget app instance name
domain -- New app domain on which the application will be moved
path -- New path at which the application will be move
"""
from yunohost.utils.form import DomainOption, WebPathOption
from yunohost.hook import hook_exec_with_script_debug_if_failure, hook_callback
from yunohost.service import service_reload_or_restart
installed = _is_installed(app)
if not installed:
raise YunohostValidationError(
"app_not_installed", app=app, all_apps=_get_all_installed_apps_id()
)
if not os.path.exists(
os.path.join(APPS_SETTING_PATH, app, "scripts", "change_url")
):
raise YunohostValidationError("app_change_url_no_script", app_name=app)
old_domain = app_setting(app, "domain")
old_path = app_setting(app, "path")
# Normalize path and domain format
domain = DomainOption.normalize(domain)
old_domain = DomainOption.normalize(old_domain)
path = WebPathOption.normalize(path)
old_path = WebPathOption.normalize(old_path)
if (domain, path) == (old_domain, old_path):
raise YunohostValidationError(
"app_change_url_identical_domains", domain=domain, path=path
)
app_setting_path = os.path.join(APPS_SETTING_PATH, app)
path_requirement = _guess_webapp_path_requirement(app_setting_path)
_validate_webpath_requirement(
{"domain": domain, "path": path}, path_requirement, ignore_app=app
)
if path_requirement == "full_domain" and path != "/":
raise YunohostValidationError("app_change_url_require_full_domain", app=app)
tmp_workdir_for_app = _make_tmp_workdir_for_app(app=app)
# Prepare env. var. to pass to script
env_dict = _make_environment_for_app_script(
app, workdir=tmp_workdir_for_app, action="change_url"
)
env_dict["YNH_APP_OLD_DOMAIN"] = old_domain
env_dict["YNH_APP_OLD_PATH"] = old_path
env_dict["YNH_APP_NEW_DOMAIN"] = domain
env_dict["YNH_APP_NEW_PATH"] = path
env_dict["old_domain"] = old_domain
env_dict["old_path"] = old_path
env_dict["new_domain"] = domain
env_dict["new_path"] = path
env_dict["domain"] = domain
env_dict["path"] = path
env_dict["path_url"] = path
env_dict["change_path"] = "1" if old_path != path else "0"
env_dict["change_domain"] = "1" if old_domain != domain else "0"
if domain != old_domain:
operation_logger.related_to.append(("domain", old_domain))
operation_logger.extra.update({"env": env_dict})
operation_logger.start()
old_nginx_conf_path = f"/etc/nginx/conf.d/{old_domain}.d/{app}.conf"
new_nginx_conf_path = f"/etc/nginx/conf.d/{domain}.d/{app}.conf"
old_nginx_conf_backup = None
if not os.path.exists(old_nginx_conf_path):
logger.warning(
f"Current nginx config file {old_nginx_conf_path} doesn't seem to exist ... wtf ?"
)
else:
old_nginx_conf_backup = read_file(old_nginx_conf_path)
change_url_script = os.path.join(tmp_workdir_for_app, "scripts/change_url")
# Execute App change_url script
change_url_failed = True
try:
(
change_url_failed,
failure_message_with_debug_instructions,
) = hook_exec_with_script_debug_if_failure(
change_url_script,
env=env_dict,
operation_logger=operation_logger,
error_message_if_script_failed=m18n.n("app_change_url_script_failed"),
error_message_if_failed=lambda e: m18n.n(
"app_change_url_failed", app=app, error=e
),
)
finally:
shutil.rmtree(tmp_workdir_for_app)
if change_url_failed:
logger.warning("Restoring initial nginx config file")
if old_nginx_conf_path != new_nginx_conf_path and os.path.exists(
new_nginx_conf_path
):
rm(new_nginx_conf_path, force=True)
if old_nginx_conf_backup:
write_to_file(old_nginx_conf_path, old_nginx_conf_backup)
service_reload_or_restart("nginx")
# restore values modified by app_checkurl
# see begining of the function
app_setting(app, "domain", value=old_domain)
app_setting(app, "path", value=old_path)
raise YunohostError(failure_message_with_debug_instructions, raw_msg=True)
else:
# make sure the domain/path setting are propagated
app_setting(app, "domain", value=domain)
app_setting(app, "path", value=path)
app_ssowatconf()
service_reload_or_restart("nginx")
logger.success(
m18n.n("app_change_url_success", app=app, domain=domain, path=path)
)
hook_callback("post_app_change_url", env=env_dict)
def app_upgrade(
app=[],
url=None,
file=None,
force=False,
no_safety_backup=False,
continue_on_failure=False,
):
"""
Upgrade app
Keyword argument:
file -- Folder or tarball for upgrade
app -- App(s) to upgrade (default all)
url -- Git url to fetch for upgrade
no_safety_backup -- Disable the safety backup during upgrade
"""
from yunohost.hook import (
hook_add,
hook_remove,
hook_callback,
hook_exec_with_script_debug_if_failure,
)
from yunohost.permission import permission_sync_to_user
from yunohost.regenconf import manually_modified_files
from yunohost.utils.legacy import _patch_legacy_helpers
from yunohost.backup import (
backup_list,
backup_create,
backup_delete,
backup_restore,
)
apps = app
# Check if disk space available
if free_space_in_directory("/") <= 512 * 1000 * 1000:
raise YunohostValidationError("disk_space_not_sufficient_update")
# If no app is specified, upgrade all apps
if not apps:
# FIXME : not sure what's supposed to happen if there is a url and a file but no apps...
if not url and not file:
apps = _installed_apps()
elif not isinstance(app, list):
apps = [app]
# Remove possible duplicates
apps = [app_ for i, app_ in enumerate(apps) if app_ not in apps[:i]]
# Abort if any of those app is in fact not installed..
for app_ in apps:
_assert_is_installed(app_)
if len(apps) == 0:
raise YunohostValidationError("apps_already_up_to_date")
if len(apps) > 1:
logger.info(m18n.n("app_upgrade_several_apps", apps=", ".join(apps)))
notifications = {}
failed_to_upgrade_apps = []
for number, app_instance_name in enumerate(apps):
logger.info(m18n.n("app_upgrade_app_name", app=app_instance_name))
app_dict = app_info(app_instance_name, full=True)
if file and isinstance(file, dict):
# We use this dirty hack to test chained upgrades in unit/functional tests
new_app_src = file[app_instance_name]
elif file:
new_app_src = file
elif url:
new_app_src = url
elif app_dict["upgradable"] == "url_required":
logger.warning(m18n.n("custom_app_url_required", app=app_instance_name))
continue
elif app_dict["upgradable"] == "yes" or force:
new_app_src = app_dict["manifest"]["id"]
else:
logger.success(m18n.n("app_already_up_to_date", app=app_instance_name))
continue
manifest, extracted_app_folder = _extract_app(new_app_src)
# Manage upgrade type and avoid any upgrade if there is nothing to do
upgrade_type = "UNKNOWN"
# Get current_version and new version
app_new_version_raw = manifest.get("version", "?")
app_current_version_raw = app_dict.get("version", "?")
app_new_version = _parse_app_version(app_new_version_raw)
app_current_version = _parse_app_version(app_current_version_raw)
if "~ynh" in str(app_current_version_raw) and "~ynh" in str(app_new_version_raw):
if app_current_version >= app_new_version and not force:
# In case of upgrade from file or custom repository
# No new version available
logger.success(m18n.n("app_already_up_to_date", app=app_instance_name))
# Save update time
now = int(time.time())
app_setting(app_instance_name, "update_time", now)
app_setting(
app_instance_name,
"current_revision",
manifest.get("remote", {}).get("revision", "?"),
)
continue
if app_current_version > app_new_version:
upgrade_type = "DOWNGRADE"
elif app_current_version == app_new_version:
upgrade_type = "UPGRADE_SAME"
else:
app_current_version_upstream, _ = str(app_current_version_raw).split("~ynh")
app_new_version_upstream, _ = str(app_new_version_raw).split("~ynh")
if app_current_version_upstream == app_new_version_upstream:
upgrade_type = "UPGRADE_PACKAGE"
else:
upgrade_type = "UPGRADE_APP"
# Check requirements
for name, passed, values, err in _check_manifest_requirements(
manifest, action="upgrade"
):
if not passed:
if name == "ram":
# i18n: confirm_app_insufficient_ram
_ask_confirmation(
"confirm_app_insufficient_ram", params=values, force=force
)
else:
raise YunohostValidationError(err, **values)
# Display pre-upgrade notifications and ask for simple confirm
if (
manifest["notifications"]["PRE_UPGRADE"]
and Moulinette.interface.type == "cli"
):
settings = _get_app_settings(app_instance_name)
notifications = _filter_and_hydrate_notifications(
manifest["notifications"]["PRE_UPGRADE"],
current_version=app_current_version_raw,
data=settings,
)
_display_notifications(notifications, force=force)
if manifest["packaging_format"] >= 2:
if no_safety_backup:
# FIXME: i18n
logger.warning(
"Skipping the creation of a backup prior to the upgrade."
)
else:
# FIXME: i18n
logger.info("Creating a safety backup prior to the upgrade")
# Switch between pre-upgrade1 or pre-upgrade2
safety_backup_name = f"{app_instance_name}-pre-upgrade1"
other_safety_backup_name = f"{app_instance_name}-pre-upgrade2"
if safety_backup_name in backup_list()["archives"]:
safety_backup_name = f"{app_instance_name}-pre-upgrade2"
other_safety_backup_name = f"{app_instance_name}-pre-upgrade1"
tweaked_backup_core_only = False
if "BACKUP_CORE_ONLY" not in os.environ:
tweaked_backup_core_only = True
os.environ["BACKUP_CORE_ONLY"] = "1"
try:
backup_create(
name=safety_backup_name, apps=[app_instance_name], system=None
)
finally:
if tweaked_backup_core_only:
del os.environ["BACKUP_CORE_ONLY"]
if safety_backup_name in backup_list()["archives"]:
# if the backup suceeded, delete old safety backup to save space
if other_safety_backup_name in backup_list()["archives"]:
backup_delete(other_safety_backup_name)
else:
# Is this needed ? Shouldn't backup_create report an expcetion if backup failed ?
raise YunohostError(
"Uhoh the safety backup failed ?! Aborting the upgrade process.",
raw_msg=True,
)
_assert_system_is_sane_for_app(manifest, "pre")
# We'll check that the app didn't brutally edit some system configuration
manually_modified_files_before_install = manually_modified_files()
app_setting_path = os.path.join(APPS_SETTING_PATH, app_instance_name)
# Attempt to patch legacy helpers ...
_patch_legacy_helpers(extracted_app_folder)
# Prepare env. var. to pass to script
env_dict = _make_environment_for_app_script(
app_instance_name, workdir=extracted_app_folder, action="upgrade"
)
env_dict_more = {
"YNH_APP_UPGRADE_TYPE": upgrade_type,
"YNH_APP_MANIFEST_VERSION": str(app_new_version_raw),
"YNH_APP_CURRENT_VERSION": str(app_current_version_raw),
}
if manifest["packaging_format"] < 2:
env_dict_more["NO_BACKUP_UPGRADE"] = "1" if no_safety_backup else "0"
env_dict.update(env_dict_more)
# Start register change on system
related_to = [("app", app_instance_name)]
operation_logger = OperationLogger("app_upgrade", related_to, env=env_dict)
operation_logger.start()
if manifest["packaging_format"] >= 2:
from yunohost.utils.resources import AppResourceManager
AppResourceManager(
app_instance_name,
wanted=manifest,
current=app_dict["manifest"],
workdir=extracted_app_folder,
).apply(
rollback_and_raise_exception_if_failure=True,
operation_logger=operation_logger,
action="upgrade",
)
# Boring stuff : the resource upgrade may have added/remove/updated setting
# so we need to reflect this in the env_dict used to call the actual upgrade script x_x
# Or: the old manifest may be in v1 and the new in v2, so force to add the setting in env
env_dict = _make_environment_for_app_script(
app_instance_name,
workdir=extracted_app_folder,
action="upgrade",
force_include_app_settings=True,
)
env_dict.update(env_dict_more)
# Execute the app upgrade script
upgrade_failed = True
try:
(
upgrade_failed,
failure_message_with_debug_instructions,
) = hook_exec_with_script_debug_if_failure(
extracted_app_folder + "/scripts/upgrade",
env=env_dict,
operation_logger=operation_logger,
error_message_if_script_failed=m18n.n("app_upgrade_script_failed"),
error_message_if_failed=lambda e: m18n.n(
"app_upgrade_failed", app=app_instance_name, error=e
),
)
finally:
# If upgrade failed, try to restore the safety backup
if (
upgrade_failed
and manifest["packaging_format"] >= 2
and not no_safety_backup
):
logger.warning(
"Upgrade failed ... attempting to restore the safety backup (Yunohost first need to remove the app for this) ..."
)
app_remove(app_instance_name, force_workdir=extracted_app_folder)
backup_restore(
name=safety_backup_name, apps=[app_instance_name], force=True
)
if not _is_installed(app_instance_name):
logger.error(
"Uhoh ... Yunohost failed to restore the app to the way it was before the failed upgrade :|"
)
# Whatever happened (install success or failure) we check if it broke the system
# and warn the user about it
try:
broke_the_system = False
_assert_system_is_sane_for_app(manifest, "post")
except Exception as e:
broke_the_system = True
logger.error(
m18n.n("app_upgrade_failed", app=app_instance_name, error=str(e))
)
failure_message_with_debug_instructions = operation_logger.error(str(e))
# We'll check that the app didn't brutally edit some system configuration
manually_modified_files_after_install = manually_modified_files()
manually_modified_files_by_app = set(
manually_modified_files_after_install
) - set(manually_modified_files_before_install)
if manually_modified_files_by_app:
logger.error(
"Packagers /!\\ This app manually modified some system configuration files! This should not happen! If you need to do so, you should implement a proper conf_regen hook. Those configuration were affected:\n - "
+ "\n -".join(manually_modified_files_by_app)
)
# If the upgrade didnt fail, update the revision and app files (even if it broke the system, otherwise we end up in a funky intermediate state where the app files don't match the installed version or settings, for example for v1->v2 upgrade marked as "broke the system" for some reason)
if not upgrade_failed:
now = int(time.time())
app_setting(app_instance_name, "update_time", now)
app_setting(
app_instance_name,
"current_revision",
manifest.get("remote", {}).get("revision", "?"),
)
# Clean hooks and add new ones
hook_remove(app_instance_name)
if "hooks" in os.listdir(extracted_app_folder):
for hook in os.listdir(extracted_app_folder + "/hooks"):
hook_add(
app_instance_name, extracted_app_folder + "/hooks/" + hook
)
# Replace scripts and manifest and conf (if exists)
# Move scripts and manifest to the right place
for file_to_copy in APP_FILES_TO_COPY:
rm(f"{app_setting_path}/{file_to_copy}", recursive=True, force=True)
if os.path.exists(os.path.join(extracted_app_folder, file_to_copy)):
cp(
f"{extracted_app_folder}/{file_to_copy}",
f"{app_setting_path}/{file_to_copy}",
recursive=True,
)
# Clean and set permissions
shutil.rmtree(extracted_app_folder)
chmod(app_setting_path, 0o600)
chmod(f"{app_setting_path}/settings.yml", 0o400)
chown(app_setting_path, "root", recursive=True)
# If upgrade failed or broke the system,
# raise an error and interrupt all other pending upgrades
if upgrade_failed or broke_the_system:
if not continue_on_failure or broke_the_system:
# display this if there are remaining apps
if apps[number + 1 :]:
not_upgraded_apps = apps[number:]
if broke_the_system and not continue_on_failure:
logger.error(
m18n.n(
"app_not_upgraded_broken_system",
failed_app=app_instance_name,
apps=", ".join(not_upgraded_apps),
)
)
elif broke_the_system and continue_on_failure:
logger.error(
m18n.n(
"app_not_upgraded_broken_system_continue",
failed_app=app_instance_name,
apps=", ".join(not_upgraded_apps),
)
)
else:
logger.error(
m18n.n(
"app_not_upgraded",
failed_app=app_instance_name,
apps=", ".join(not_upgraded_apps),
)
)
raise YunohostError(
failure_message_with_debug_instructions, raw_msg=True
)
else:
operation_logger.close()
logger.error(
m18n.n(
"app_failed_to_upgrade_but_continue",
failed_app=app_instance_name,
operation_logger_name=operation_logger.name,
)
)
failed_to_upgrade_apps.append(
(app_instance_name, operation_logger.name)
)
# Otherwise we're good and keep going !
# So much win
logger.success(m18n.n("app_upgraded", app=app_instance_name))
# Format post-upgrade notifications
if manifest["notifications"]["POST_UPGRADE"]:
# Get updated settings to hydrate notifications
settings = _get_app_settings(app_instance_name)
notifications = _filter_and_hydrate_notifications(
manifest["notifications"]["POST_UPGRADE"],
current_version=app_current_version_raw,
data=settings,
)
if Moulinette.interface.type == "cli":
# ask for simple confirm
_display_notifications(notifications, force=force)
# Reset the dismiss flag for post upgrade notification
app_setting(
app_instance_name, "_dismiss_notification_post_upgrade", delete=True
)
hook_callback("post_app_upgrade", env=env_dict)
operation_logger.success()
permission_sync_to_user()
logger.success(m18n.n("upgrade_complete"))
if failed_to_upgrade_apps:
apps = ""
for app_id, operation_logger_name in failed_to_upgrade_apps:
apps += m18n.n(
"apps_failed_to_upgrade_line",
app_id=app_id,
operation_logger_name=operation_logger_name,
)
logger.warning(m18n.n("apps_failed_to_upgrade", apps=apps))
if Moulinette.interface.type == "api":
return {"notifications": {"POST_UPGRADE": notifications}}
def app_manifest(app, with_screenshot=False):
from yunohost.utils.form import parse_raw_options
manifest, extracted_app_folder = _extract_app(app)
manifest["install"] = parse_raw_options(manifest.get("install", {}), serialize=True)
# Add a base64 image to be displayed in web-admin
if with_screenshot and Moulinette.interface.type == "api":
import base64
manifest["screenshot"] = None
screenshots_folder = os.path.join(extracted_app_folder, "doc", "screenshots")
if os.path.exists(screenshots_folder):
with os.scandir(screenshots_folder) as it:
for entry in it:
ext = os.path.splitext(entry.name)[1].replace(".", "").lower()
if entry.is_file() and ext in ("png", "jpg", "jpeg", "webp", "gif"):
with open(entry.path, "rb") as img_file:
data = base64.b64encode(img_file.read()).decode("utf-8")
manifest["screenshot"] = (
f"data:image/{ext};charset=utf-8;base64,{data}"
)
break
shutil.rmtree(extracted_app_folder)
manifest["requirements"] = {}
for name, passed, values, err in _check_manifest_requirements(
manifest, action="install"
):
if Moulinette.interface.type == "api":
manifest["requirements"][name] = {
"pass": passed,
"values": values,
}
else:
manifest["requirements"][name] = "ok" if passed else m18n.n(err, **values)