Search in sources :

Example 16 with Resource

use of io.fabric8.support.api.Resource in project kie-wb-common by kiegroup.

the class OpenShiftClient method addSystemGroupRole.

private void addSystemGroupRole(String prjName, String name, String role) {
    Resource<PolicyBinding, DoneablePolicyBinding> bindingResource = delegate.policyBindings().inNamespace(prjName).withName(":default");
    DoneablePolicyBinding binding;
    if (bindingResource.get() == null) {
        binding = bindingResource.createNew();
    } else {
        binding = bindingResource.edit();
    }
    binding.editOrNewMetadata().withName(":default").endMetadata().editOrNewPolicyRef().withName("default").endPolicyRef().addNewRoleBinding().withName(role).editOrNewRoleBinding().editOrNewMetadata().withName(role).withNamespace(prjName).endMetadata().addToGroupNames("system:serviceaccounts:" + prjName).addNewSubject().withName("default").withNamespace(prjName).withKind("SystemGroup").endSubject().withNewRoleRef().withName(role).endRoleRef().endRoleBinding().endRoleBinding().done();
}
Also used : DoneablePolicyBinding(io.fabric8.openshift.api.model.DoneablePolicyBinding) DoneablePolicyBinding(io.fabric8.openshift.api.model.DoneablePolicyBinding) PolicyBinding(io.fabric8.openshift.api.model.PolicyBinding)

Example 17 with Resource

use of io.fabric8.support.api.Resource in project fabric8 by jboss-fuse.

the class OpenshiftContainerProvider method create.

@Override
public CreateOpenshiftContainerMetadata create(CreateOpenshiftContainerOptions options, CreationStateListener listener) throws Exception {
    assertValid();
    IUser user = getOrCreateConnection(options).getUser();
    IDomain domain = getOrCreateDomain(user, options);
    String cartridgeUrl = null;
    Set<String> profiles = options.getProfiles();
    String versionId = options.getVersion();
    Map<String, String> openshiftConfigOverlay = new HashMap<String, String>();
    if (profiles != null && versionId != null) {
        ProfileService profileService = fabricService.get().adapt(ProfileService.class);
        Version version = profileService.getVersion(versionId);
        if (version != null) {
            for (String profileId : profiles) {
                Profile profile = version.getRequiredProfile(profileId);
                if (profile != null) {
                    Profile overlay = profileService.getOverlayProfile(profile);
                    Map<String, String> openshiftConfig = overlay.getConfiguration(OpenShiftConstants.OPENSHIFT_PID);
                    if (openshiftConfig != null) {
                        openshiftConfigOverlay.putAll(openshiftConfig);
                    }
                }
            }
        }
        cartridgeUrl = openshiftConfigOverlay.get("cartridge");
    }
    if (cartridgeUrl == null) {
        cartridgeUrl = defaultCartridgeUrl;
    }
    String[] cartridgeUrls = cartridgeUrl.split(" ");
    LOG.info("Creating cartridges: " + cartridgeUrl);
    String standAloneCartridgeUrl = cartridgeUrls[0];
    StandaloneCartridge cartridge;
    if (standAloneCartridgeUrl.startsWith(PREFIX_CARTRIDGE_ID)) {
        cartridge = new StandaloneCartridge(standAloneCartridgeUrl.substring(PREFIX_CARTRIDGE_ID.length()));
    } else {
        cartridge = new StandaloneCartridge(new URL(standAloneCartridgeUrl));
    }
    String zookeeperUrl = fabricService.get().getZookeeperUrl();
    String zookeeperPassword = fabricService.get().getZookeeperPassword();
    Map<String, String> userEnvVars = null;
    if (!options.isEnsembleServer()) {
        userEnvVars = new HashMap<String, String>();
        userEnvVars.put("OPENSHIFT_FUSE_ZOOKEEPER_URL", zookeeperUrl);
        userEnvVars.put("OPENSHIFT_FUSE_ZOOKEEPER_PASSWORD", zookeeperPassword);
        String zkPasswordEncode = System.getProperty("zookeeper.password.encode", "true");
        userEnvVars.put("OPENSHIFT_FUSE_ZOOKEEPER_PASSWORD_ENCODE", zkPasswordEncode);
        userEnvVars.put("OPENSHIFT_FUSE_CREATED_FROM_FABRIC", "true");
    }
    String initGitUrl = null;
    int timeout = IHttpClient.NO_TIMEOUT;
    ApplicationScale scale = null;
    String containerName = options.getName();
    long t0 = System.currentTimeMillis();
    IApplication application;
    try {
        application = domain.createApplication(containerName, cartridge, scale, new GearProfile(options.getGearProfile()), initGitUrl, timeout, userEnvVars);
    } catch (OpenShiftTimeoutException e) {
        long t1;
        do {
            Thread.sleep(5000);
            domain.refresh();
            application = domain.getApplicationByName(containerName);
            if (application != null) {
                break;
            }
            t1 = System.currentTimeMillis();
        } while (t1 - t0 < TimeUnit.MILLISECONDS.convert(15, TimeUnit.MINUTES));
    }
    LOG.info("Created application " + containerName);
    // now lets add all the embedded cartridges
    List<IEmbeddableCartridge> list = new ArrayList<IEmbeddableCartridge>();
    for (int idx = 1, size = cartridgeUrls.length; idx < size; idx++) {
        String embeddedUrl = cartridgeUrls[idx];
        LOG.info("Adding embedded cartridge: " + embeddedUrl);
        if (embeddedUrl.startsWith(PREFIX_CARTRIDGE_ID)) {
            list.add(new EmbeddableCartridge(embeddedUrl.substring(PREFIX_CARTRIDGE_ID.length())));
        } else {
            list.add(new EmbeddableCartridge(new URL(embeddedUrl)));
        }
    }
    if (!list.isEmpty()) {
        application.addEmbeddableCartridges(list);
    }
    String gitUrl = application.getGitUrl();
    // in case of OpenShiftTimeoutException, application resource doesn't contain getCreationLog().
    // actually this method throws NPE
    CreateOpenshiftContainerMetadata metadata = new CreateOpenshiftContainerMetadata(domain.getId(), application.getUUID(), application.getMessages() == null ? "" : application.getCreationLog(), gitUrl);
    metadata.setContainerName(containerName);
    metadata.setCreateOptions(options);
    return metadata;
}
Also used : HashMap(java.util.HashMap) ApplicationScale(com.openshift.client.ApplicationScale) OpenShiftTimeoutException(com.openshift.client.OpenShiftTimeoutException) ArrayList(java.util.ArrayList) GearProfile(com.openshift.internal.client.GearProfile) Profile(io.fabric8.api.Profile) IGearProfile(com.openshift.client.IGearProfile) URL(java.net.URL) IDomain(com.openshift.client.IDomain) IApplication(com.openshift.client.IApplication) ProfileService(io.fabric8.api.ProfileService) Version(io.fabric8.api.Version) GearProfile(com.openshift.internal.client.GearProfile) IGearProfile(com.openshift.client.IGearProfile) IUser(com.openshift.client.IUser) EmbeddableCartridge(com.openshift.client.cartridge.EmbeddableCartridge) IEmbeddableCartridge(com.openshift.client.cartridge.IEmbeddableCartridge) StandaloneCartridge(com.openshift.client.cartridge.StandaloneCartridge) IEmbeddableCartridge(com.openshift.client.cartridge.IEmbeddableCartridge)

Example 18 with Resource

use of io.fabric8.support.api.Resource 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 19 with Resource

use of io.fabric8.support.api.Resource in project fabric8 by jboss-fuse.

the class Deployer method logDeployment.

protected void logDeployment(Deployer.Deployment overallDeployment, int verbose) {
    if (overallDeployment.regions.isEmpty()) {
        print("No deployment change.", verbose);
        return;
    }
    print("Changes to perform:", verbose);
    for (Map.Entry<String, RegionDeployment> region : overallDeployment.regions.entrySet()) {
        Deployer.RegionDeployment deployment = region.getValue();
        print("  Region: " + region.getKey(), verbose);
        if (!deployment.toDelete.isEmpty()) {
            print("    Bundles to uninstall:", verbose);
            for (Bundle bundle : deployment.toDelete) {
                print("      " + bundle.getSymbolicName() + " / " + bundle.getVersion(), verbose);
            }
        }
        if (!deployment.toUpdate.isEmpty()) {
            print("    Bundles to update:", verbose);
            for (Map.Entry<Bundle, Resource> entry : deployment.toUpdate.entrySet()) {
                print("      " + entry.getKey().getSymbolicName() + " / " + entry.getKey().getVersion() + " with " + getUri(entry.getValue()), verbose);
            }
        }
        if (!deployment.toInstall.isEmpty()) {
            print("    Bundles to install:", verbose);
            for (Resource resource : deployment.toInstall) {
                print("      " + getUri(resource), verbose);
            }
        }
    }
}
Also used : Bundle(org.osgi.framework.Bundle) Resource(org.osgi.resource.Resource) FeatureResource(io.fabric8.agent.resolver.FeatureResource)

Example 20 with Resource

use of io.fabric8.support.api.Resource in project fabric8 by jboss-fuse.

the class Deployer method computeDeployment.

protected Deployment computeDeployment(DeploymentState dstate, DeploymentRequest request, SubsystemResolver resolver) throws IOException {
    Deployment result = new Deployment();
    Map<String, Set<Resource>> bundlesPerRegions = resolver.getBundlesPerRegions();
    // Gather all regions, including old ones and new ones
    Set<String> regions = new HashSet<>();
    regions.addAll(dstate.state.managedBundles.keySet());
    regions.addAll(bundlesPerRegions.keySet());
    for (String region : regions) {
        Deployer.RegionDeployment deployment = new Deployer.RegionDeployment();
        // Get the list of bundles currently assigned in the region
        Set<Long> managed = dstate.state.managedBundles.get(region);
        if (managed == null) {
            managed = Collections.emptySet();
        }
        // Compute the list of resources to deploy in the region
        Set<Resource> bundlesInRegion = bundlesPerRegions.get(region);
        List<Resource> toDeploy = bundlesInRegion != null ? new ArrayList<>(bundlesInRegion) : new ArrayList<Resource>();
        // as either to ignore or delete
        for (long bundleId : managed) {
            // Look for the installed bundle
            Bundle bundle = dstate.bundles.get(bundleId);
            // Bundle has been manually uninstalled ?
            if (bundle != null) {
                // Look for a matching resource
                Resource resource = null;
                for (Resource res : toDeploy) {
                    if (bundle.getSymbolicName().equals(getSymbolicName(res)) && bundle.getVersion().equals(getVersion(res))) {
                        resource = res;
                        break;
                    }
                }
                // We found a matching bundle
                if (resource != null) {
                    String uri = getUri(resource);
                    // and flag it as to update
                    if (uri != null && isUpdateable(uri)) {
                        // Always update snapshots
                        if (Constants.UPDATE_SNAPSHOTS_ALWAYS.equalsIgnoreCase(request.updateSnaphots)) {
                            LOGGER.debug("Update snapshot for " + bundle.getLocation());
                            deployment.toUpdate.put(bundle, resource);
                        } else if (Constants.UPDATE_SNAPSHOTS_CRC.equalsIgnoreCase(request.updateSnaphots)) {
                            // if the checksum are different
                            InputStream is = null;
                            try {
                                is = getBundleInputStream(resource, resolver.getProviders());
                                Long bpNewCrc = null;
                                try {
                                    URI resourceURI = new URI(uri);
                                    if ("blueprint".equals(resourceURI.getScheme())) {
                                        InputStream bis = getBlueprintInputStream(is);
                                        // original stream is closed in either case
                                        if (bis != null) {
                                            bpNewCrc = ChecksumUtils.checksum(bis);
                                            is = bis;
                                        } else {
                                            // rewind FileInputStream, because we failed to read blueprint
                                            // descriptor
                                            is = getBundleInputStream(resource, resolver.getProviders());
                                        }
                                    }
                                } catch (URISyntaxException ignored) {
                                }
                                long newCrc = bpNewCrc != null ? bpNewCrc : ChecksumUtils.checksum(is);
                                long oldCrc = dstate.state.bundleChecksums.containsKey(bundle.getBundleId()) ? dstate.state.bundleChecksums.get(bundle.getBundleId()) : 0L;
                                if (newCrc != oldCrc) {
                                    LOGGER.debug("New snapshot available for " + bundle.getLocation());
                                    deployment.toUpdate.put(bundle, resource);
                                }
                                result.bundleChecksums.put(bundle.getBundleId(), newCrc);
                            } finally {
                                if (is != null) {
                                    try {
                                        is.close();
                                    } catch (IOException ignored) {
                                    }
                                }
                            }
                        }
                    }
                    // We're done for this resource
                    toDeploy.remove(resource);
                    result.resToBnd.put(resource, bundle);
                // There's no matching resource
                // If the bundle is managed, we need to delete it
                } else if (managed.contains(bundle.getBundleId())) {
                    deployment.toDelete.add(bundle);
                }
            }
        }
        // Second pass on remaining resources
        for (Resource resource : toDeploy) {
            TreeMap<Version, Bundle> matching = new TreeMap<>();
            VersionRange range = new VersionRange(Macro.transform(request.bundleUpdateRange, getVersion(resource).toString()));
            for (Bundle bundle : deployment.toDelete) {
                if (bundle.getSymbolicName().equals(getSymbolicName(resource)) && range.contains(bundle.getVersion())) {
                    matching.put(bundle.getVersion(), bundle);
                }
            }
            if (!matching.isEmpty()) {
                Bundle bundle = matching.lastEntry().getValue();
                deployment.toUpdate.put(bundle, resource);
                deployment.toDelete.remove(bundle);
                result.resToBnd.put(resource, bundle);
            } else {
                deployment.toInstall.add(resource);
            }
        }
        Collections.sort(deployment.toInstall, new ResourceComparator());
        // Add this region if there is something to do
        if (!deployment.toDelete.isEmpty() || !deployment.toUpdate.isEmpty() || !deployment.toInstall.isEmpty()) {
            result.regions.put(region, deployment);
        }
    }
    return result;
}
Also used : MapUtils.addToMapSet(io.fabric8.agent.internal.MapUtils.addToMapSet) MapUtils.removeFromMapSet(io.fabric8.agent.internal.MapUtils.removeFromMapSet) VersionRange(org.apache.felix.utils.version.VersionRange) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) Version(org.osgi.framework.Version) ResourceUtils.getVersion(io.fabric8.agent.resolver.ResourceUtils.getVersion) Bundle(org.osgi.framework.Bundle) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Resource(org.osgi.resource.Resource) FeatureResource(io.fabric8.agent.resolver.FeatureResource) IOException(java.io.IOException)

Aggregations

HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)25 Resource (io.fabric8.kubernetes.client.dsl.Resource)25 Map (java.util.Map)20 Test (org.junit.Test)20 IOException (java.io.IOException)19 HashMap (java.util.HashMap)16 Deployment (io.fabric8.kubernetes.api.model.extensions.Deployment)14 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)14 MixedOperation (io.fabric8.kubernetes.client.dsl.MixedOperation)14 Resource (org.osgi.resource.Resource)14 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)13 NonNamespaceOperation (io.fabric8.kubernetes.client.dsl.NonNamespaceOperation)13 ArrayList (java.util.ArrayList)13 Async (io.vertx.ext.unit.Async)12 File (java.io.File)10 ReplicationController (io.fabric8.kubernetes.api.model.ReplicationController)9 Service (io.fabric8.kubernetes.api.model.Service)9 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)9 DeploymentConfig (io.fabric8.openshift.api.model.DeploymentConfig)8 Bundle (org.osgi.framework.Bundle)7