001/*
002 * (C) Copyright 2017 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.commons.logging.Log;
024import org.apache.commons.logging.LogFactory;
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 Log log = LogFactory.getLog(ReloadHelper.class);
054
055    public static void hotReloadPackage(String packageId) {
056        log.info("Reload Studio package with id=" + packageId);
057        try {
058            ReloadService reloadService = Framework.getService(ReloadService.class);
059            ReloadContext reloadContext = new ReloadContext();
060
061            PackageManager pm = Framework.getService(PackageManager.class);
062
063            PackageUpdateService pus = Framework.getService(PackageUpdateService.class);
064            LocalPackage pkg = pus.getPackage(packageId);
065
066            // Remove package from PackageUpdateService and get its bundleName to hot reload it
067            if (pkg != null) {
068                // get the bundle symbolic names to hot reload
069                UninstallTask uninstallTask = (UninstallTask) pkg.getUninstallTask();
070                // in our hot reload case, we just care about the bundle
071                // so get the rollback commands and then the target
072                uninstallTask.getCommands()
073                             .stream()
074                             .filter(Rollback.class::isInstance)
075                             .map(Rollback.class::cast)
076                             .map(Rollback::getRollbackOptions)
077                             .map(uninstallTask.getUpdateManager()::getRollbackTarget)
078                             .map(reloadService::getOSGIBundleName)
079                             .forEachOrdered(reloadContext::undeploy);
080                // remove the package from package update service, unless download will fail
081                pus.removePackage(pkg.getId());
082            }
083
084            // Download
085            DownloadingPackage downloadingPkg = pm.download(packageId);
086            while (!downloadingPkg.isCompleted()) {
087                if (log.isTraceEnabled()) {
088                    log.trace("Downloading studio snapshot package: " + packageId);
089                }
090                Thread.sleep(100);
091            }
092
093            log.info("Installing " + packageId);
094            pkg = pus.getPackage(packageId);
095            if (pkg == null || PackageState.DOWNLOADED != pkg.getPackageState()) {
096                throw new NuxeoException("Error while downloading studio snapshot " + pkg);
097            }
098
099            // get bundles to deploy
100            InstallTask installTask = (InstallTask) pkg.getInstallTask();
101            pus.setPackageState(pkg, PackageState.INSTALLING);
102            // in our hot reload case, we just care about the bundle
103            // so get the rollback commands and then the target
104            installTask.getCommands()
105                       .stream()
106                       .filter(Update.class::isInstance)
107                       .map(Update.class::cast)
108                       .map(Update::getFile)
109                       .forEachOrdered(reloadContext::deploy);
110
111            // Reload
112            ReloadResult result = reloadService.reloadBundles(reloadContext);
113
114            // set package as started
115            pus.setPackageState(pkg, PackageState.STARTED);
116            // we need to write uninstall.xml otherwise next hot reload will fail :/
117            // as we don't use the install task, commandLogs is empty
118            // fill it with deployed bundles
119            String id = pkg.getId();
120            Version version = pkg.getVersion();
121            result.deployedFilesAsStream()
122                  // first convert it to UpdateOptions
123                  .map(f -> UpdateOptions.newInstance(id, f, f.getParentFile()))
124                  // then get key
125                  .map(installTask.getUpdateManager()::getKey)
126                  // then build the Rollback command to append to commandLogs
127                  .map(key -> new RollbackOptions(id, key, version.toString()))
128                  .map(Rollback::new)
129                  .forEachOrdered(installTask.getCommandLog()::add);
130            // write the log
131            File file = pkg.getData().getEntry(LocalPackage.UNINSTALL);
132            installTask.writeLog(file);
133        } catch (BundleException | PackageException | ConnectServerError e) {
134            throw new NuxeoException("Error while updating studio snapshot", e);
135        } catch (InterruptedException e) {
136            Thread.currentThread().interrupt();
137            throw new NuxeoException("Error while downloading studio snapshot", e);
138        }
139    }
140
141}