001/*
002 * (C) Copyright 2017-2018 Nuxeo (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *    http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Kevin Leturc <kleturc@nuxeo.com>
018 */
019package org.nuxeo.ecm.admin.runtime;
020
021import java.io.File;
022
023import org.apache.logging.log4j.LogManager;
024import org.apache.logging.log4j.Logger;
025import org.nuxeo.connect.connector.ConnectServerError;
026import org.nuxeo.connect.data.DownloadingPackage;
027import org.nuxeo.connect.packages.PackageManager;
028import org.nuxeo.connect.update.LocalPackage;
029import org.nuxeo.connect.update.PackageException;
030import org.nuxeo.connect.update.PackageState;
031import org.nuxeo.connect.update.PackageUpdateService;
032import org.nuxeo.connect.update.Version;
033import org.nuxeo.connect.update.task.standalone.InstallTask;
034import org.nuxeo.connect.update.task.standalone.UninstallTask;
035import org.nuxeo.connect.update.task.update.Rollback;
036import org.nuxeo.connect.update.task.update.RollbackOptions;
037import org.nuxeo.connect.update.task.update.Update;
038import org.nuxeo.connect.update.task.update.UpdateOptions;
039import org.nuxeo.ecm.core.api.NuxeoException;
040import org.nuxeo.runtime.api.Framework;
041import org.nuxeo.runtime.reload.ReloadContext;
042import org.nuxeo.runtime.reload.ReloadResult;
043import org.nuxeo.runtime.reload.ReloadService;
044import org.osgi.framework.BundleException;
045
046/**
047 * Helper to hot reload studio bundles.
048 *
049 * @since 9.3
050 */
051public class ReloadHelper {
052
053    private static final Logger log = LogManager.getLogger(ReloadHelper.class);
054
055    public static synchronized void hotReloadPackage(String packageId) {
056        log.info("Reload Studio package with id={}", packageId);
057        LocalPackage pkg = null;
058        InstallTask installTask = null;
059        try {
060            ReloadService reloadService = Framework.getService(ReloadService.class);
061            ReloadContext reloadContext = new ReloadContext();
062
063            PackageManager pm = Framework.getService(PackageManager.class);
064
065            PackageUpdateService pus = Framework.getService(PackageUpdateService.class);
066            pkg = pus.getPackage(packageId);
067
068            // Remove package from PackageUpdateService and get its bundleName to hot reload it
069            if (pkg != null) {
070                if (pkg.getPackageState().isInstalled()) {
071                    if (pkg.getUninstallFile().exists()) {
072                        // get the bundle symbolic names to hot reload
073                        UninstallTask uninstallTask = (UninstallTask) pkg.getUninstallTask();
074                        // in our hot reload case, we just care about the bundle
075                        // so get the rollback commands and then the target
076                        uninstallTask.getCommands()
077                                     .stream()
078                                     .filter(Rollback.class::isInstance)
079                                     .map(Rollback.class::cast)
080                                     .map(Rollback::getRollbackOptions)
081                                     .map(uninstallTask.getUpdateManager()::getRollbackTarget)
082                                     .map(reloadService::getOSGIBundleName)
083                                     .forEachOrdered(reloadContext::undeploy);
084                    } else {
085                        log.warn("Unable to uninstall previous bundle because {} doesn't exist",
086                                 pkg.getUninstallFile());
087                    }
088                }
089                // remove the package from package update service, unless download will fail
090                pus.removePackage(pkg.getId());
091            }
092
093            // Download
094            DownloadingPackage downloadingPkg = pm.download(packageId);
095            while (!downloadingPkg.isCompleted()) {
096                log.trace("Downloading studio snapshot package: {}", packageId);
097                Thread.sleep(100); // NOSONAR (we want the whole hot-reload to be synchronized)
098            }
099
100            log.info("Installing {}", packageId);
101            pkg = pus.getPackage(packageId);
102            if (pkg == null || PackageState.DOWNLOADED != pkg.getPackageState()) {
103                throw new NuxeoException("Error while downloading studio snapshot " + pkg);
104            }
105
106            // get bundles to deploy
107            installTask = (InstallTask) pkg.getInstallTask();
108            pus.setPackageState(pkg, PackageState.INSTALLING);
109
110            // in our hot reload case, we just care about the bundle
111            // so get the update commands and then the file
112            installTask.getCommands()
113                       .stream()
114                       .filter(Update.class::isInstance)
115                       .map(Update.class::cast)
116                       .map(Update::getFile)
117                       .forEachOrdered(reloadContext::deploy);
118
119            // Reload
120            ReloadResult result = reloadService.reloadBundles(reloadContext);
121
122            // set package as started
123            pus.setPackageState(pkg, PackageState.STARTED);
124            // we need to write uninstall.xml otherwise next hot reload will fail :/
125            // as we don't use the install task, commandLogs is empty
126            // fill it with deployed bundles
127            String id = pkg.getId();
128            Version version = pkg.getVersion();
129            result.deployedFilesAsStream()
130                  // first convert it to UpdateOptions
131                  .map(f -> UpdateOptions.newInstance(id, f, f.getParentFile()))
132                  // then get key
133                  .map(installTask.getUpdateManager()::getKey)
134                  // then build the Rollback command to append to commandLogs
135                  .map(key -> new RollbackOptions(id, key, version.toString()))
136                  .map(Rollback::new)
137                  .forEachOrdered(installTask.getCommandLog()::add);
138        } catch (BundleException | PackageException | ConnectServerError e) {
139            throw new NuxeoException("Error while updating studio snapshot", e);
140        } catch (InterruptedException e) {
141            Thread.currentThread().interrupt();
142            throw new NuxeoException("Error while downloading studio snapshot", e);
143        } finally {
144            if (pkg != null && installTask != null) {
145                // write the log
146                File file = pkg.getData().getEntry(LocalPackage.UNINSTALL);
147                try {
148                    installTask.writeLog(file);
149                } catch (PackageException e) {
150                    // don't rethrow inside finally
151                    log.error("Exception when writing uninstall.xml", e);
152                }
153            }
154        }
155    }
156
157}