Search in sources :

Example 16 with Agent

use of io.fabric8.agent.service.Agent in project fabric8 by jboss-fuse.

the class ProfileDisplayAction method displayProfile.

private void displayProfile(Profile profile) {
    PrintStream output = System.out;
    output.println("Profile id: " + profile.getId());
    output.println("Version   : " + profile.getVersion());
    output.println("Attributes: ");
    Map<String, String> props = profile.getAttributes();
    for (String key : props.keySet()) {
        output.println("\t" + key + ": " + props.get(key));
    }
    String versionId = profile.getVersion();
    String profileId = profile.getId();
    output.printf("Containers: %s\n", toString(fabricService.getAssociatedContainers(versionId, profileId)));
    ProfileService profileService = fabricService.adapt(ProfileService.class);
    if (overlay) {
        profile = profileService.getOverlayProfile(profile);
    }
    Map<String, Map<String, String>> configuration = new HashMap<>(profile.getConfigurations());
    Map<String, byte[]> resources = profile.getFileConfigurations();
    Map<String, String> agentConfiguration = profile.getConfiguration(Constants.AGENT_PID);
    List<String> agentProperties = new ArrayList<String>();
    List<String> systemProperties = new ArrayList<String>();
    List<String> configProperties = new ArrayList<String>();
    List<String> otherResources = new ArrayList<String>();
    for (Map.Entry<String, String> entry : agentConfiguration.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        if (value.contains(",")) {
            value = "\t" + value.replace(",", ",\n\t\t");
        }
        if (key.startsWith("system.")) {
            systemProperties.add("  " + key.substring("system.".length()) + " = " + value);
        } else if (key.startsWith("config.")) {
            configProperties.add("  " + key.substring("config.".length()) + " = " + value);
        } else if (!key.startsWith("feature.") && !key.startsWith("repository") && !key.startsWith("bundle.") && !key.startsWith("fab.") && !key.startsWith("override.") && !key.startsWith("attribute.")) {
            agentProperties.add("  " + key + " = " + value);
        }
    }
    if (configuration.containsKey(Constants.AGENT_PID)) {
        output.println("\nContainer settings");
        output.println("----------------------------");
        if (profile.getLibraries().size() > 0) {
            printConfigList("Libraries : ", output, profile.getLibraries());
        }
        if (profile.getRepositories().size() > 0) {
            printConfigList("Repositories : ", output, profile.getRepositories());
        }
        if (profile.getFeatures().size() > 0) {
            printConfigList("Features : ", output, profile.getFeatures());
        }
        if (profile.getBundles().size() > 0) {
            printConfigList("Bundles : ", output, profile.getBundles());
        }
        if (profile.getFabs().size() > 0) {
            printConfigList("Fabs : ", output, profile.getFabs());
        }
        if (profile.getOverrides().size() > 0) {
            printConfigList("Overrides : ", output, profile.getOverrides());
        }
        if (agentProperties.size() > 0) {
            printConfigList("Agent Properties : ", output, agentProperties);
        }
        if (systemProperties.size() > 0) {
            printConfigList("System Properties : ", output, systemProperties);
        }
        if (configProperties.size() > 0) {
            printConfigList("Config Properties : ", output, configProperties);
        }
        configuration.remove(Constants.AGENT_PID);
    }
    output.println("\nConfiguration details");
    output.println("----------------------------");
    for (Map.Entry<String, Map<String, String>> cfg : configuration.entrySet()) {
        output.println("PID: " + cfg.getKey());
        for (Map.Entry<String, String> values : cfg.getValue().entrySet()) {
            output.println("  " + values.getKey() + " " + values.getValue());
        }
        output.println("\n");
    }
    output.println("\nOther resources");
    output.println("----------------------------");
    for (Map.Entry<String, byte[]> resource : resources.entrySet()) {
        String name = resource.getKey();
        if (!name.endsWith(".properties")) {
            output.println("Resource: " + resource.getKey());
            if (displayResources) {
                output.println(new String(resource.getValue(), Charsets.UTF_8));
                output.println("\n");
            }
        }
    }
}
Also used : PrintStream(java.io.PrintStream) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ProfileService(io.fabric8.api.ProfileService) HashMap(java.util.HashMap) Map(java.util.Map)

Example 17 with Agent

use of io.fabric8.agent.service.Agent in project fabric8 by jboss-fuse.

the class GitDataStoreImplProfilesIT method readVersionAndRefreshProfile.

@Test
public void readVersionAndRefreshProfile() {
    gdsi.importFromFileSystem("src/test/resources/distros/distro1/fabric/import");
    Version version = profileRegistry.getVersion("1.0");
    assertNotNull(version);
    Profile defaultProfile = version.getProfile("default");
    assertNotNull(defaultProfile);
    assertThat(defaultProfile.getBundles().size(), equalTo(1));
    assertThat(defaultProfile.getBundles().get(0), equalTo("mvn:io.fabric8/fabric-amazing/${version:fabric}"));
    assertThat(defaultProfile.getFeatures().size(), equalTo(1));
    assertThat(defaultProfile.getFeatures().get(0), equalTo("extraordinary"));
    assertThat(defaultProfile.getConfigurations().size(), equalTo(2));
    assertThat(defaultProfile.getConfigurations().get("my.special.pid").get("property2"), equalTo("value2"));
    assertThat(defaultProfile.getConfigurations().get("io.fabric8.agent").get("some.other.property"), equalTo("valueX"));
    assertThat(defaultProfile.getConfigurations().get("io.fabric8.agent").get("io.fabric8.number.of.sources"), equalTo("42,142,200"));
    ProfileBuilder builder = ProfileBuilder.Factory.createFrom(defaultProfile);
    Map<String, String> agentConfiguration = builder.getConfiguration(Constants.AGENT_PID);
    // refresh
    agentConfiguration.put("lastRefresh." + defaultProfile.getId(), String.valueOf(System.currentTimeMillis()));
    agentConfiguration.put("io.fabric8.number.of.sources", "100");
    builder.addConfiguration(Constants.AGENT_PID, agentConfiguration);
    profileRegistry.updateProfile(builder.getProfile());
}
Also used : Version(io.fabric8.api.Version) ProfileBuilder(io.fabric8.api.ProfileBuilder) Profile(io.fabric8.api.Profile) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 18 with Agent

use of io.fabric8.agent.service.Agent in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method alignTo.

@Override
public boolean alignTo(Map<String, String> versions, List<String> urls, File localMavenRepository, Runnable callback) throws PatchException {
    if (aligning.getAndSet(true)) {
        return false;
    }
    try {
        if (!env.isFabric()) {
            try {
                // we probably survived fabric:create without refreshing patch-management bundle
                env = envService.determineEnvironmentType();
                File patchRepositoryLocation = new File(patchesDir, GitPatchRepositoryImpl.MAIN_GIT_REPO_LOCATION);
                getGitPatchRepository().close();
                GitPatchRepositoryImpl repository = new GitPatchRepositoryImpl(env, patchRepositoryLocation, karafHome, karafBase, karafData, patchesDir);
                setGitPatchRepository(repository);
                start();
                // let's tweak the configuration when entering fabric mode
                // this way we will track other kinds of baselines
                ensurePatchManagementInitialized();
                if (master) {
                    // let the caller know that we've configured patch management in "master" container
                    // this is mainly to push the changes from local to cluster git repository
                    // so child/ssh containers created in fabric can fetch correct baselines
                    callback.run();
                }
            } catch (Exception e) {
                throw new PatchException(e.getMessage(), e);
            }
        }
        if (env.isFabric()) {
            Git fork = null;
            try {
                ensuringLock.lock();
                String version = versions.get(env.getProductId());
                String tagName = String.format(env.getBaselineTagFormat(), version);
                // we have to be at that tag
                Git mainRepository = gitPatchRepository.findOrCreateMainGitRepository();
                fetchFabricPatchData(mainRepository);
                fork = gitPatchRepository.cloneRepository(mainRepository, true);
                gitPatchRepository.checkout(fork).setName(gitPatchRepository.getMainBranchName()).call();
                RevTag tag = gitPatchRepository.findCurrentBaseline(fork);
                if (tag != null && tagName.equals(tag.getTagName())) {
                    if (master) {
                        // and then to data/git/servlet
                        try {
                            gitPatchRepository.pushPatchBranches();
                            callback.run();
                        } catch (Exception e) {
                            Activator.log(LogService.LOG_WARNING, null, e.getMessage(), e, false);
                        } catch (Error e) {
                            // in case newer patch management calls agent which is still wired to old patch management
                            Activator.log(LogService.LOG_WARNING, null, e.getMessage(), e, false);
                        }
                    }
                    return false;
                }
                boolean baselineSwitched = handleNonCurrentBaseline(fork, version, tagName, false, true);
                if (localMavenRepository != null) {
                    try {
                        File systemRepo = getSystemRepository(karafHome, systemContext);
                        // let's copy artifacts referenced in etc/startup.properties from localMavenRepository to system
                        File etcStartupProperties = new File(karafBase, "etc/startup.properties");
                        try (FileInputStream fis = new FileInputStream(etcStartupProperties)) {
                            Properties props = new Properties();
                            props.load(fis);
                            for (String artifact : props.stringPropertyNames()) {
                                File target = new File(systemRepo, artifact);
                                File src = new File(localMavenRepository, artifact);
                                if (!target.exists() && src.isFile()) {
                                    FileUtils.copyFile(src, target);
                                }
                            }
                        }
                        // now the URLs from the passed lis
                        for (String url : urls) {
                            String path = Utils.mvnurlToPath(url);
                            if (path != null) {
                                File target = new File(systemRepo, path);
                                File src = new File(localMavenRepository, path);
                                if (!target.exists() && src.isFile()) {
                                    FileUtils.copyFile(src, target);
                                }
                            }
                        }
                    } catch (Exception e) {
                        Activator.log(LogService.LOG_ERROR, null, e.getMessage(), e, false);
                    }
                }
                return baselineSwitched;
            } catch (Exception e) {
                throw new PatchException(e.getMessage(), e);
            } finally {
                ensuringLock.unlock();
                if (fork != null) {
                    gitPatchRepository.closeRepository(fork, true);
                }
            }
        }
        return false;
    } finally {
        aligning.set(false);
    }
}
Also used : Git(org.eclipse.jgit.api.Git) RevTag(org.eclipse.jgit.revwalk.RevTag) PatchException(io.fabric8.patch.management.PatchException) Properties(java.util.Properties) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) PatchException(io.fabric8.patch.management.PatchException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) FileInputStream(java.io.FileInputStream)

Example 19 with Agent

use of io.fabric8.agent.service.Agent 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 20 with Agent

use of io.fabric8.agent.service.Agent in project fabric8 by jboss-fuse.

the class FabricPatchServiceImpl method bundleUpdatesInPatch.

/**
 * Simpler (than in standalone scenario) method of checking what bundles are updated with currently installed
 * {@link PatchKind#ROLLUP rollup patch}.
 * We only care about core bundles updated - all other bundles are handled by fabric agent.
 * @param patch
 * @return
 */
private List<BundleUpdate> bundleUpdatesInPatch(Patch patch) throws IOException {
    List<BundleUpdate> updatesInThisPatch = new LinkedList<>();
    for (String newLocation : patch.getPatchData().getBundles()) {
        // [symbolicName, version] of the new bundle
        String[] symbolicNameVersion = helper.getBundleIdentity(newLocation);
        if (symbolicNameVersion == null || symbolicNameVersion[0] == null) {
            continue;
        }
        String sn = stripSymbolicName(symbolicNameVersion[0]);
        String vr = symbolicNameVersion[1];
        Version newVersion = VersionTable.getVersion(vr);
        BundleUpdate update = new BundleUpdate(sn, newVersion.toString(), newLocation, null, null);
        update.setIndependent(true);
        updatesInThisPatch.add(update);
    }
    return updatesInThisPatch;
}
Also used : Version(org.osgi.framework.Version) BundleUpdate(io.fabric8.patch.management.BundleUpdate) LinkedList(java.util.LinkedList)

Aggregations

IOException (java.io.IOException)8 FabricService (io.fabric8.api.FabricService)7 Container (io.fabric8.api.Container)6 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 Map (java.util.Map)6 Test (org.junit.Test)6 Bundle (org.osgi.framework.Bundle)5 BundleContext (org.osgi.framework.BundleContext)5 Profile (io.fabric8.api.Profile)4 File (java.io.File)4 BundleException (org.osgi.framework.BundleException)4 MultiException (io.fabric8.common.util.MultiException)3 FileInputStream (java.io.FileInputStream)3 List (java.util.List)3 Set (java.util.Set)3 ConfigurationException (org.osgi.service.cm.ConfigurationException)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 DownloadManager (io.fabric8.agent.download.DownloadManager)2 Downloader (io.fabric8.agent.download.Downloader)2