Search in sources :

Example 1 with Task

use of io.fabric8.maven.docker.util.Task in project docker-maven-plugin by fabric8io.

the class WatchService method defaultContainerRestartTask.

private Task<ImageWatcher> defaultContainerRestartTask() {
    return new Task<ImageWatcher>() {

        @Override
        public void execute(ImageWatcher watcher) throws Exception {
            // Stop old one
            ImageConfiguration imageConfig = watcher.getImageConfiguration();
            PortMapping mappedPorts = runService.createPortMapping(imageConfig.getRunConfiguration(), watcher.getWatchContext().getMojoParameters().getProject().getProperties());
            String id = watcher.getContainerId();
            String optionalPreStop = getPreStopCommand(imageConfig);
            if (optionalPreStop != null) {
                runService.execInContainer(id, optionalPreStop, watcher.getImageConfiguration());
            }
            runService.stopPreviouslyStartedContainer(id, false, false);
            // Start new one
            watcher.setContainerId(runService.createAndStartContainer(imageConfig, mappedPorts, watcher.getWatchContext().getPomLabel(), watcher.getWatchContext().getMojoParameters().getProject().getProperties(), watcher.getWatchContext().getMojoParameters().getProject().getBasedir()));
        }
    };
}
Also used : Task(io.fabric8.maven.docker.util.Task) ImageConfiguration(io.fabric8.maven.docker.config.ImageConfiguration) WatchImageConfiguration(io.fabric8.maven.docker.config.WatchImageConfiguration) PortMapping(io.fabric8.maven.docker.access.PortMapping)

Example 2 with Task

use of io.fabric8.maven.docker.util.Task in project fabric8 by jboss-fuse.

the class DummyBatchingProgressMonitor method deactivateInternal.

private void deactivateInternal() {
    // Remove the GitListener
    gitService.get().removeGitListener(gitListener);
    // Shutdown the thread pool
    threadPool.shutdown();
    threadPoolInitial.shutdown();
    try {
        for (ScheduledExecutorService ses : new ScheduledExecutorService[] { threadPool, threadPoolInitial }) {
            try {
                // Give some time to the running task to complete.
                if (!ses.awaitTermination(5, TimeUnit.SECONDS)) {
                    ses.shutdownNow();
                }
            } catch (InterruptedException ex) {
                ses.shutdownNow();
                // Preserve interrupt status.
                Thread.currentThread().interrupt();
            }
        }
    } catch (Exception ex) {
        throw FabricException.launderThrowable(ex);
    } finally {
        LOGGER.debug("Restoring ProxySelector to original: {}", defaultProxySelector);
        ProxySelector.setDefault(defaultProxySelector);
        // Closing the shared counter
        try {
            if (counter != null) {
                counter.close();
            }
        } catch (IOException ex) {
            LOGGER.warn("Error closing SharedCount due " + ex.getMessage() + ". This exception is ignored.");
        }
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) IOException(java.io.IOException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) FabricException(io.fabric8.api.FabricException) KeeperException(org.apache.zookeeper.KeeperException) MalformedURLException(java.net.MalformedURLException)

Example 3 with Task

use of io.fabric8.maven.docker.util.Task in project fabric8 by jboss-fuse.

the class ServerInvokerImpl method onCommand.

protected void onCommand(final Transport transport, Object data) {
    try {
        final DataByteArrayInputStream bais = new DataByteArrayInputStream((Buffer) data);
        final int size = bais.readInt();
        final long correlation = bais.readVarLong();
        // Use UTF8Buffer instead of string to avoid encoding/decoding UTF-8 strings
        // for every request.
        final UTF8Buffer service = readBuffer(bais).utf8();
        final Buffer encoded_method = readBuffer(bais);
        final ServiceFactoryHolder holder = holders.get(service);
        final MethodData methodData = holder.getMethodData(encoded_method);
        final Object svc = holder.factory.get();
        Runnable task = new Runnable() {

            public void run() {
                final DataByteArrayOutputStream baos = new DataByteArrayOutputStream();
                try {
                    // make space for the size field.
                    baos.writeInt(0);
                    baos.writeVarLong(correlation);
                } catch (IOException e) {
                    // should not happen
                    throw new RuntimeException(e);
                }
                // Lets decode the remaining args on the target's executor
                // to take cpu load off the
                methodData.invocationStrategy.service(methodData.serializationStrategy, holder.loader, methodData.method, svc, bais, baos, new Runnable() {

                    public void run() {
                        holder.factory.unget();
                        final Buffer command = baos.toBuffer();
                        // Update the size field.
                        BufferEditor editor = command.buffer().bigEndianEditor();
                        editor.writeInt(command.length);
                        queue().execute(new Runnable() {

                            public void run() {
                                transport.offer(command);
                            }
                        });
                    }
                });
            }
        };
        Executor executor;
        if (svc instanceof Dispatched) {
            executor = ((Dispatched) svc).queue();
        } else {
            executor = blockingExecutor;
        }
        executor.execute(task);
    } catch (Exception e) {
        LOGGER.info("Error while reading request", e);
    }
}
Also used : IOException(java.io.IOException) IOException(java.io.IOException) EOFException(java.io.EOFException) Dispatched(io.fabric8.dosgi.api.Dispatched) Executor(java.util.concurrent.Executor)

Example 4 with Task

use of io.fabric8.maven.docker.util.Task in project fabric8 by jboss-fuse.

the class ServiceImpl method install.

/**
 * <p>Main installation method. Installing a patch in non-fabric mode is a matter of correct merge (cherry-pick, merge,
 * rebase) of patch branch into <code>master</code> branch.</p>
 * <p>Static changes are handled by git, runtime changes (bundles, features) are handled depending on patch type:<ul>
 *     <li>Rollup: clear OSGi bundle cache, reinstall features that were installed after restart</li>
 *     <li>Non-Rollup: update bundles, generate overrides.properties and update scripts to reference new versions</li>
 * </ul></p>
 * <p>For Rollup patches we don't update bundles - we clear the bundle cache instead.</p>
 * @param patches
 * @param simulate
 * @param synchronous
 * @return
 */
private Map<String, PatchResult> install(final Collection<Patch> patches, final boolean simulate, boolean synchronous) {
    PatchKind kind = checkConsistency(patches);
    checkPrerequisites(patches);
    checkStandaloneChild(patches);
    // checkFabric();
    String transaction = null;
    try {
        // Compute individual patch results (patchId -> Result)
        final Map<String, PatchResult> results = new LinkedHashMap<String, PatchResult>();
        // current state of the framework
        Bundle[] allBundles = bundleContext.getBundles();
        // bundle -> url to update the bundle from (used for non-rollup patch)
        final Map<Bundle, String> bundleUpdateLocations = new HashMap<>();
        /* A "key" is name + "update'able version". Such version is current version with micro version == 0 */
        // [symbolic name|updateable-version] -> newest update for the bundle out of all installed patches
        final Map<String, BundleUpdate> updatesForBundleKeys = new LinkedHashMap<>();
        // [feature name|updateable-version] -> newest update for the feature out of all installed patches
        final Map<String, FeatureUpdate> updatesForFeatureKeys = new LinkedHashMap<>();
        // symbolic name -> version -> location
        final BundleVersionHistory history = createBundleVersionHistory();
        // beginning installation transaction = creating of temporary branch in git
        transaction = this.patchManagement.beginInstallation(kind);
        // bundles from etc/startup.properties + felix.framework = all bundles not managed by features
        // these bundles will be treated in special way
        // symbolic name -> Bundle
        final Map<String, Bundle> coreBundles = helper.getCoreBundles(allBundles);
        // runtime info is prepared to apply runtime changes and static info is prepared to update KARAF_HOME files
        for (Patch patch : patches) {
            List<FeatureUpdate> featureUpdatesInThisPatch = null;
            if (kind == PatchKind.ROLLUP) {
                // list of feature updates for the current patch
                featureUpdatesInThisPatch = featureUpdatesInPatch(patch, updatesForFeatureKeys, kind);
                helper.sortFeatureUpdates(featureUpdatesInThisPatch);
            }
            // list of bundle updates for the current patch - for ROLLUP patch, we minimize the list of bundles
            // to "restore" (install after clearing data/cache) by not including bundles that are
            // already updated as part of fueatures update
            List<BundleUpdate> bundleUpdatesInThisPatch = bundleUpdatesInPatch(patch, allBundles, bundleUpdateLocations, history, updatesForBundleKeys, kind, coreBundles, featureUpdatesInThisPatch);
            // each patch may change files, we're not updating the main files yet - it'll be done when
            // install transaction is committed
            patchManagement.install(transaction, patch, bundleUpdatesInThisPatch);
            // each patch may ship a migrator
            if (!simulate) {
                installMigratorBundle(patch);
            }
            // prepare patch result before doing runtime changes
            PatchResult result = null;
            if (patch.getResult() != null) {
                result = patch.getResult();
                if (patchManagement.isStandaloneChild()) {
                    // ENTESB-5120: "result" is actually a result of patch installation in root container
                    // we need dedicated result for admin:create based child container
                    PatchResult childResult = new PatchResult(patch.getPatchData(), simulate, System.currentTimeMillis(), bundleUpdatesInThisPatch, featureUpdatesInThisPatch, result);
                    result.addChildResult(System.getProperty("karaf.name"), childResult);
                }
            } else {
                result = new PatchResult(patch.getPatchData(), simulate, System.currentTimeMillis(), bundleUpdatesInThisPatch, featureUpdatesInThisPatch);
            }
            result.getKarafBases().add(String.format("%s | %s", System.getProperty("karaf.name"), System.getProperty("karaf.base")));
            results.put(patch.getPatchData().getId(), result);
        }
        // One special case
        if (kind == PatchKind.NON_ROLLUP) {
            // for rollup patch, this bundle will be installed from scratch
            for (Map.Entry<Bundle, String> entry : bundleUpdateLocations.entrySet()) {
                Bundle bundle = entry.getKey();
                if (bundle.getSymbolicName() != null && "org.ops4j.pax.url.mvn".equals(stripSymbolicName(bundle.getSymbolicName()))) {
                    // handle this bundle specially - update it here
                    URL location = new URL(entry.getValue());
                    System.out.printf("Special update of bundle \"%s\" from \"%s\"%n", bundle.getSymbolicName(), location);
                    if (!simulate) {
                        BundleUtils.update(bundle, location);
                        bundle.start();
                    }
                    // replace location - to be stored in result
                    bundleUpdateLocations.put(bundle, location.toString());
                }
            }
        }
        Presentation.displayFeatureUpdates(updatesForFeatureKeys.values(), true);
        // effectively, we will update all the bundles from this list - even if some bundles will be "updated"
        // as part of feature installation
        Presentation.displayBundleUpdates(updatesForBundleKeys.values(), true);
        // then required repositories, features and bundles will be reinstalled
        if (kind == PatchKind.ROLLUP) {
            if (!simulate) {
                if (patches.size() == 1) {
                    Patch patch = patches.iterator().next();
                    PatchResult result = results.get(patch.getPatchData().getId());
                    patch.setResult(result);
                    // single shot
                    if (patchManagement.isStandaloneChild()) {
                        backupService.backupDataFiles(result.getChildPatches().get(System.getProperty("karaf.name")), Pending.ROLLUP_INSTALLATION);
                    } else {
                        backupService.backupDataFiles(result, Pending.ROLLUP_INSTALLATION);
                    }
                    for (Bundle b : coreBundles.values()) {
                        if (b.getSymbolicName() != null && Utils.stripSymbolicName(b.getSymbolicName()).equals("org.apache.felix.fileinstall")) {
                            b.stop(Bundle.STOP_TRANSIENT);
                            break;
                        }
                    }
                    // update KARAF_HOME
                    patchManagement.commitInstallation(transaction);
                    if (patchManagement.isStandaloneChild()) {
                        result.getChildPatches().get(System.getProperty("karaf.name")).setPending(Pending.ROLLUP_INSTALLATION);
                    } else {
                        result.setPending(Pending.ROLLUP_INSTALLATION);
                    }
                    result.store();
                    // Some updates need a full JVM restart.
                    if (isJvmRestartNeeded(results)) {
                        boolean handlesFullRestart = Boolean.getBoolean("karaf.restart.jvm.supported");
                        if (handlesFullRestart) {
                            System.out.println("Rollup patch " + patch.getPatchData().getId() + " installed. Restarting Karaf..");
                            System.setProperty("karaf.restart.jvm", "true");
                        } else {
                            System.out.println("Rollup patch " + patch.getPatchData().getId() + " installed. Shutting down Karaf, please restart...");
                        }
                    } else {
                        // We don't need a JVM restart, so lets just do a OSGi framework restart
                        System.setProperty("karaf.restart", "true");
                    }
                    File karafData = new File(bundleContext.getProperty("karaf.data"));
                    File cleanCache = new File(karafData, "clean_cache");
                    cleanCache.createNewFile();
                    Thread.currentThread().setContextClassLoader(bundleContext.getBundle(0l).adapt(BundleWiring.class).getClassLoader());
                    bundleContext.getBundle(0l).stop();
                }
            } else {
                System.out.println("Simulation only - no files and runtime data will be modified.");
                patchManagement.rollbackInstallation(transaction);
            }
            return results;
        }
        // update KARAF_HOME
        if (!simulate) {
            patchManagement.commitInstallation(transaction);
        } else {
            patchManagement.rollbackInstallation(transaction);
        }
        if (!simulate) {
            Runnable task = new Runnable() {

                @Override
                public void run() {
                    try {
                        // update bundles
                        applyChanges(bundleUpdateLocations);
                        // persist results of all installed patches
                        for (Patch patch : patches) {
                            PatchResult result = results.get(patch.getPatchData().getId());
                            patch.setResult(result);
                            result.store();
                        }
                    } catch (Exception e) {
                        e.printStackTrace(System.err);
                        System.err.flush();
                    }
                }
            };
            if (synchronous) {
                task.run();
            } else {
                new Thread(task).start();
            }
        } else {
            System.out.println("Simulation only - no files and runtime data will be modified.");
        }
        return results;
    } catch (Exception e) {
        e.printStackTrace(System.err);
        System.err.flush();
        if (transaction != null && patchManagement != null) {
            patchManagement.rollbackInstallation(transaction);
        }
        throw new PatchException(e.getMessage(), e);
    } finally {
        System.out.flush();
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PatchKind(io.fabric8.patch.management.PatchKind) URL(java.net.URL) LinkedHashMap(java.util.LinkedHashMap) BundleUpdate(io.fabric8.patch.management.BundleUpdate) FeatureUpdate(io.fabric8.patch.management.FeatureUpdate) Bundle(org.osgi.framework.Bundle) URISyntaxException(java.net.URISyntaxException) PatchException(io.fabric8.patch.management.PatchException) BundleException(org.osgi.framework.BundleException) IOException(java.io.IOException) PatchResult(io.fabric8.patch.management.PatchResult) PatchException(io.fabric8.patch.management.PatchException) Patch(io.fabric8.patch.management.Patch) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) File(java.io.File)

Example 5 with Task

use of io.fabric8.maven.docker.util.Task in project fabric8 by jboss-fuse.

the class WaitForProvisionTaskTest method testStraightSuccess.

@Test
public void testStraightSuccess() throws Exception {
    Container container = createMock(Container.class);
    expect(container.getId()).andReturn("container").anyTimes();
    expect(container.isAlive()).andReturn(true).anyTimes();
    expect(container.isManaged()).andReturn(true).anyTimes();
    expect(container.getProvisionStatus()).andReturn("success").anyTimes();
    expect(container.getSshUrl()).andReturn("container:8181").anyTimes();
    expect(container.getProvisionException()).andReturn(null).anyTimes();
    replay(container);
    WaitForProvisionTask task = new WaitForProvisionTask(container, "success", 10000L);
    assertTrue(task.call());
    verify(container);
}
Also used : Container(io.fabric8.api.Container) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)6 Container (io.fabric8.api.Container)5 IOException (java.io.IOException)4 FabricException (io.fabric8.api.FabricException)2 ImageConfiguration (io.fabric8.maven.docker.config.ImageConfiguration)2 Task (io.fabric8.maven.docker.util.Task)2 MalformedURLException (java.net.MalformedURLException)2 KeeperException (org.apache.zookeeper.KeeperException)2 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)2 DataStoreTemplate (io.fabric8.api.DataStoreTemplate)1 GitContext (io.fabric8.api.GitContext)1 LockHandle (io.fabric8.api.LockHandle)1 Dispatched (io.fabric8.dosgi.api.Dispatched)1 GitProxyService (io.fabric8.git.GitProxyService)1 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)1 DockerAccessException (io.fabric8.maven.docker.access.DockerAccessException)1 PortMapping (io.fabric8.maven.docker.access.PortMapping)1 WatchImageConfiguration (io.fabric8.maven.docker.config.WatchImageConfiguration)1 BuildService (io.fabric8.maven.docker.service.BuildService)1 ServiceHub (io.fabric8.maven.docker.service.ServiceHub)1