diff --git a/.buckconfig b/.buckconfig new file mode 100644 index 0000000..cd59b4c --- /dev/null +++ b/.buckconfig @@ -0,0 +1,11 @@ +# Documentation: https://buckbuild.com/concept/buckconfig.html + +[parser] + python_interpreter = /usr/bin/python2 + +[python#py3] + interpreter = /usr/bin/python3 + +[repositories] + ubuntu20to22 = . + dist-upgrader = ./dist-upgrader diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..a2f8fc8 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,16 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**Feedback archive** +*Please attach a feedback archive to the bug report.* +You could create it by calling `ubuntu20to22 --prepare-feedback`. +The archive will help us investigate the problem better and faster. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..11fc491 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..39d7b97 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,34 @@ +name: Build with Buck + +on: [push] + +jobs: + build: + # Not latest, because python3.6 is not available on latest + # (https://github.com/actions/setup-python/issues/544), + # and SandakovMM/build-with-buck@v2 action requires it + runs-on: ubuntu-20.04 + steps: + - name: Checkout repository and submodules + uses: actions/checkout@v4 + with: + submodules: recursive + # We use tags to determine version, so fetch them + fetch-depth: 0 + fetch-tags: true + # Workaround for https://github.com/actions/checkout/issues/882 + - name: Explicitly fetch tags + run: git fetch --force --tags + - name: Prepare artifact store + run: mkdir -p ./buck-out/gen + - name: Build ubuntu20to22 + id: build + uses: SandakovMM/build-with-buck@v3 + with: + command: build + target: :ubuntu20to22 + - name: Store result + uses: actions/upload-artifact@v3 + with: + name: ubuntu20to22 + path: ./buck-out/gen/ubuntu20to22 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..722d5e7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.vscode diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..7946a51 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "dist-upgrader"] + path = dist-upgrader + url = https://github.com/plesk/dist-upgrader.git diff --git a/BUCK b/BUCK new file mode 100644 index 0000000..9f6d0cf --- /dev/null +++ b/BUCK @@ -0,0 +1,26 @@ +# Copyright 2024. Plesk International GmbH. All rights reserved. +# vim:ft=python: + +include_defs('//product.defs.py') + + +python_binary( + name = 'ubuntu20to22.pex', + platform = 'py3', + # libgcc_s.so.1 is preloaded to workaround crash due to "libgcc_s.so.1 must + # be installed for pthread_cancel to work" instead of clean exit after + # dist-upgrade, see https://bugs.python.org/issue44434 + build_args = ['--python-shebang', '/usr/bin/env -S LD_PRELOAD=libgcc_s.so.1 python3'], + main_module = 'ubuntu20to22.main', + deps = [ + 'dist-upgrader//pleskdistup:lib', + '//ubuntu20to22:lib', + ], +) + +genrule( + name = 'ubuntu20to22', + srcs = [':ubuntu20to22.pex'], + out = 'ubuntu20to22', + cmd = 'cp $(location :ubuntu20to22.pex) $OUT && chmod +x $OUT', +) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e7f3409 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2020 Plesk International GmbH + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 0000000..9d27537 --- /dev/null +++ b/README.md @@ -0,0 +1,124 @@ +# The tool to dist-upgrade servers with Plesk from Ubuntu 20 to 22 + +## Introduction +This utility is the official tool to dist-upgrade servers with Plesk from Ubuntu 20 to 22. + +The utility uses [Plesk dist-upgrader](https://github.com/plesk/dist-upgrader). + +## Preparation +To avoid downtime and data loss, make sure you have read and understood the following information before using the utility: +1. **Upgrade Plesk to the last version.** +2. **Create a full server backup.** Before the upgrade, make a full server backup (which includes a full backup of all the databases). +3. Notify the customers about upcoming downtime. Expected downtime is 20-30 minutes. +4. **Remote management module must be installed on the server**. +5. We strongly recommend that you **create a snapshot you can use as a recovery point** in case the conversion process fails. +6. Read the [Known issues](#known-issues) section below for the list of known issues. + +## Timing +The conversion process should run between 20 and 30 minutes. **Plesk services, hosted websites, and e-mails will be unavailable during the entirety of the conversion process**. + +## Known issues +### Blockers +Do not use the utility if any of the following is true: +- **Your system is in a container (like Virtuozzo containers, Docker Containers, etc).** + +## Requirements +- Last Plesk version. +- At least 5 GB of free disk space. +- At least 2 GB of RAM. + +## Conversion phases +The conversion process consists of two phases: +1. The "convert" phase contains preparation and upgrading actions. +2. The "finish" phase is the last phase containing all finishing actions. + +During each phase a conversion plan consisting of stages, which in turn consist of actions, is executed. You can see the general stages in the `--help` output and the detailed plan in the `--show-plan` output. + +## Using the utility +To retrieve the latest available version of the tool, please navigate to the "Releases" section. Once there, locate the most recent version of the tool and download the attached archive. + +To prepare the latest version of the tool for use, please run the following commands: +```shell +> unzip ubuntu20to22.zip +> chmod 755 ubuntu20to22 +``` + +To monitor the conversion process, we recommend using the ['screen' utility](https://www.gnu.org/software/screen/) to run the utility in the background. To do so, run the following command: +```shell +> screen -S ubuntu20to22 +> ./ubuntu20to22 +``` +If you lose your SSH connection to the server, you can reconnect to the screen session by running the following command: +```shell +> screen -r ubuntu20to22 +``` + +You can also call ubuntu20to22 in the background: +```shell +> ./ubuntu20to22 & +``` + +And monitor its status with the '--status' or '--monitor' flags: +```shell +> ./ubuntu20to22 --status +> ./ubuntu20to22 --monitor +... live monitor session ... +``` + +The conversion process requires 2 reboots. It will be resumed automatically after reboot by the `plesk-dist-upgrader` systemd service. In addition to `--status` and `--monitor`, you can check the status of the conversion process by running the following command: +```shell +> systemctl status plesk-dist-upgrader +``` + +Running dist-upgrader without any arguments initiates the conversion process. The utility performs preliminary checks, and if any issues are detected, it provides descriptions of the problems along with guidance on how to resolve them. +Following the preliminary checks, the tool proceeds with the dist-upgrade process, which is divided into multiple stages. Some stages end with a reboot. You can check the list of stages and steps by `./ubuntu20to22 --show-plan`. +When dist-upgrade is finished, you will see the following login message: +``` +=============================================================================== +Message from the Plesk dist-upgrader tool: +The server has been upgraded to Ubuntu 22. +You can remove this message from the /etc/motd file. +=============================================================================== +``` + +## Logs +If something goes wrong, read the logs to identify the problem. +The dist-upgrader writes its log to the `/var/log/plesk/ubuntu20to22.log` file, as well as to stdout. +After the first reboot, the process is resumed by the `plesk-dist-upgrader` service, so its output is available in system logs (see `systemctl status plesk-dist-upgrader` and `journalctl -u plesk-dist-upgrader`). + +## Revert +If the utility fails during the the "convert" stage before actual dist-upgrade of packages, you can use the dist-upgrader utility with the `-r` or `--revert` options to restore Plesk to normal operation. The dist-upgrader will undo some of the changes it made and restart Plesk services. Once you have resolved the root cause of the failure, you can attempt the conversion again. +Note: +- You cannot use revert to undo the changes after the dist-upgrade of packages, because packages provided by the new OS version are already installed. +- `--revert` mode is not perfect, it can fail or be unable to restore the initial state of the system. So, the importance of creating full server backup or snapshot before starting dist-upgrade can't be stressed enough. + +### Checking the status of the conversion process and monitoring its progress +To check the status of the conversion process, use the `--status` option. You can see the current stage of the conversion process, the elapsed time, and the estimated time until finish. +```shell +> ./ubuntu20to22 --status +``` + +To monitor the progress of the conversion process in real time, use the `--monitor` option. +```shell +> ./ubuntu20to22 --monitor +( stage 3 / action re-installing plesk components ) 02:26 / 06:18 +``` + +## Issue handling +If for some reason the process has failed, inspect the log. By default, it's put to `/var/log/plesk/ubuntu20to22.log`. If the process was interrupted before the first reboot, you can restart it with the `--resume` option. If the problem has happened after the first reboot, you can restart the process by running `systemctl restart plesk-dist-upgrader`. + +If something goes wrong, you will be informed on the next login with this message: +``` +=============================================================================== +Message from Plesk dist-upgrader tool: +Something went wrong during dist-upgrade by ubuntu20to22. +See the /var/log/plesk/ubuntu20to22.log file for more information. +You can remove this message from the /etc/motd file. +=============================================================================== +``` + +### Send feedback +If you got any error, please [create an issue on GitHub](https://github.com/plesk/ubuntu20to22/issues). Describe your problem and attach the feedback archive or at least the log to the issue. The feedback archive can be created by calling the tool with the `--prepare-feedback` option: +```shell +> ./ubuntu20to22 --prepare-feedback +``` diff --git a/buck.defs.py b/buck.defs.py new file mode 100644 index 0000000..fa17cf9 --- /dev/null +++ b/buck.defs.py @@ -0,0 +1,33 @@ +# Copyright 2024. Plesk International GmbH. All rights reserved. +# vim:ft=python: + +import os.path + +with allow_unsafe_import(): + import subprocess + + +def get_full_base_path(): + path = get_base_path() + cell = get_cell_name() + if cell: + path = os.path.join(cell, path) + return path + + +def get_git_revision(path=None): + if not path: + path = get_full_base_path() + return subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=path, universal_newlines=True).strip() + + +def get_git_revision_description(dirty=True, path=None): + cmd = ['git', 'describe', '--match', 'v[0-9]*'] + if dirty is True: + cmd.append('--dirty') + if not path: + path = get_full_base_path() + try: + return subprocess.check_output(cmd, cwd=path, universal_newlines=True).strip() + except Exception: + return get_git_revision(path=path) diff --git a/dist-upgrader b/dist-upgrader new file mode 160000 index 0000000..79bac2c --- /dev/null +++ b/dist-upgrader @@ -0,0 +1 @@ +Subproject commit 79bac2c0fd2ea694b5148411e0b98f48eb093b3b diff --git a/product.defs.py b/product.defs.py new file mode 100644 index 0000000..3440aab --- /dev/null +++ b/product.defs.py @@ -0,0 +1,17 @@ +# Copyright 2024. Plesk International GmbH. All rights reserved. +# vim:ft=python: + +include_defs('//buck.defs.py') + + +# Function is necessary, because Buck won't allow +# get_git_revision_description() to be called at the top level of an +# included file due to get_base_path() call inside (so, you can't just +# do REVISION = get_git_revision_description()) +def get_product_revision(): + return get_git_revision_description() + + +def get_product_version(): + rev = get_product_revision() + return rev.lstrip('v').split('-', 1)[0] if '-' in rev else '' diff --git a/ubuntu20to22/BUCK b/ubuntu20to22/BUCK new file mode 100644 index 0000000..76d244e --- /dev/null +++ b/ubuntu20to22/BUCK @@ -0,0 +1,28 @@ +# Copyright 2024. Plesk International GmbH. All rights reserved. +# vim:ft=python: + +include_defs('//product.defs.py') + + +genrule( + name = 'config', + srcs = ['config.py'], + out = 'config.py', + bash = '''\ + PRODUCT_VERSION='{version}' + PRODUCT_REVISION='{revision}' + sed -e "s/@@PRODUCT_VERSION@@/$PRODUCT_VERSION/g; s/@@PRODUCT_REVISION@@/$PRODUCT_REVISION/g" "$SRCS" >"$OUT" + '''.format( + version=get_product_version(), + revision=get_product_revision(), + ), +) + +python_library( + name = 'lib', + srcs = glob( + ['**/*.py'], + exclude = ['config.py'], + ) + [':config'], + visibility = ['PUBLIC'], +) diff --git a/ubuntu20to22/__init__.py b/ubuntu20to22/__init__.py new file mode 100644 index 0000000..f76e1c0 --- /dev/null +++ b/ubuntu20to22/__init__.py @@ -0,0 +1 @@ +# Copyright 2024. Plesk International GmbH. All rights reserved. diff --git a/ubuntu20to22/config.py b/ubuntu20to22/config.py new file mode 100644 index 0000000..d44ea6c --- /dev/null +++ b/ubuntu20to22/config.py @@ -0,0 +1,4 @@ +# Copyright 2024. Plesk International GmbH. All rights reserved. + +version = "@@PRODUCT_VERSION@@" +revision = "@@PRODUCT_REVISION@@" diff --git a/ubuntu20to22/main.py b/ubuntu20to22/main.py new file mode 100644 index 0000000..08c3098 --- /dev/null +++ b/ubuntu20to22/main.py @@ -0,0 +1,13 @@ +#!/usr/bin/python3 +# Copyright 2024. Plesk International GmbH. All rights reserved. + +import sys + +import pleskdistup.main +import pleskdistup.registry + +import ubuntu20to22.upgrader + +if __name__ == "__main__": + pleskdistup.registry.register_upgrader(ubuntu20to22.upgrader.Ubuntu20to22Factory()) + sys.exit(pleskdistup.main.main()) diff --git a/ubuntu20to22/upgrader.py b/ubuntu20to22/upgrader.py new file mode 100644 index 0000000..c917be2 --- /dev/null +++ b/ubuntu20to22/upgrader.py @@ -0,0 +1,233 @@ +# Copyright 2024. Plesk International GmbH. All rights reserved. + +import argparse +import os +import typing + +from pleskdistup import actions +from pleskdistup.common import action, feedback +from pleskdistup.phase import Phase +from pleskdistup.upgrader import DistUpgrader, DistUpgraderFactory, PathType, SystemDescription + +import ubuntu20to22.config + + +class Ubuntu20to22Upgrader(DistUpgrader): + _os_from_name = "Ubuntu" + _os_from_version = "20" + _os_to_name = "Ubuntu" + _os_to_version = "22" + + def __init__(self): + super().__init__() + + def __repr__(self) -> str: + attrs = ", ".join(f"{k}={getattr(self, k)!r}" for k in ( + "_os_from_name", "_os_from_version", + "_os_to_name", "_os_to_version", + )) + return f"{self.__class__.__name__}({attrs})" + + def __str__(self) -> str: + return f"{self.__class__.__name__}" + + @classmethod + def supports( + cls, + from_system: typing.Optional[SystemDescription] = None, + to_system: typing.Optional[SystemDescription] = None + ) -> bool: + def matching_system( + system: SystemDescription, + os_name: str, + os_version: str, + ) -> bool: + return ( + (system.os_name is None or system.os_name == os_name) + and (system.os_version is None or system.os_version == os_version) + ) + + return ( + (from_system is None or matching_system(from_system, cls._os_from_name, cls._os_from_version)) + and (to_system is None or matching_system(to_system, cls._os_to_name, cls._os_to_version)) + ) + + @property + def upgrader_name(self) -> str: + return "Plesk::Ubuntu20to22Upgrader" + + @property + def upgrader_version(self) -> str: + return ubuntu20to22.config.revision + + @property + def issues_url(self) -> str: + return "https://github.com/plesk/ubuntu20to22/issues" + + def prepare_feedback( + self, + feed: feedback.Feedback, + ) -> feedback.Feedback: + feed.collect_actions += [ + feedback.collect_installed_packages_apt, + feedback.collect_installed_packages_dpkg, + feedback.collect_apt_policy, + feedback.collect_plesk_version, + ] + return feed + + def construct_actions( + self, + upgrader_bin_path: PathType, + options: typing.Any, + phase: Phase + ) -> typing.Dict[str, typing.List[action.ActiveAction]]: + new_os = f"{self._os_to_name} {self._os_to_version}" + return { + "Prepare": [ + actions.HandleConversionStatus( + options.status_flag_path, + options.completion_flag_path, + ), + actions.AddFinishSshLoginMessage(new_os), # Executed at the finish phase only + actions.AddInProgressSshLoginMessage(new_os), + actions.DisablePleskSshBanner(), + actions.RepairPleskInstallation(), # Executed at the finish phase only + actions.UpgradePackages(), + actions.UpdatePlesk(), + actions.AddUpgradeSystemdService( + os.path.abspath(upgrader_bin_path), + options, + ), + actions.ConfigureMariadb({ + "mysqld.bind-address": { + "prepare": actions.ConfigValueReplacer( + new_value="127.0.0.1", + old_value="::ffff:127.0.0.1", + ), + "revert": actions.ConfigValueReplacer( + new_value="::ffff:127.0.0.1", + old_value="127.0.0.1", + ), + }, + "mysqld.innodb_fast_shutdown": { + "prepare": actions.ConfigValueReplacer( + new_value="0", + old_value=None, + ), + "revert": actions.ConfigValueReplacer( + new_value=None, + old_value="0", + ), + }, + }), + actions.EnableEnhancedSecurityMode(), + ], + "Switch repositories": [ + actions.SetupUbuntuRepositories("focal", "jammy"), + actions.SwitchPleskRepositories(to_os_version="22.04"), + ], + "Dist-upgrade": [ + actions.DoDistupgrade(), + ], + "Update Plesk": [ + actions.UpdatePlesk(update_cmd_args=["--skip-cleanup"]), + ], + "Update Plesk extensions": [ + actions.UpdatePleskExtensions([ + "panel-migrator", "site-import", "docker", "grafana", + "ruby", + ]), + ], + "Finishing actions": [ + actions.Reboot( + prepare_next_phase=Phase.FINISH, + name="reboot and perform finishing actions", + ), + actions.Reboot( + prepare_reboot=None, + post_reboot=action.RebootType.AFTER_LAST_STAGE, + name="final reboot", + ), + ], + } + + def get_check_actions( + self, + options: typing.Any, + phase: Phase, + ) -> typing.List[action.CheckAction]: + if phase is Phase.FINISH: + return [] + + return [ + actions.AssertMinPleskVersion("18.0.44"), + actions.AssertPleskInstallerNotInProgress(), + actions.AssertMinPhpVersion("7.4"), + actions.AssertDpkgNotLocked(), + actions.AssertNotInContainer(), + actions.AssertPleskComponents(not_installed=["mailman"]), + actions.AssertMinFreeDiskSpace( + { + # Space requirements in bytes + "/boot": 150 * 1024**2, + "/opt": 150 * 1024**2, + "/usr": 1800 * 1024**2, + "/var": 2000 * 1024**2, + } + ) + ] + + def parse_args(self, args: typing.Sequence[str]) -> None: + DESC_MESSAGE = f"""Use this upgrader to dist-upgrade an {self._os_from_name} {self._os_from_version} server with Plesk to {self._os_to_name} {self._os_to_version}. +The process consists of the following general stages: + +-- Preparation (about 5 minutes) - The OS is prepared for the conversion. +-- Conversion (about 15 minutes) - Plesk and system dist-upgrade is performed. +-- Finalization (about 5 minutes) - The server is returned to normal operation. + +The system will be rebooted after each of the stages, so reboot times +should be added to get the total time estimate. + +To see the detailed plan, run the utility with the --show-plan option. + +For assistance, submit an issue here {self.issues_url} +and attach the feedback archive generated with --prepare-feedback or at least +the log file. +""" + parser = argparse.ArgumentParser( + usage=argparse.SUPPRESS, + description=DESC_MESSAGE, + formatter_class=argparse.RawDescriptionHelpFormatter, + add_help=False, + ) + parser.add_argument( + "-h", "--help", action="help", default=argparse.SUPPRESS, + help=argparse.SUPPRESS, + ) + parser.parse_args(args) + + +class Ubuntu20to22Factory(DistUpgraderFactory): + def __init__(self): + super().__init__() + + def __repr__(self) -> str: + return f"{self.__class__.__name__}(upgrader_name={self.upgrader_name})" + + def __str__(self) -> str: + return f"{self.__class__.__name__} (creates {self.upgrader_name})" + + def supports( + self, + from_system: typing.Optional[SystemDescription] = None, + to_system: typing.Optional[SystemDescription] = None + ) -> bool: + return Ubuntu20to22Upgrader.supports(from_system, to_system) + + @property + def upgrader_name(self) -> str: + return "Plesk::Ubuntu20to22Upgrader" + + def create_upgrader(self, *args, **kwargs) -> DistUpgrader: + return Ubuntu20to22Upgrader(*args, **kwargs)