Search in sources :

Example 1 with DownloadCallback

use of io.fabric8.agent.download.DownloadCallback in project fabric8 by jboss-fuse.

the class Agent method loadResources.

// 
// State support
// 
public static Callable<Map<String, Resource>> loadResources(DownloadManager manager, Map<String, Map<VersionRange, Map<String, String>>> metadata, Set<String> uris) throws MultiException, InterruptedException, MalformedURLException {
    final Map<String, Resource> resources = new HashMap<>();
    final Downloader downloader = manager.createDownloader();
    final MetadataBuilder builder = new MetadataBuilder(metadata);
    final DownloadCallback callback = new DownloadCallback() {

        @Override
        public void downloaded(StreamProvider provider) throws Exception {
            String uri = provider.getUrl();
            Map<String, String> headers = builder.getMetadata(uri, provider.getFile());
            Resource resource = ResourceBuilder.build(uri, headers);
            synchronized (resources) {
                resources.put(uri, resource);
            }
        }
    };
    for (String uri : uris) {
        downloader.download(uri, callback);
    }
    return new Callable<Map<String, Resource>>() {

        @Override
        public Map<String, Resource> call() throws Exception {
            downloader.await();
            return resources;
        }
    };
}
Also used : StreamProvider(io.fabric8.agent.download.StreamProvider) HashMap(java.util.HashMap) DownloadCallback(io.fabric8.agent.download.DownloadCallback) Resource(org.osgi.resource.Resource) Downloader(io.fabric8.agent.download.Downloader) Callable(java.util.concurrent.Callable)

Example 2 with DownloadCallback

use of io.fabric8.agent.download.DownloadCallback in project fabric8 by jboss-fuse.

the class AgentUtils method downloadLocations.

public static Map<String, File> downloadLocations(DownloadManager manager, Collection<String> uris, final boolean storeInDefaultKarafRepository) throws MultiException, InterruptedException, MalformedURLException {
    final Map<String, File> files = new HashMap<>();
    final Downloader downloader = manager.createDownloader();
    final File targetLocation = storeInDefaultKarafRepository ? getDefaultKarafRepository() : null;
    for (String uri : uris) {
        downloader.download(uri, new DownloadCallback() {

            @Override
            public void downloaded(StreamProvider provider) throws Exception {
                String uri = provider.getUrl();
                File file = provider.getFile();
                synchronized (files) {
                    files.put(uri, file);
                    if (storeInDefaultKarafRepository) {
                        storeInDefaultKarafRepository(targetLocation, file, uri);
                    }
                }
            }
        });
    }
    downloader.await();
    return files;
}
Also used : StreamProvider(io.fabric8.agent.download.StreamProvider) HashMap(java.util.HashMap) DownloadCallback(io.fabric8.agent.download.DownloadCallback) Downloader(io.fabric8.agent.download.Downloader) File(java.io.File) MalformedURLException(java.net.MalformedURLException) MultiException(io.fabric8.common.util.MultiException)

Example 3 with DownloadCallback

use of io.fabric8.agent.download.DownloadCallback in project fabric8 by jboss-fuse.

the class DeploymentAgent method doUpdate.

public boolean doUpdate(Dictionary<String, ?> props) throws Exception {
    if (props == null || Boolean.parseBoolean((String) props.get("disabled"))) {
        return false;
    }
    final Hashtable<String, String> properties = new Hashtable<>();
    for (Enumeration e = props.keys(); e.hasMoreElements(); ) {
        Object key = e.nextElement();
        Object val = props.get(key);
        if (!"service.pid".equals(key) && !FeatureConfigInstaller.FABRIC_ZOOKEEPER_PID.equals(key)) {
            properties.put(key.toString(), val.toString());
        }
    }
    updateStatus("analyzing", null);
    // Building configuration
    curatorCompleteService.waitForService(TimeUnit.SECONDS.toMillis(30));
    String httpUrl;
    List<URI> mavenRepoURIs;
    // force reading of updated informations from ZK
    if (!fabricService.isEmpty()) {
        updateMavenRepositoryConfiguration(fabricService.getService());
    }
    try {
        fabricServiceOperations.lock();
        // no one will change the members now
        httpUrl = this.httpUrl;
        mavenRepoURIs = this.mavenRepoURIs;
    } finally {
        fabricServiceOperations.unlock();
    }
    addMavenProxies(properties, httpUrl, mavenRepoURIs);
    final MavenResolver resolver = MavenResolvers.createMavenResolver(properties, "org.ops4j.pax.url.mvn");
    final DownloadManager manager = DownloadManagers.createDownloadManager(resolver, getDownloadExecutor());
    manager.addListener(new DownloadCallback() {

        @Override
        public void downloaded(StreamProvider provider) throws Exception {
            int pending = manager.pending();
            updateStatus(pending > 0 ? "downloading (" + pending + " pending)" : "downloading", null);
        }
    });
    // Update framework, libs, system and config props
    final Object lock = new Object();
    final AtomicBoolean restart = new AtomicBoolean();
    final Set<String> libsToRemove = new HashSet<>(managedLibs.keySet());
    final Set<String> endorsedLibsToRemove = new HashSet<>(managedEndorsedLibs.keySet());
    final Set<String> extensionLibsToRemove = new HashSet<>(managedExtensionLibs.keySet());
    final Set<String> sysPropsToRemove = new HashSet<>(managedSysProps.keySet());
    final Set<String> configPropsToRemove = new HashSet<>(managedConfigProps.keySet());
    final Set<String> etcsToRemove = new HashSet<>(managedEtcs.keySet());
    final Properties configProps = new Properties(new File(KARAF_BASE + File.separator + "etc" + File.separator + "config.properties"));
    final Properties systemProps = new Properties(new File(KARAF_BASE + File.separator + "etc" + File.separator + "system.properties"));
    Downloader downloader = manager.createDownloader();
    for (String key : properties.keySet()) {
        if (key.equals("framework")) {
            String url = properties.get(key);
            if (!url.startsWith("mvn:")) {
                throw new IllegalArgumentException("Framework url must use the mvn: protocol");
            }
            downloader.download(url, new DownloadCallback() {

                @Override
                public void downloaded(StreamProvider provider) throws Exception {
                    File file = provider.getFile();
                    String path = file.getPath();
                    if (path.startsWith(KARAF_HOME)) {
                        path = path.substring(KARAF_HOME.length() + 1);
                    }
                    synchronized (lock) {
                        if (!path.equals(configProps.get("karaf.framework.felix"))) {
                            configProps.put("karaf.framework", "felix");
                            configProps.put("karaf.framework.felix", path);
                            restart.set(true);
                        }
                    }
                }
            });
        } else if (key.startsWith("config.")) {
            String k = key.substring("config.".length());
            String v = properties.get(key);
            synchronized (lock) {
                managedConfigProps.put(k, v);
                configPropsToRemove.remove(k);
                if (!v.equals(configProps.get(k))) {
                    configProps.put(k, v);
                    restart.set(true);
                }
            }
        } else if (key.startsWith("system.")) {
            String k = key.substring("system.".length());
            synchronized (lock) {
                String v = properties.get(key);
                managedSysProps.put(k, v);
                sysPropsToRemove.remove(k);
                if (!v.equals(systemProps.get(k))) {
                    systemProps.put(k, v);
                    restart.set(true);
                }
            }
        } else if (key.startsWith("lib.")) {
            String value = properties.get(key);
            downloader.download(value, new DownloadCallback() {

                @Override
                public void downloaded(StreamProvider provider) throws Exception {
                    File libFile = provider.getFile();
                    String libName = libFile.getName();
                    Long checksum = ChecksumUtils.checksum(libFile);
                    boolean update;
                    synchronized (lock) {
                        managedLibs.put(libName, "true");
                        libsToRemove.remove(libName);
                        update = !Long.toString(checksum).equals(libChecksums.getProperty(libName));
                    }
                    if (update) {
                        Files.copy(libFile, new File(LIB_PATH, libName));
                        restart.set(true);
                    }
                }
            });
        } else if (key.startsWith("endorsed.")) {
            String value = properties.get(key);
            downloader.download(value, new DownloadCallback() {

                @Override
                public void downloaded(StreamProvider provider) throws Exception {
                    File libFile = provider.getFile();
                    String libName = libFile.getName();
                    Long checksum = ChecksumUtils.checksum(new FileInputStream(libFile));
                    boolean update;
                    synchronized (lock) {
                        managedEndorsedLibs.put(libName, "true");
                        endorsedLibsToRemove.remove(libName);
                        update = !Long.toString(checksum).equals(endorsedChecksums.getProperty(libName));
                    }
                    if (update) {
                        Files.copy(libFile, new File(LIB_ENDORSED_PATH, libName));
                        restart.set(true);
                    }
                }
            });
        } else if (key.startsWith("extension.")) {
            String value = properties.get(key);
            downloader.download(value, new DownloadCallback() {

                @Override
                public void downloaded(StreamProvider provider) throws Exception {
                    File libFile = provider.getFile();
                    String libName = libFile.getName();
                    Long checksum = ChecksumUtils.checksum(libFile);
                    boolean update;
                    synchronized (lock) {
                        managedExtensionLibs.put(libName, "true");
                        extensionLibsToRemove.remove(libName);
                        update = !Long.toString(checksum).equals(extensionChecksums.getProperty(libName));
                    }
                    if (update) {
                        Files.copy(libFile, new File(LIB_EXT_PATH, libName));
                        restart.set(true);
                    }
                }
            });
        } else if (key.startsWith("etc.")) {
            String value = properties.get(key);
            downloader.download(value, new DownloadCallback() {

                @Override
                public void downloaded(StreamProvider provider) throws Exception {
                    File etcFile = provider.getFile();
                    String etcName = etcFile.getName();
                    Long checksum = ChecksumUtils.checksum(new FileInputStream(etcFile));
                    boolean update;
                    synchronized (lock) {
                        managedEtcs.put(etcName, "true");
                        etcsToRemove.remove(etcName);
                        update = !Long.toString(checksum).equals(etcChecksums.getProperty(etcName));
                    }
                    if (update) {
                        Files.copy(etcFile, new File(KARAF_ETC, etcName));
                    }
                }
            });
        }
    }
    downloader.await();
    // Remove unused libs, system & config properties
    for (String sysProp : sysPropsToRemove) {
        systemProps.remove(sysProp);
        managedSysProps.remove(sysProp);
        System.clearProperty(sysProp);
        restart.set(true);
    }
    for (String configProp : configPropsToRemove) {
        configProps.remove(configProp);
        managedConfigProps.remove(configProp);
        restart.set(true);
    }
    for (String lib : libsToRemove) {
        File libFile = new File(LIB_PATH, lib);
        libFile.delete();
        libChecksums.remove(lib);
        managedLibs.remove(lib);
        restart.set(true);
    }
    for (String lib : endorsedLibsToRemove) {
        File libFile = new File(LIB_ENDORSED_PATH, lib);
        libFile.delete();
        endorsedChecksums.remove(lib);
        managedEndorsedLibs.remove(lib);
        restart.set(true);
    }
    for (String lib : extensionLibsToRemove) {
        File libFile = new File(LIB_EXT_PATH, lib);
        libFile.delete();
        extensionChecksums.remove(lib);
        managedExtensionLibs.remove(lib);
        restart.set(true);
    }
    for (String etc : etcsToRemove) {
        File etcFile = new File(KARAF_ETC, etc);
        etcFile.delete();
        etcChecksums.remove(etc);
        managedEtcs.remove(etc);
    }
    libChecksums.save();
    endorsedChecksums.save();
    extensionChecksums.save();
    etcChecksums.save();
    managedLibs.save();
    managedEndorsedLibs.save();
    managedExtensionLibs.save();
    managedConfigProps.save();
    managedSysProps.save();
    managedEtcs.save();
    if (restart.get()) {
        updateStatus("restarting", null);
        configProps.save();
        systemProps.save();
        System.setProperty("karaf.restart", "true");
        bundleContext.getBundle(0).stop();
        return false;
    }
    FeatureConfigInstaller configInstaller = null;
    ServiceReference configAdminServiceReference = bundleContext.getServiceReference(ConfigurationAdmin.class.getName());
    if (configAdminServiceReference != null) {
        ConfigurationAdmin configAdmin = (ConfigurationAdmin) bundleContext.getService(configAdminServiceReference);
        configInstaller = new FeatureConfigInstaller(bundleContext, configAdmin, manager);
    }
    int bundleStartTimeout = Constants.BUNDLE_START_TIMEOUT;
    String overriddenTimeout = properties.get(Constants.BUNDLE_START_TIMEOUT_PID_KEY);
    try {
        if (overriddenTimeout != null)
            bundleStartTimeout = Integer.parseInt(overriddenTimeout);
    } catch (Exception e) {
        LOGGER.warn("Failed to set {} value: [{}], applying default value: {}", Constants.BUNDLE_START_TIMEOUT_PID_KEY, overriddenTimeout, Constants.BUNDLE_START_TIMEOUT);
    }
    Agent agent = new Agent(bundleContext.getBundle(), systemBundleContext, manager, configInstaller, null, DEFAULT_FEATURE_RESOLUTION_RANGE, DEFAULT_BUNDLE_UPDATE_RANGE, DEFAULT_UPDATE_SNAPSHOTS, bundleContext.getDataFile(STATE_FILE), bundleStartTimeout) {

        @Override
        public void updateStatus(String status) {
            DeploymentAgent.this.updateStatus(status, null, false);
        }

        @Override
        public void updateStatus(String status, boolean force) {
            DeploymentAgent.this.updateStatus(status, null, force);
        }

        @Override
        protected void saveState(State newState) throws IOException {
            super.saveState(newState);
            DeploymentAgent.this.state.replace(newState);
        }

        @Override
        protected void provisionList(Set<Resource> resources) {
            DeploymentAgent.this.provisionList = resources;
        }

        @Override
        protected boolean done(boolean agentStarted, List<String> urls) {
            if (agentStarted) {
                // let's do patch-management "last touch" only if new agent wasn't started.
                return true;
            }
            // agent finished provisioning, we can call back to low level patch management
            ServiceReference<PatchManagement> srPm = systemBundleContext.getServiceReference(PatchManagement.class);
            ServiceReference<FabricService> srFs = systemBundleContext.getServiceReference(FabricService.class);
            if (srPm != null && srFs != null) {
                PatchManagement pm = systemBundleContext.getService(srPm);
                FabricService fs = systemBundleContext.getService(srFs);
                if (pm != null && fs != null) {
                    LOGGER.info("Validating baseline information");
                    this.updateStatus("validating baseline information", true);
                    Profile profile = fs.getCurrentContainer().getOverlayProfile();
                    Map<String, String> versions = profile.getConfiguration("io.fabric8.version");
                    File localRepository = resolver.getLocalRepository();
                    if (pm.alignTo(versions, urls, localRepository, new PatchSynchronization())) {
                        this.updateStatus("requires full restart", true);
                        // let's reuse the same flag
                        restart.set(true);
                        return false;
                    }
                    if (handleRestartJvmFlag(profile, restart)) {
                        return false;
                    }
                }
            }
            return true;
        }
    };
    agent.setDeploymentAgentId(deploymentAgentId);
    agent.provision(getPrefixedProperties(properties, "repository."), getPrefixedProperties(properties, "feature."), getPrefixedProperties(properties, "bundle."), getPrefixedProperties(properties, "req."), getPrefixedProperties(properties, "override."), getPrefixedProperties(properties, "optional."), getMetadata(properties, "metadata#"));
    if (restart.get()) {
        // prevent updating status to "success"
        return false;
    }
    return true;
}
Also used : Set(java.util.Set) TreeSet(java.util.TreeSet) HashSet(java.util.HashSet) DownloadCallback(io.fabric8.agent.download.DownloadCallback) Downloader(io.fabric8.agent.download.Downloader) Properties(org.apache.felix.utils.properties.Properties) URI(java.net.URI) DownloadManager(io.fabric8.agent.download.DownloadManager) Profile(io.fabric8.api.Profile) PatchManagement(io.fabric8.patch.management.PatchManagement) MavenResolver(io.fabric8.maven.MavenResolver) List(java.util.List) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Agent(io.fabric8.agent.service.Agent) StreamProvider(io.fabric8.agent.download.StreamProvider) Enumeration(java.util.Enumeration) Hashtable(java.util.Hashtable) ConfigurationException(org.osgi.service.cm.ConfigurationException) BundleException(org.osgi.framework.BundleException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) ServiceReference(org.osgi.framework.ServiceReference) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FeatureConfigInstaller(io.fabric8.agent.service.FeatureConfigInstaller) State(io.fabric8.agent.service.State) FabricService(io.fabric8.api.FabricService) File(java.io.File) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin)

Example 4 with DownloadCallback

use of io.fabric8.agent.download.DownloadCallback in project fabric8 by jboss-fuse.

the class ArchetypeGenerateAction method fetchArchetype.

/**
 * Fetches archetype from the configured repositories
 * TODO: make this code available to hawt.io/JMX too
 */
private File fetchArchetype(Archetype archetype) throws IOException {
    MavenResolver resolver = MavenResolvers.createMavenResolver(new Hashtable<String, String>(), "org.ops4j.pax.url.mvn");
    DownloadManager dm = DownloadManagers.createDownloadManager(resolver, Executors.newSingleThreadScheduledExecutor());
    final AtomicReference<File> file = new AtomicReference<>();
    String url = String.format("mvn:%s/%s/%s", archetype.groupId, archetype.artifactId, archetype.version);
    Downloader downloader = dm.createDownloader();
    downloader.download(url, new DownloadCallback() {

        @Override
        public void downloaded(StreamProvider provider) throws Exception {
            file.set(provider.getFile());
        }
    });
    // wait for download
    try {
        boolean init = false;
        for (int i = 0; i < 2 * 60 && file.get() == null; i++) {
            // dont do anything in the first 3 seconds as we likely can download it faster
            if (i > 3) {
                if (!init) {
                    System.out.print("Downloading archetype in progress: ");
                    init = true;
                }
                System.out.print(".");
            }
            // only sleep 0.5 sec so we can react faster
            Thread.sleep(500);
        }
    } catch (InterruptedException e) {
        System.err.println("\nFailed to download " + archetype);
        throw new IOException(e.getMessage(), e);
    }
    try {
        downloader.await();
        return file.get();
    } catch (Exception e) {
        System.err.println("\nFailed to download archetype within 60 seconds: " + archetype);
        throw new IOException("Failed to download archetype within 60 seconds: " + archetype);
    }
}
Also used : StreamProvider(io.fabric8.agent.download.StreamProvider) DownloadCallback(io.fabric8.agent.download.DownloadCallback) Downloader(io.fabric8.agent.download.Downloader) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) DownloadManager(io.fabric8.agent.download.DownloadManager) IOException(java.io.IOException) MavenResolver(io.fabric8.maven.MavenResolver) File(java.io.File)

Example 5 with DownloadCallback

use of io.fabric8.agent.download.DownloadCallback in project fabric8 by jboss-fuse.

the class AgentUtils method downloadRepositories.

public static Callable<Map<String, Repository>> downloadRepositories(DownloadManager manager, Set<String> uris) throws MultiException, InterruptedException, MalformedURLException {
    final Map<String, Repository> repositories = new HashMap<>();
    final Downloader downloader = manager.createDownloader();
    final File targetLocation = getDefaultKarafRepository();
    for (String uri : uris) {
        downloader.download(uri, new DownloadCallback() {

            @Override
            public void downloaded(StreamProvider provider) throws Exception {
                String uri = provider.getUrl();
                Repository repository = new Repository(URI.create(uri));
                repository.load(new FileInputStream(provider.getFile()), true);
                synchronized (repositories) {
                    repositories.put(uri, repository);
                }
                for (URI repo : repository.getRepositories()) {
                    downloader.download(repo.toASCIIString(), this);
                }
                Artifact artifact = Utils.mvnurlToArtifact(uri, true);
                if (artifact == null || artifact.getVersion() == null || !artifact.getVersion().endsWith("-SNAPSHOT")) {
                    // we need a feature repository to be available in ${karaf.home}/${karaf.default.repository}
                    // it makes patching much easier
                    // ENTESB-6931: don't store SNAPSHOT feature repositories in ${karaf.home}/${karaf.default.repository}
                    storeInDefaultKarafRepository(targetLocation, provider.getFile(), uri);
                }
            }
        });
    }
    return new Callable<Map<String, Repository>>() {

        @Override
        public Map<String, Repository> call() throws Exception {
            downloader.await();
            return repositories;
        }
    };
}
Also used : StreamProvider(io.fabric8.agent.download.StreamProvider) HashMap(java.util.HashMap) DownloadCallback(io.fabric8.agent.download.DownloadCallback) Downloader(io.fabric8.agent.download.Downloader) URI(java.net.URI) MalformedURLException(java.net.MalformedURLException) MultiException(io.fabric8.common.util.MultiException) FileInputStream(java.io.FileInputStream) Artifact(io.fabric8.patch.management.Artifact) Callable(java.util.concurrent.Callable) Repository(io.fabric8.agent.model.Repository) File(java.io.File)

Aggregations

DownloadCallback (io.fabric8.agent.download.DownloadCallback)5 Downloader (io.fabric8.agent.download.Downloader)5 StreamProvider (io.fabric8.agent.download.StreamProvider)5 File (java.io.File)4 HashMap (java.util.HashMap)3 DownloadManager (io.fabric8.agent.download.DownloadManager)2 MultiException (io.fabric8.common.util.MultiException)2 MavenResolver (io.fabric8.maven.MavenResolver)2 FileInputStream (java.io.FileInputStream)2 IOException (java.io.IOException)2 MalformedURLException (java.net.MalformedURLException)2 URI (java.net.URI)2 Callable (java.util.concurrent.Callable)2 Repository (io.fabric8.agent.model.Repository)1 Agent (io.fabric8.agent.service.Agent)1 FeatureConfigInstaller (io.fabric8.agent.service.FeatureConfigInstaller)1 State (io.fabric8.agent.service.State)1 FabricService (io.fabric8.api.FabricService)1 Profile (io.fabric8.api.Profile)1 Artifact (io.fabric8.patch.management.Artifact)1