Search in sources :

Example 76 with Check

use of io.fabric8.karaf.checks.Check in project fabric8 by jboss-fuse.

the class ServiceImplTest method testCheckPrerequisitesNotInstalled.

@Test
public void testCheckPrerequisitesNotInstalled() throws IOException {
    ServiceImpl service = createMockServiceImpl(getDirectoryForResource("prereq/patch2.patch"));
    Patch patch = service.getPatch("patch2");
    assertNotNull(patch);
    try {
        service.checkPrerequisites(patch);
        fail("Patch will prerequisites that are not yet installed should not pass check");
    } catch (PatchException e) {
        assertTrue(e.getMessage().toLowerCase().contains("required patch 'prereq2' is not installed"));
    }
}
Also used : GitPatchManagementServiceImpl(io.fabric8.patch.management.impl.GitPatchManagementServiceImpl) PatchException(io.fabric8.patch.management.PatchException) Patch(io.fabric8.patch.management.Patch) Test(org.junit.Test)

Example 77 with Check

use of io.fabric8.karaf.checks.Check in project fabric8 by jboss-fuse.

the class ServiceImplTest method testCheckPrerequisitesMissing.

@Test
public void testCheckPrerequisitesMissing() throws IOException {
    ServiceImpl service = createMockServiceImpl(getDirectoryForResource("prereq/patch1.patch"));
    Patch patch = service.getPatch("patch1");
    assertNotNull(patch);
    try {
        service.checkPrerequisites(patch);
        fail("Patch will missing prerequisites should not pass check");
    } catch (PatchException e) {
        assertTrue(e.getMessage().toLowerCase().contains("required patch 'prereq1' is missing"));
    }
}
Also used : GitPatchManagementServiceImpl(io.fabric8.patch.management.impl.GitPatchManagementServiceImpl) PatchException(io.fabric8.patch.management.PatchException) Patch(io.fabric8.patch.management.Patch) Test(org.junit.Test)

Example 78 with Check

use of io.fabric8.karaf.checks.Check in project fabric8 by jboss-fuse.

the class FabricPatchServiceImpl method install.

@Override
public PatchResult install(final Patch patch, boolean simulation, final String versionId, boolean upload, final String username, final String password, final ProfileUpdateStrategy strategy) throws IOException {
    // we start from the same state as in standalone mode - after successful patch:add
    // we have other things to do in fabric env however:
    // 1. check prerequisites
    // 2. we don't care about current state of framework - it'll be managed by fabric-agent and we don't
    // necessary install a patch for this container we're in
    // 3. we don't do patchManagement.beginInstallation / patchManagement.commitInstallation here
    // this will be done later - after updated fabric-agent is started
    // 4. we don't have to analyze bundles/features/repositories updates - these will be handled simply by
    // updating profiles in specified version
    PatchKind kind = patch.getPatchData().isRollupPatch() ? PatchKind.ROLLUP : PatchKind.NON_ROLLUP;
    if (kind == PatchKind.NON_ROLLUP) {
        throw new UnsupportedOperationException("patch:fabric-install should be used for Rollup patches only");
    }
    String currentContainersVersionId = fabricService.getCurrentContainer().getVersionId();
    if (!simulation && versionId.equals(currentContainersVersionId)) {
        throw new UnsupportedOperationException("Can't install Rollup patch in current version. Please install" + " this patch in new version and then upgrade existing container(s)");
    }
    fabricService.adapt(ProfileService.class).getRequiredVersion(versionId);
    // just a list of new bundle locations - in fabric the updatable version depends on the moment we
    // apply the new version to existing containers.
    List<BundleUpdate> bundleUpdatesInThisPatch = bundleUpdatesInPatch(patch);
    Presentation.displayBundleUpdates(bundleUpdatesInThisPatch, true);
    PatchResult result = new PatchResult(patch.getPatchData(), simulation, System.currentTimeMillis(), bundleUpdatesInThisPatch, null);
    if (!simulation) {
        // update profile definitions stored in Git. We don't update ${karaf.home}/fabric, becuase it is used
        // only once - when importing profiles during fabric:create.
        // when fabric is already available, we have to update (Git) repository information
        GitOperation operation = new GitOperation() {

            @Override
            public Object call(Git git, GitContext context) throws Exception {
                // we can't pass git reference to patch-management
                // because patch-management private-packages git library
                // but we can leverage the write lock we have
                GitHelpers.checkoutBranch(git, versionId);
                // let's get back in history to the point before user changes (profile-edits), but not earlier
                // than last R patch
                String patchBranch = patchManagement.findLatestPatchRevision(git.getRepository().getDirectory(), versionId);
                // now install profiles from patch just like there were no user changes
                patchManagement.installProfiles(git.getRepository().getDirectory(), versionId, patch, strategy);
                // and finally we have to merge user and patch changes to profiles.
                patchManagement.mergeProfileChanges(patch, git.getRepository().getDirectory(), versionId, patchBranch);
                context.commitMessage("Installing rollup patch \"" + patch.getPatchData().getId() + "\"");
                return null;
            }
        };
        gitDataStore.gitOperation(new GitContext().requireCommit().setRequirePush(true), operation, null);
        if (upload) {
            PatchManagement.UploadCallback callback = new PatchManagement.UploadCallback() {

                @Override
                public void doWithUrlConnection(URLConnection connection) throws ProtocolException {
                    if (connection instanceof HttpURLConnection) {
                        ((HttpURLConnection) connection).setRequestMethod("PUT");
                    }
                    if (username != null && password != null) {
                        connection.setRequestProperty("Authorization", "Basic " + Base64Encoder.encode(username + ":" + password));
                    }
                }
            };
            patchManagement.uploadPatchArtifacts(patch.getPatchData(), fabricService.getMavenRepoUploadURI(), callback);
        }
    }
    return result;
}
Also used : PatchKind(io.fabric8.patch.management.PatchKind) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) ProfileService(io.fabric8.api.ProfileService) GitOperation(io.fabric8.git.internal.GitOperation) Git(org.eclipse.jgit.api.Git) HttpURLConnection(java.net.HttpURLConnection) GitContext(io.fabric8.api.GitContext) PatchManagement(io.fabric8.patch.management.PatchManagement) PatchResult(io.fabric8.patch.management.PatchResult) BundleUpdate(io.fabric8.patch.management.BundleUpdate)

Example 79 with Check

use of io.fabric8.karaf.checks.Check in project fabric8 by jboss-fuse.

the class Activator method start.

@Override
@SuppressWarnings("unchecked")
public void start(final BundleContext context) throws Exception {
    bundle = context.getBundle();
    systemContext = context.getBundle(0).getBundleContext();
    logServiceTracker = new ServiceTracker(context, "org.osgi.service.log.LogService", null);
    logServiceTracker.open();
    patchManagementService = new GitPatchManagementServiceImpl(context);
    final int targetStartLevel = Integer.parseInt(System.getProperty("org.osgi.framework.startlevel.beginning"));
    sl = context.getBundle(0).adapt(FrameworkStartLevel.class);
    activatedAt = sl.getStartLevel();
    if (!patchManagementService.isEnabled()) {
        log(LogService.LOG_INFO, "\nPatch management is disabled");
        return;
    }
    switch(activatedAt) {
        case PATCH_MANAGEMENT_START_LEVEL:
            // this bundle is configured in etc/startup.properties, we can handle registered tasks
            // like updating critical bundles
            startupVersion = context.getBundle().getVersion();
            // we're started before fileinstall, so we can remove this bundle if it is available in deploy/
            patchManagementService.cleanupDeployDir();
            break;
        default:
            // this bundle was activated from deploy/ directory or osgi:install. But this doesn't mean there's no
            // patch-management bundle configured in etc/startup.properties
            // the point is that when etc/startup.properties already has this bundle, there should be no such bundle in deploy/
            // TODO (there may be newer version however)
            deployVersion = context.getBundle().getVersion();
            break;
    }
    patchManagementService.start();
    patchManagementRegistration = systemContext.registerService(PatchManagement.class, PatchManagement.class.cast(patchManagementService), null);
    backupServiceRegistration = systemContext.registerService(BackupService.class, new FileBackupService(systemContext), null);
    if (startupVersion != null) {
        // we should be at start level 2. let's check if there are any rollup paatches being installed or
        // rolled back - we've got some work to do at this early stage of Karaf
        patchManagementService.checkPendingPatches();
    }
    if (sl.getStartLevel() == targetStartLevel) {
        // dropped to deploy/ when framework was already at target start-level
        patchManagementService.ensurePatchManagementInitialized();
    } else {
        // let's wait for last start level
        startLevelNotificationFrameworkListener = new StartLevelNotificationFrameworkListener(targetStartLevel);
        systemContext.addFrameworkListener(startLevelNotificationFrameworkListener);
    }
}
Also used : BackupService(io.fabric8.patch.management.BackupService) ServiceTracker(org.osgi.util.tracker.ServiceTracker) PatchManagement(io.fabric8.patch.management.PatchManagement) FrameworkStartLevel(org.osgi.framework.startlevel.FrameworkStartLevel)

Example 80 with Check

use of io.fabric8.karaf.checks.Check in project fabric8 by jboss-fuse.

the class FabricServiceImpl method substituteConfigurations.

/**
 * Performs substitution to configuration based on the registered {@link PlaceholderResolver} instances.
 */
public Map<String, Map<String, String>> substituteConfigurations(final Map<String, Map<String, String>> configurations) {
    final Map<String, PlaceholderResolver> resolversSnapshot = new HashMap<String, PlaceholderResolver>(placeholderResolvers);
    // Check that all resolvers are available
    Set<String> requiredSchemes = getSchemesForProfileConfigurations(configurations);
    Set<String> availableSchemes = resolversSnapshot.keySet();
    if (!availableSchemes.containsAll(requiredSchemes)) {
        StringBuilder sb = new StringBuilder();
        sb.append("Missing Placeholder Resolvers:");
        for (String scheme : requiredSchemes) {
            if (!availableSchemes.contains(scheme)) {
                sb.append(" ").append(scheme);
            }
        }
        throw new FabricException(sb.toString());
    }
    final Map<String, Map<String, String>> mutableConfigurations = new HashMap<>();
    for (Entry<String, Map<String, String>> entry : configurations.entrySet()) {
        String key = entry.getKey();
        Map<String, String> value = new HashMap<>(entry.getValue());
        mutableConfigurations.put(key, value);
    }
    final FabricService fabricService = this;
    for (Map.Entry<String, Map<String, String>> entry : mutableConfigurations.entrySet()) {
        final String pid = entry.getKey();
        Map<String, String> props = entry.getValue();
        Map<String, String> original = new HashMap<>(props);
        for (Map.Entry<String, String> e : original.entrySet()) {
            final String key = e.getKey();
            final String value = e.getValue();
            try {
                props.put(key, InterpolationHelper.substVars(value, key, null, props, new InterpolationHelper.SubstitutionCallback() {

                    public String getValue(String toSubstitute) {
                        if (toSubstitute != null && toSubstitute.contains(":")) {
                            String scheme = toSubstitute.substring(0, toSubstitute.indexOf(":"));
                            return resolversSnapshot.get(scheme).resolve(fabricService, mutableConfigurations, pid, key, toSubstitute);
                        }
                        return substituteBundleProperty(toSubstitute, bundleContext);
                    }
                }));
            } catch (EncryptionOperationNotPossibleException exception) {
                LOGGER.warn("Error resolving " + key, exception);
            }
        }
    }
    return mutableConfigurations;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) FabricException(io.fabric8.api.FabricException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) FabricService(io.fabric8.api.FabricService) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) PlaceholderResolver(io.fabric8.api.PlaceholderResolver)

Aggregations

Test (org.junit.Test)35 IOException (java.io.IOException)23 File (java.io.File)17 ArrayList (java.util.ArrayList)17 HashMap (java.util.HashMap)15 FabricService (io.fabric8.api.FabricService)11 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)11 Map (java.util.Map)10 Container (io.fabric8.api.Container)9 PatchException (io.fabric8.patch.management.PatchException)9 Expectations (mockit.Expectations)9 Profile (io.fabric8.api.Profile)8 TreeMap (java.util.TreeMap)7 Version (io.fabric8.api.Version)6 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)6 AuthConfig (io.fabric8.maven.docker.access.AuthConfig)6 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)6 Check (io.fabric8.karaf.checks.Check)5 KubernetesListBuilder (io.fabric8.kubernetes.api.model.KubernetesListBuilder)5 Patch (io.fabric8.patch.management.Patch)5