Действия по миграции Moodle вручнуюMoodle manual migration steps
В этой статье описаны действия по переносу локального архива Moodle в Azure.This article describes the steps to migrate the on-premises Moodle archive to Azure. Содержимое этого архива Moodle включает в себя приложение Moodle, соответствующую конфигурацию и копию базы данных из локального развертывания Moodle.The contents of this Moodle archive include the Moodle application, relevant configuration, and a copy of the database from the on-premises Moodle deployment. После успешного импорта локальной резервной копии в инфраструктуру Azure вы выполните обновления конфигурации для Moodle.Once you successfully import the on-premises backup into the Azure infrastructure, you carry out configuration updates for Moodle.
Перед началом этого процесса обязательно выполните все действия, описанные в следующих статьях:Before you begin this process, make sure to complete all the steps in these articles:
- Подготовка к Moodle миграцииHow to prepare for a Moodle migration
- Архитектура и шаблоны миграции MoodleMoodle migration architecture and templates
После завершения развертывания шаблона Azure Resource Manager (ARM) Войдите в портал Azure и перейдите к группе ресурсов, созданной в рамках процесса развертывания.After the Azure Resource Manager (ARM) template deployment finishes, sign in to the Azure portal and go to the resource group you created as part of the deployment process. Ознакомьтесь со списком недавно созданных ресурсов инфраструктуры.Review the list of newly created infrastructure resources. Созданные ресурсы будут выглядеть примерно так, как показано на следующем рисунке, в зависимости от шаблона ARM, который использовался для развертывания.The created resources look similar to the following image, depending on the ARM template you used for deployment.
Копирование архива MoodleCopy the Moodle archive
Первым шагом процесса миграции является копирование архива резервного копирования Moodle из хранилища BLOB-объектов Azure на виртуальную машину контроллера (ВМ) для развертывания Moodle.The first step in the migration process is to copy the Moodle backup archive from Azure Blob Storage to the controller virtual machine (VM) for the Moodle deployment. Это тот же архив, который вы создали при создании архива.This is the same archive you created in Create an archive.
Вход в виртуальную машину контроллераSign in to the controller virtual machine
Используйте бесплатный, эмулятор терминала с открытым исходным кодом или средство последовательной консоли , например, для входа в виртуальную машину контроллера.Use a free, open-source terminal emulator or serial console tool like PuTTY to sign in to a controller VM.
В поле Конфигурация выводимых данных введите общедоступный IP-адрес виртуальной машины контроллера в качестве имени узла.In PuTTY Configuration, enter the public IP address of the controller VM as the Host Name.
В области навигации слева разверните узел SSH.In the left navigation, expand SSH.
Выберите Проверка подлинности и найдите файл ключа SSH, который использовался для развертывания инфраструктуры Azure с помощью шаблона ARM.Select Auth, and find the SSH key file you used to deploy the Azure infrastructure with the ARM template.
Выберите Open (Открыть).Select Open. В поле имя пользователя введите azureadmin, так как оно жестко запрограммировано в шаблоне.For user name, enter azureadmin, as it's hard-coded in the template.
Дополнительные сведения о выводимых данных см. в разделе Общие вопросы и ответы об устранении неполадок.For more information about PuTTY, see PuTTY general FAQ/troubleshooting questions.
Скачайте и установите AzCopy на виртуальной машине контроллера.Download and install AzCopy on the controller VM
После входа в виртуальную машину контроллера выполните следующие команды, чтобы установить AzCopy:After you sign in to the controller VM, run the following commands to install AzCopy:
sudo -s
wget https://aka.ms/downloadazcopy-v10-linux
tar -xvf downloadazcopy-v10-linux
sudo rm /usr/bin/azcopy
sudo cp ./azcopy_linux_amd64_*/azcopy /usr/bin/
Создание резервной копии текущей конфигурацииBack up the current configuration
Прежде чем начать процесс импорта, рекомендуется создать резервную копию конфигурации по умолчанию или текущей.Before you start the import process, it's recommended to back up the default or current configuration.
Создайте каталог резервного копирования:Create a backup directory:
cd /home/azureadmin/ mkdir -p backup mkdir -p backup/moodle mkdir -p backup/moodle/html
Создайте резервные копии
moodle
moodledata
каталогов и.Create backups of themoodle
andmoodledata
directories:mv /moodle/html/moodle /home/azureadmin/backup/moodle/html/moodle mv /moodle/moodledata /home/azureadmin/backup/moodle/moodledata
Копирование архива Moodle на виртуальную машину контроллераCopy the Moodle archive to the controller VM
Выполните следующие команды, чтобы скачать сжатый
storage.tar.gz
файл резервной копии из хранилища BLOB-объектов Azure в каталог виртуальных машин контроллера/home/azureadmin/
:Run the following commands to download the compressedstorage.tar.gz
backup file from Azure Blob Storage to the controller VM/home/azureadmin/
directory:sudo -s cd /home/azureadmin/ azcopy copy "https://<storageaccount>.blob.core.windows.net/<container>/<BlobDirectoryName><SAStoken>" "/home/azureadmin/storage.tar.gz"
Замените учетную запись хранения и значения токенов SAS.Substitute your own storage account and SAS token values. Пример:For example:
azcopy copy "https://onpremisesstorage.blob.core.windows.net/migration/storage.tar.gz?sv=2019-12-12&ss=" "/home/azureadmin/storage.tar.gz"
Извлеките сжатый файл в каталог.Extract the compressed file to a directory.
cd /home/azureadmin tar -zxvf storage.tar.gz
Импорт файлов Moodle в AzureImport Moodle files to Azure
После извлечения каталог можно найти storage
в разделе home/azureadmin
.Once extracted, you can find the storage
directory under home/azureadmin
. Этот storage
Каталог содержит moodle
moodledata
каталоги,, и configuration
и файл резервной копии базы данных.This storage
directory contains moodle
, moodledata
, and configuration
directories, and a database backup file. Каждый из этих файлов и каталогов копируется в целевые расположения в следующих шагах:You copy each of these files and directories to the target locations in the following steps:
Скопируйте
moodle
каталоги иmoodledata
в общее расположение в разделе/moodle
.Copy themoodle
andmoodledata
directories to a shared location under/moodle
.cp -rf /home/azureadmin/storage/moodle /moodle/html/ cp -rf /home/azureadmin/storage/moodledata /moodle/moodledata
Импорт базы данных Moodle в AzureImport the Moodle database to Azure
Подключитесь к базе данных Azure для сервера MySQL и импортируйте Архив локальной базы данных Moodle в базу данных Azure для MySQL.Connect to the Azure Database for MySQL server, and import the on-premises Moodle database archive to Azure Database for MySQL.
Подключение к серверу MySQLConnect to the MySQL server
Экземпляры базы данных Azure для MySQL защищены брандмауэром.Azure Database for MySQL instances are protected by a firewall. По умолчанию все соединения с сервером и базами данных, расположенными на сервере, отклоняются.All connections to the server and the databases inside the server are rejected by default. Прежде чем подключиться к базе данных Azure для MySQL в первый раз, настройте брандмауэр для разрешения доступа к общедоступному IP-адресу или диапазону IP-адресов виртуальной машины контроллера.Before connecting to Azure Database for MySQL for the first time, configure the firewall to allow access for the controller VM's public IP address or IP address range.
Брандмауэр можно настроить с помощью командной строки Azure (Azure CLI) или портал Azure.You can configure the firewall by using the Azure command line (Azure CLI) or the Azure portal.
Выполните следующую команду Azure CLI, заменив собственные значения заполнителей:Run the following Azure CLI command, substituting your own values for the placeholders:
az mysql server firewall-rule create --resource-group <myresourcegroup> --server <mydemoserver> --name <AllowMyIP> --start-ip-address <192.168.0.1> --end-ip-address <192.168.0.1>
На портал Azure выберите сервер базы данных Azure для MySQL из развернутых ресурсов инфраструктуры Moodle.Or, in the Azure portal, select the Azure Database for MySQL server from your deployed Moodle infrastructure resources. На левой панели навигации на странице сервера выберите Безопасность подключения.In the server page's left navigation, select Connection security.
Вы можете добавить разрешенные IP-адреса и настроить правила брандмауэра.You can add allowed IP addresses and configure firewall rules here. После создания правил нажмите кнопку сохранить .Select Save after you've created the rules.
Теперь вы можете подключиться к серверу MySQL с помощью mysql
программы командной строки или MySQL Workbench.You can now connect to the MySQL server by using the mysql
command-line tool or MySQL Workbench.
Чтобы получить сведения о подключении, перейдите на страницу обзора сервера MySQL в портал Azure.To get connection information, go to your MySQL server's Overview page in the Azure portal. Используйте значки копирования рядом с каждым полем, чтобы скопировать имя сервера и имя входа администратора сервера.Use the copy icons next to each field to copy the Server name and Server admin login name.
Например, имя сервера может быть mydemoserver.mysql.database.azure.com
, а имя входа администратора сервера — myadmin@mydemoserver
.For example, your server name might be mydemoserver.mysql.database.azure.com
, and the server admin login name might be myadmin@mydemoserver
.
Вам также потребуется пароль.You also need the password. Если необходимо сбросить пароль, в строке меню выберите Сброс пароля .If you need to reset the password, select Reset password in the menu bar.
Используйте сведения о сервере базы данных в следующих разделах.Use these database server details in the following sections.
Импорт базы данных Moodle в базу данных Azure для MySQLImport the Moodle database to Azure Database for MySQL
Создайте базу данных MySQL для импорта локальной базы данных в:Create a MySQL database to import the on-premises database into:
mysql -h $server_name -u $server_admin_login_name -p$admin_password -e "CREATE DATABASE $moodledbname CHARACTER SET utf8;"
Назначьте правильные разрешения для базы данных:Assign the correct permissions to the database:
mysql -h $server_name -u $server_admin_login_name -p$admin_password -e "GRANT ALL ON $moodledbname.* TO '$server_admin_login_name' IDENTIFIED BY '$admin_password';"
Импортируйте базу данных:Import the database:
mysql -h $server_name -u $server_admin_login_name -p$admin_password $moodledbname < /home/azureadmin/storage/database.sql
Обновить конфигурацииUpdate configurations
После импорта архива локальной базы данных Moodle в базу данных Azure для MySQL при необходимости обновите следующие конфигурации на виртуальной машине контроллера:After importing the on-premises Moodle database archive to Azure Database for MySQL, update the following configurations on the controller VM as necessary:
- Обновите файл конфигурации Moodle.Update the Moodle config file.
- Настройте разрешения для каталога.Configure directory permissions.
- Настройка веб-серверов PHP и NGINX.Configure PHP and NGINX web servers.
- Обновите DNS-имя и другие переменные.Update the DNS name and other variables.
- Установите все отсутствующие расширения PHP.Install any missing PHP extensions.
- Убедитесь, что экземпляры веб-сервера на виртуальной машине контроллера остановлены.Ensure the web server instances on the controller VM are stopped.
- Скопируйте файлы конфигурации в общую папку для копирования в масштабируемые наборы виртуальных машин.Copy the config files to a shared location for copying to virtual machine scale sets.
Обновление файла конфигурации MoodleUpdate the Moodle config file
Обновите параметры сведений о базе данных в файле конфигурации Moodle /moodle/config.php
.Update the database detail parameters in the Moodle configuration file /moodle/config.php
.
Чтобы получить DNS-имя для этой задачи, сделайте следующее:To get the DNS name for this task:
В портал Azure выберите Load Balancer общедоступный IP-адрес из развернутых ресурсов инфраструктуры Moodle.In the Azure portal, select the Load Balancer public IP address from your deployed Moodle infrastructure resources.
На странице Обзор щелкните значок копирования рядом с DNS-именем.On the Overview page, select the copy icon next to the DNS name.
Чтобы обновить config.php
файл, выполните следующие действия.To update the config.php
file:
Введите следующие команды для редактирования
config.php
вnano
редакторе:Enter the following commands to editconfig.php
in thenano
editor:cd /moodle/html/moodle/ nano config.php
Обновите сведения о базе данных в файле, используя значения, скопированные из портал Azure:Update the database details in the file, using the values you copied from the Azure portal:
$CFG->dbhost = 'localhost'; // Change 'localhost' to the server name. $CFG->dbname = 'moodle'; // Change 'moodle' to the newly created database name. $CFG->dbuser = 'root'; // Change 'root' to the server admin login name. $CFG->dbpass = 'password'; // Change 'password' to the server admin login password. $CFG->wwwroot = 'https://on-premises.com'; // Change 'on-premises' to the DNS name. $CFG->dataroot = '/var/moodledata'; // Change the path to '/moodle/moodledata'.
После внесения изменений нажмите клавиши CTRL + O, чтобы сохранить файл, и CTRL + X, чтобы выйти из редактора.After making the changes, press Ctrl+O to save the file and Ctrl+X to exit the editor.
Локальный каталог можно сохранить dataroot
в любом расположении.You can store the on-premises dataroot
directory at any location.
Настройка разрешений для каталогаConfigure directory permissions
Назначьте в каталог разрешения 755 и www-data owner: Group
moodle
.Assign 755 and www-data owner:group permissions to themoodle
directory.sudo chmod 755 /moodle/html/moodle sudo chown -R www-data:www-data /moodle/html/moodle
Назначьте в каталог разрешения 770 и www-data owner: Group
moodledata
.Assign 770 and www-data owner:group permissions to themoodledata
directory.sudo chmod 770 /moodle/moodledata sudo chown -R www-data:www-data /moodle/moodledata
Обновление файлов веб-конфигурацииUpdate web config files
Создайте резервную копию и обновите conf
файл nginx:Back up and update the NGINX conf
file:
sudo mv /etc/nginx/sites-enabled/*.conf /home/azureadmin/backup/
cd /home/azureadmin/storage/configuration/
sudo cp -rf nginx/sites-enabled/*.conf /etc/nginx/sites-enabled/
Создайте резервную копию и обновите www.conf
файл PHP:Back up and update the PHP www.conf
file:
_PHPVER='/usr/bin/php -r "echo PHP_VERSION;" | /usr/bin/cut -c 1,2,3'
echo $_PHPVER
sudo mv /etc/php/$_PHPVER/fpm/pool.d/www.conf /home/azureadmin/backup/www.conf
sudo cp -rf /home/azureadmin/storage/configuration/php/$_PHPVER/fpm/pool.d/www.conf /etc/php/$_PHPVER/fpm/pool.d/
Обновление переменных конфигурации NGINXUpdate the NGINX configuration variables
Обновите DNS-имя облака Azure, чтобы оно было DNS-именем локального приложения Moodle.Update the Azure cloud DNS name to the on-premises Moodle application's DNS name.
Откройте файл конфигурации NGINX:Open the NGINX configuration file:
nano /etc/nginx/sites-enabled/*.conf
При развертывании шаблона ARM для сервера NGINX устанавливается порт 81.The ARM template deployment sets the NGINX server to port 81. Обновите
SERVER_PORT
файл в файле до 81, если он не равен 81.Update theSERVER_PORT
in the file to 81 if it's not 81.Обновите
server_name
.Update theserver_name
. Например, дляserver_name on-premises.com
обновитеon-premises.com
с помощью DNS-имени.For example, for aserver_name on-premises.com
, updateon-premises.com
with the DNS name. В большинстве случаев DNS-имя не изменяется при миграции.In most cases, the DNS name doesn't change in the migration.Обновите
root
расположение каталога HTML.Update the HTMLroot
directory location. Например, изменитеroot /var/www/html/moodle;
наroot /moodle/html/moodle;
.For example, updateroot /var/www/html/moodle;
toroot /moodle/html/moodle;
.Локальный корневой каталог может находиться в любом расположении.The on-premises root directory can be at any location.
После внесения изменений нажмите клавиши CTRL + O, чтобы сохранить файл и CTRL + X для выхода.After making the changes, press Ctrl+O to save the file and Ctrl+X to exit.
Установка отсутствующих расширений PHPInstall any missing PHP extensions
Шаблоны развертывания ARM устанавливают следующие расширения PHP:The ARM deployment templates install the following PHP extensions:
fpm
cli
curl
zip
pear
mbstring
dev
mcrypt
soap
json
redis
bcmath
gd
mysql
xmlrpc
intl
xml
bz2
Если локальное приложение Moodle имеет какие-либо расширения PHP, которые отсутствуют на виртуальной машине контроллера, их можно установить вручную.If the on-premises Moodle application has any PHP extensions that aren't on the controller VM, you can install them manually.
Чтобы получить список расширений PHP в локальном приложении, выполните:To get the list of PHP extensions in the on-premises application, run:
php -m
Чтобы установить недостающие расширения, выполните команду:To install missing extensions, run:
sudo apt-get install -y php-<extension>
Убедитесь, что экземпляры веб-сервера на виртуальной машине контроллера остановленыEnsure the web server instances on the controller VM are stopped
Перезапустите веб-серверы.Restart the web servers.
sudo systemctl restart nginx sudo systemctl restart php$_PHPVER-fpm
Останавливает веб-серверы.Stop the web servers.
sudo systemctl stop nginx sudo systemctl stop php$_PHPVER-fpm
Когда запрос достигает Azure Load Balancer, он перенаправляется к экземплярам масштабируемого набора виртуальных машин, а не к виртуальной машине контроллера.When a request reaches Azure Load Balancer, it now redirects to virtual machine scale set instances and not to the controller VM.
Копировать файлы конфигурацииCopy configuration files
Скопируйте файлы конфигурации PHP и веб-сервера в общее расположение для последующего копирования в экземпляры масштабируемых наборов виртуальных машин.Copy PHP and web server configuration files to a shared location for later copying to virtual machine scale set instances.
Чтобы создать каталог для файлов конфигурации в общем расположении, выполните:To create the directory for configuration files in a shared location, run:
mkdir -p /moodle/config
mkdir -p /moodle/config/php
mkdir -p /moodle/config/nginx
Чтобы скопировать файлы конфигурации PHP и веб-сервера в общий каталог, выполните команду:To copy the PHP and web server configuration files to the shared directory, run:
cp /etc/nginx/sites-enabled/* /moodle/config/nginx
cp /etc/php/$_PHPVER/fpm/pool.d/www.conf /moodle/config/php
Дальнейшие действияNext steps
Продолжайте настраивать экземпляр контроллера Moodle и рабочие узлы для следующих шагов в процессе миграции Moodle.Continue to Set up the Moodle controller instance and worker nodes for the next steps in the Moodle migration process.