Search in sources :

Example 1 with Pending

use of io.fabric8.patch.management.Pending in project fabric8 by jboss-fuse.

the class ProfileServiceImpl method deleteProfile.

@Override
public void deleteProfile(FabricService fabricService, String versionId, String profileId, boolean force) {
    assertValid();
    Profile profile = getRequiredProfile(versionId, profileId);
    LOGGER.info("deleteProfile: {}", profile);
    // TODO: what about child profiles ?
    Container[] containers = fabricService != null ? fabricService.getAssociatedContainers(versionId, profileId) : new Container[0];
    if (containers.length == 0) {
        profileRegistry.get().deleteProfile(versionId, profileId);
    } else if (force) {
        for (Container container : containers) {
            container.removeProfiles(profileId);
        }
        profileRegistry.get().deleteProfile(versionId, profileId);
    } else {
        StringBuilder sb = new StringBuilder();
        sb.append("Cannot delete profile:").append(profileId).append(".");
        sb.append("Profile has assigned ").append(containers.length).append(" container(s):");
        for (Container c : containers) {
            sb.append(" ").append(c.getId());
        }
        sb.append(". Use force option to also remove the profile from the containers.");
        throw new FabricException(sb.toString());
    }
    // lets remove any pending requirements on this profile
    FabricRequirements requirements = fabricService != null ? fabricService.getRequirements() : null;
    if (requirements != null && requirements.removeProfileRequirements(profileId)) {
        try {
            fabricService.setRequirements(requirements);
        } catch (IOException e) {
            throw new FabricException("Failed to update requirements after deleting profile " + profileId + ". " + e, e);
        }
    }
}
Also used : Container(io.fabric8.api.Container) FabricException(io.fabric8.api.FabricException) FabricRequirements(io.fabric8.api.FabricRequirements) IOException(java.io.IOException) Profile(io.fabric8.api.Profile)

Example 2 with Pending

use of io.fabric8.patch.management.Pending in project fabric8 by jboss-fuse.

the class BootstrapConfiguration method configureInternal.

void configureInternal(Map<String, ?> conf) throws Exception {
    configuration = configurer.configure(conf, this);
    if (Strings.isNullOrBlank(runtimeId)) {
        throw new IllegalArgumentException("Runtime id must not be null or empty.");
    }
    if (Strings.isNullOrBlank(localResolver)) {
        localResolver = globalResolver;
    }
    String decodedZookeeperPassword = null;
    Properties userProps = new Properties();
    try {
        userProps.load(new File(confDir, "users.properties"));
    } catch (IOException e) {
        LOGGER.warn("Failed to load users from etc/users.properties. No users will be imported.", e);
    }
    if (Strings.isNotBlank(zookeeperPassword)) {
        decodedZookeeperPassword = PasswordEncoder.decode(zookeeperPassword);
    } else if (userProps.containsKey(DEFAULT_ADMIN_USER)) {
        String passwordAndRole = userProps.getProperty(DEFAULT_ADMIN_USER).trim();
        decodedZookeeperPassword = passwordAndRole.substring(0, passwordAndRole.indexOf(ROLE_DELIMITER));
    } else {
        decodedZookeeperPassword = PasswordEncoder.encode(CreateEnsembleOptions.generatePassword());
    }
    // do not trigger io.fabric8.zookeeper update if restart is pending (fabric:join)
    if (!Boolean.getBoolean("karaf.restart") && zookeeperUrl != null && zookeeperPassword != null) {
        Configuration zkConfugiration = configAdmin.get().getConfiguration(Constants.ZOOKEEPER_CLIENT_PID);
        if (zkConfugiration.getProperties() == null) {
            Hashtable<String, Object> zkProperties = new Hashtable<>();
            zkProperties.put("zookeeper.url", zookeeperUrl);
            zkProperties.put("zookeeper.password", PasswordEncoder.encode(decodedZookeeperPassword));
            zkConfugiration.update(zkProperties);
        }
    }
    if (userProps.isEmpty()) {
        userProps.put(DEFAULT_ADMIN_USER, decodedZookeeperPassword + ROLE_DELIMITER + DEFAULT_ADMIN_ROLE);
    }
    String minimumPort = (String) configuration.get("minimum.port");
    if (!Strings.isNullOrBlank(minimumPort)) {
        this.minport = Integer.valueOf(minimumPort);
    }
    String maximumPort = (String) configuration.get("maximum.port");
    if (!Strings.isNullOrBlank(maximumPort)) {
        this.maxport = Integer.valueOf(maximumPort);
    }
    options = CreateEnsembleOptions.builder().bindAddress(bindAddress).agentEnabled(agentAutoStart).ensembleStart(ensembleAutoStart).zookeeperPassword(decodedZookeeperPassword).zooKeeperServerPort(zookeeperServerPort).zooKeeperServerConnectionPort(zookeeperServerConnectionPort).autoImportEnabled(profilesAutoImport).importPath(profilesAutoImportPath).resolver(localResolver).globalResolver(globalResolver).users(userProps).minimumPort(minport).maximumPort(maxport).profiles(profiles).version(version).build();
}
Also used : Configuration(org.osgi.service.cm.Configuration) Hashtable(java.util.Hashtable) IOException(java.io.IOException) RuntimeProperties(io.fabric8.api.RuntimeProperties) Properties(org.apache.felix.utils.properties.Properties) File(java.io.File)

Example 3 with Pending

use of io.fabric8.patch.management.Pending in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method checkPendingPatches.

@Override
public void checkPendingPatches() {
    File[] pendingPatches = patchesDir.listFiles(new FileFilter() {

        @Override
        public boolean accept(File pathname) {
            return pathname.exists() && pathname.getName().endsWith(".pending");
        }
    });
    if (pendingPatches == null || pendingPatches.length == 0) {
        return;
    }
    final String dataCache = systemContext.getProperty("org.osgi.framework.storage");
    for (File pending : pendingPatches) {
        try {
            Pending what = Pending.valueOf(FileUtils.readFileToString(pending));
            final String prefix = what == Pending.ROLLUP_INSTALLATION ? "install" : "rollback";
            String name = pending.getName().replaceFirst("\\.pending$", "");
            if (isStandaloneChild()) {
                if (name.endsWith("." + System.getProperty("karaf.name") + ".patch")) {
                    name = name.replaceFirst("\\." + System.getProperty("karaf.name"), "");
                } else {
                    continue;
                }
            }
            File patchFile = new File(pending.getParentFile(), name);
            if (!patchFile.isFile()) {
                Activator.log(LogService.LOG_INFO, "Ignoring patch result file: " + patchFile.getName());
                continue;
            }
            PatchData patchData = PatchData.load(new FileInputStream(patchFile));
            Patch patch = loadPatch(new PatchDetailsRequest(patchData.getId()));
            String dataFilesName = patchData.getId() + ".datafiles";
            if (isStandaloneChild()) {
                dataFilesName = patchData.getId() + "." + System.getProperty("karaf.name") + ".datafiles";
            }
            final File dataFilesBackupDir = new File(pending.getParentFile(), dataFilesName);
            final Properties backupProperties = new Properties();
            FileInputStream inStream = new FileInputStream(new File(dataFilesBackupDir, "backup-" + prefix + ".properties"));
            backupProperties.load(inStream);
            IOUtils.closeQuietly(inStream);
            // maybe one of those bundles has data directory to restore?
            for (Bundle b : systemContext.getBundles()) {
                if (b.getSymbolicName() != null) {
                    String key = String.format("%s$$%s", stripSymbolicName(b.getSymbolicName()), b.getVersion().toString());
                    if (backupProperties.containsKey(key)) {
                        String backupDirName = backupProperties.getProperty(key);
                        File backupDir = new File(dataFilesBackupDir, prefix + "/" + backupDirName + "/data");
                        restoreDataDirectory(dataCache, b, backupDir);
                        // we no longer want to restore this dir
                        backupProperties.remove(key);
                    }
                }
            }
            // 2. We can however have more bundle data backups - we'll restore them after each bundle
            // is INSTALLED and we'll use listener for this
            BundleListener bundleListener = new SynchronousBundleListener() {

                @Override
                public void bundleChanged(BundleEvent event) {
                    Bundle b = event.getBundle();
                    if (event.getType() == BundleEvent.INSTALLED && b.getSymbolicName() != null) {
                        String key = String.format("%s$$%s", stripSymbolicName(b.getSymbolicName()), b.getVersion().toString());
                        if (backupProperties.containsKey(key)) {
                            String backupDirName = backupProperties.getProperty(key);
                            File backupDir = new File(dataFilesBackupDir, prefix + "/" + backupDirName + "/data");
                            restoreDataDirectory(dataCache, b, backupDir);
                        }
                    }
                }
            };
            systemContext.addBundleListener(bundleListener);
            pendingPatchesListeners.put(patchData.getId(), bundleListener);
        } catch (Exception e) {
            Activator.log(LogService.LOG_ERROR, null, e.getMessage(), e, true);
        }
    }
}
Also used : PatchData(io.fabric8.patch.management.PatchData) Bundle(org.osgi.framework.Bundle) Properties(java.util.Properties) PatchDetailsRequest(io.fabric8.patch.management.PatchDetailsRequest) FileInputStream(java.io.FileInputStream) PatchException(io.fabric8.patch.management.PatchException) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) BundleEvent(org.osgi.framework.BundleEvent) BundleListener(org.osgi.framework.BundleListener) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener) FileFilter(java.io.FileFilter) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) ManagedPatch(io.fabric8.patch.management.ManagedPatch) Patch(io.fabric8.patch.management.Patch) Pending(io.fabric8.patch.management.Pending) SynchronousBundleListener(org.osgi.framework.SynchronousBundleListener)

Example 4 with Pending

use of io.fabric8.patch.management.Pending in project wildfly-camel by wildfly-extras.

the class KubernetesIntegrationTest method testKubernetesProducer.

@Test
public void testKubernetesProducer() throws Exception {
    String kubernetesProducerURI = String.format("kubernetes:%s?category=pods&operation=createPod", getKubernetesMaster());
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:start").to(kubernetesProducerURI);
        }
    });
    ProducerTemplate template = camelctx.createProducerTemplate();
    String podName = POD_NAME + "-producer";
    camelctx.start();
    KubernetesEndpoint kubernetesEndpoint = camelctx.getEndpoint(kubernetesProducerURI, KubernetesEndpoint.class);
    String kubernetesNamespace = getNamespace(kubernetesEndpoint.getKubernetesClient());
    try {
        Map<String, Object> headers = new HashMap<>();
        headers.put(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, kubernetesNamespace);
        headers.put(KubernetesConstants.KUBERNETES_POD_NAME, podName);
        headers.put(KubernetesConstants.KUBERNETES_POD_SPEC, createPodSpec());
        Pod pod = template.requestBodyAndHeaders("direct:start", null, headers, Pod.class);
        Assert.assertNotNull("Expected pod to be not null", pod);
        Assert.assertEquals("Pending", pod.getStatus().getPhase());
    } finally {
        // Clean up
        Map<String, Object> headers = new HashMap<>();
        headers.put(KubernetesConstants.KUBERNETES_NAMESPACE_NAME, kubernetesNamespace);
        headers.put(KubernetesConstants.KUBERNETES_POD_NAME, podName);
        template.requestBodyAndHeaders("kubernetes:" + getKubernetesMaster() + "?category=pods&operation=deletePod", null, headers);
        camelctx.stop();
    }
}
Also used : DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) CamelContext(org.apache.camel.CamelContext) ProducerTemplate(org.apache.camel.ProducerTemplate) KubernetesEndpoint(org.apache.camel.component.kubernetes.KubernetesEndpoint) RouteBuilder(org.apache.camel.builder.RouteBuilder) Pod(io.fabric8.kubernetes.api.model.Pod) HashMap(java.util.HashMap) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) IOException(java.io.IOException) Test(org.junit.Test)

Example 5 with Pending

use of io.fabric8.patch.management.Pending in project ephemerals by LivePersonInc.

the class KubernetesDeploymentStatusWaiter method getDeploymentStatus.

@Override
public DeploymentStatus getDeploymentStatus() {
    PodList list = client.pods().withLabel(KubernetesDeploymentHandler.DEPLOYMENT_LABEL_KEY, deployment.getId()).list();
    Pod pod = list.getItems().get(0);
    ContainerStatus containerStatus = pod.getStatus().getContainerStatuses().get(0);
    switch(pod.getStatus().getPhase()) {
        case "Pending":
            return DeploymentStatus.IN_PROGRESS;
        case "Running":
            if (containerStatus.getReady()) {
                return DeploymentStatus.FINISHED;
            } else // Out of memory / CPU issues
            if (containerStatus.getRestartCount() > deployment.getDeploymentConfiguration().getMaxDeploymentRetries() && (containerStatus.getLastState().getTerminated().getExitCode() == 137 || containerStatus.getLastState().getTerminated().getExitCode() == 143)) {
                return DeploymentStatus.FAILED;
            } else // General error
            if (containerStatus.getRestartCount() > deployment.getDeploymentConfiguration().getMaxDeploymentRetries() && containerStatus.getLastState().getTerminated().getReason().contains("Error") && containerStatus.getState().getTerminated().getReason().contains("Error") && containerStatus.getLastState().getTerminated().getExitCode().equals(containerStatus.getState().getTerminated().getExitCode())) {
                return DeploymentStatus.FAILED;
            } else // CrashLoopBackOff errors
            if (containerStatus.getRestartCount() > deployment.getDeploymentConfiguration().getMaxDeploymentRetries() && containerStatus.getLastState().getTerminated() != null && containerStatus.getState().getWaiting().getReason().contains("CrashLoopBackOff")) {
                return DeploymentStatus.FAILED;
            } else // Partial deployment if it was terminated and not restarted
            if (containerStatus.getRestartCount() == 0 && containerStatus.getState().getTerminated() != null) {
                return DeploymentStatus.PARTIALLY;
            } else {
                return DeploymentStatus.IN_PROGRESS;
            }
        case "Failed":
            return DeploymentStatus.FAILED;
        case "Unknown":
            return DeploymentStatus.UNKNOWN;
        default:
            return DeploymentStatus.UNKNOWN;
    }
}
Also used : PodList(io.fabric8.kubernetes.api.model.PodList) ContainerStatus(io.fabric8.kubernetes.api.model.ContainerStatus) Pod(io.fabric8.kubernetes.api.model.Pod)

Aggregations

IOException (java.io.IOException)8 File (java.io.File)5 Pod (io.fabric8.kubernetes.api.model.Pod)4 PodList (io.fabric8.kubernetes.api.model.PodList)3 FileFilter (java.io.FileFilter)3 FileInputStream (java.io.FileInputStream)3 Bundle (org.osgi.framework.Bundle)3 Profile (io.fabric8.api.Profile)2 Watch (io.fabric8.kubernetes.client.Watch)2 BundleUpdate (io.fabric8.patch.management.BundleUpdate)2 Patch (io.fabric8.patch.management.Patch)2 PatchData (io.fabric8.patch.management.PatchData)2 PatchDetailsRequest (io.fabric8.patch.management.PatchDetailsRequest)2 PatchException (io.fabric8.patch.management.PatchException)2 Pending (io.fabric8.patch.management.Pending)2 HashMap (java.util.HashMap)2 Hashtable (java.util.Hashtable)2 Properties (java.util.Properties)2 Test (org.junit.Test)2 BundleException (org.osgi.framework.BundleException)2