Search in sources :

Example 81 with Check

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

the class FabricServiceImpl method createContainers.

@Override
public CreateContainerMetadata[] createContainers(CreateContainerOptions options, CreationStateListener listener) {
    assertValid();
    try {
        final ContainerProvider provider = getProvider(options.getProviderType());
        if (provider == null) {
            throw new FabricException("Unable to find a container provider supporting '" + options.getProviderType() + "'");
        }
        if (!provider.isValidProvider()) {
            throw new FabricException("The provider '" + options.getProviderType() + "' is not valid in current environment");
        }
        String originalName = options.getName();
        if (originalName == null || originalName.length() == 0) {
            throw new FabricException("A name must be specified when creating containers");
        }
        // Only allow containers with valid names to get created.
        FabricValidations.validateContainerName(originalName);
        if (listener == null) {
            listener = new NullCreationStateListener();
        }
        validateProfileDependencies(options);
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        Map optionsMap = mapper.readValue(mapper.writeValueAsString(options), Map.class);
        String versionId = options.getVersion() != null ? options.getVersion() : dataStore.get().getDefaultVersion();
        Set<String> profileIds = options.getProfiles();
        if (profileIds == null || profileIds.isEmpty()) {
            profileIds = new LinkedHashSet<String>();
            profileIds.add("default");
        }
        optionsMap.put("version", versionId);
        optionsMap.put("profiles", profileIds);
        optionsMap.put("number", 0);
        // assign parent resolver if it's a child container, else assign global resolver policy
        if (bootstrapConfig != null) {
            String configuredGlobalResolver = bootstrapConfig.getGlobalResolver();
            if (!Strings.isNullOrEmpty(configuredGlobalResolver)) {
                optionsMap.put("globalResolver", configuredGlobalResolver);
                if (optionsMap.get("resolver") == null) {
                    if (optionsMap.get("parent") == null) {
                        optionsMap.put("resolver", configuredGlobalResolver);
                    }
                }
            }
        }
        final List<CreateContainerMetadata> metadatas = new CopyOnWriteArrayList<CreateContainerMetadata>();
        int orgNumber = options.getNumber();
        int number = Math.max(orgNumber, 1);
        if (orgNumber > 1) {
            originalName = originalName + "1";
        }
        final CountDownLatch latch = new CountDownLatch(number);
        Set<String> ignoreContainerNames = new HashSet<>();
        Container[] containers = getContainers();
        // check that there is no container with the given name
        for (Container container : containers) {
            if (container.getId().equals(options.getName())) {
                throw new IllegalArgumentException("A container with name " + options.getName() + " already exists.");
            }
        }
        for (int i = 1; i <= number; i++) {
            NameValidator validator = Containers.createNameValidator(containers, ignoreContainerNames);
            final String containerName = Containers.createUniqueContainerName(containers, originalName, validator);
            ignoreContainerNames.add(containerName);
            optionsMap.put("name", containerName);
            // Check if datastore configuration has been specified and fallback to current container settings.
            if (!hasValidDataStoreProperties(optionsMap)) {
                optionsMap.put("dataStoreProperties", profileRegistry.get().getDataStoreProperties());
            }
            Class cl = options.getClass().getClassLoader().loadClass(options.getClass().getName() + "$Builder");
            CreateContainerBasicOptions.Builder builder = (CreateContainerBasicOptions.Builder) mapper.readValue(mapper.writeValueAsString(optionsMap), cl);
            // We always want to pass the obfuscated version of the password to the container provider.
            builder = (CreateContainerBasicOptions.Builder) builder.zookeeperPassword(PasswordEncoder.encode(getZookeeperPassword()));
            final CreateContainerOptions containerOptions = builder.build();
            final CreationStateListener containerListener = listener;
            final FabricService fabricService = this;
            new Thread("Creating container " + containerName) {

                public void run() {
                    try {
                        if (dataStore.get().hasContainer(containerName)) {
                            CreateContainerBasicMetadata metadata = new CreateContainerBasicMetadata();
                            metadata.setContainerName(containerName);
                            metadata.setCreateOptions(containerOptions);
                            metadata.setFailure(new IllegalArgumentException("A container with name " + containerName + " already exists."));
                            metadatas.add(metadata);
                            return;
                        }
                        dataStore.get().createContainerConfig(containerOptions);
                        CreateContainerMetadata metadata = provider.create(containerOptions, containerListener);
                        if (metadata.isSuccess()) {
                            Container parent = containerOptions.getParent() != null ? getContainer(containerOptions.getParent()) : null;
                            // TODO: We need to make sure that this entries are somehow added even to ensemble servers.
                            if (!containerOptions.isEnsembleServer()) {
                                dataStore.get().createContainerConfig(metadata);
                            }
                            ContainerImpl container = new ContainerImpl(parent, metadata.getContainerName(), FabricServiceImpl.this);
                            metadata.setContainer(container);
                            LOGGER.info("The container " + metadata.getContainerName() + " has been successfully created");
                        } else {
                            LOGGER.warn("The creation of the container " + metadata.getContainerName() + " has failed", metadata.getFailure());
                            dataStore.get().deleteContainer(fabricService, containerOptions.getName());
                        }
                        metadatas.add(metadata);
                    } catch (Throwable t) {
                        CreateContainerBasicMetadata metadata = new CreateContainerBasicMetadata();
                        metadata.setContainerName(containerName);
                        metadata.setCreateOptions(containerOptions);
                        metadata.setFailure(t);
                        metadatas.add(metadata);
                        dataStore.get().deleteContainer(fabricService, containerOptions.getName());
                    } finally {
                        latch.countDown();
                    }
                }
            }.start();
        }
        if (!latch.await(30, TimeUnit.MINUTES)) {
            throw new FabricException("Timeout waiting for container creation");
        }
        return metadatas.toArray(new CreateContainerMetadata[metadatas.size()]);
    } catch (Exception e) {
        LOGGER.error("Failed to create containers " + e, e);
        throw FabricException.launderThrowable(e);
    }
}
Also used : ContainerProvider(io.fabric8.api.ContainerProvider) NullCreationStateListener(io.fabric8.api.NullCreationStateListener) NameValidator(io.fabric8.api.NameValidator) ProfileBuilder(io.fabric8.api.ProfileBuilder) FabricException(io.fabric8.api.FabricException) CreateContainerOptions(io.fabric8.api.CreateContainerOptions) Container(io.fabric8.api.Container) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) CreateContainerMetadata(io.fabric8.api.CreateContainerMetadata) CountDownLatch(java.util.concurrent.CountDownLatch) CreateContainerBasicMetadata(io.fabric8.api.CreateContainerBasicMetadata) ProfileDependencyException(io.fabric8.api.ProfileDependencyException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException) NullCreationStateListener(io.fabric8.api.NullCreationStateListener) CreationStateListener(io.fabric8.api.CreationStateListener) FabricService(io.fabric8.api.FabricService) ContainerImpl(io.fabric8.internal.ContainerImpl) CreateContainerBasicOptions(io.fabric8.api.CreateContainerBasicOptions) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) TreeMap(java.util.TreeMap) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 82 with Check

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

the class MQManager method addMasterSlaveStatus.

protected void addMasterSlaveStatus(List<MQBrokerStatusDTO> answer) throws Exception {
    Map<String, Map<String, MQBrokerStatusDTO>> groupMap = new HashMap<String, Map<String, MQBrokerStatusDTO>>();
    for (MQBrokerStatusDTO status : answer) {
        String key = status.getGroup();
        Map<String, MQBrokerStatusDTO> list = groupMap.get(key);
        if (list == null) {
            list = new HashMap<String, MQBrokerStatusDTO>();
            groupMap.put(key, list);
        }
        String statusPath = String.format("%s/%s", status.getContainer(), status.getBrokerName());
        list.put(statusPath, status);
    }
    CuratorFramework curator = getCurator();
    // now lets check the cluster status for each group
    Set<Map.Entry<String, Map<String, MQBrokerStatusDTO>>> entries = groupMap.entrySet();
    for (Map.Entry<String, Map<String, MQBrokerStatusDTO>> entry : entries) {
        String group = entry.getKey();
        Map<String, MQBrokerStatusDTO> containerMap = entry.getValue();
        String groupPath = ZkPath.MQ_CLUSTER.getPath(group);
        List<String> children = getChildrenSafe(curator, groupPath);
        for (String child : children) {
            String childPath = groupPath + "/" + child;
            byte[] data = curator.getData().forPath(childPath);
            if (data != null && data.length > 0) {
                String text = new String(data).trim();
                if (!text.isEmpty()) {
                    ObjectMapper mapper = new ObjectMapper();
                    Map<String, Object> map = mapper.readValue(data, HashMap.class);
                    String id = stringValue(map, "id", "container");
                    if (id != null) {
                        String container = stringValue(map, "container", "agent");
                        String statusPath = String.format("%s/%s", container, id);
                        MQBrokerStatusDTO containerStatus = containerMap.get(statusPath);
                        if (containerStatus != null) {
                            Boolean master = null;
                            List services = listValue(map, "services");
                            if (services != null) {
                                if (!services.isEmpty()) {
                                    List<String> serviceTexts = new ArrayList<String>();
                                    for (Object service : services) {
                                        String serviceText = getSubstitutedData(curator, service.toString());
                                        if (Strings.isNotBlank(serviceText)) {
                                            serviceTexts.add(serviceText);
                                        }
                                        containerStatus.setServices(serviceTexts);
                                    }
                                    master = Boolean.TRUE;
                                } else {
                                    master = Boolean.FALSE;
                                }
                            } else {
                                master = Boolean.FALSE;
                            }
                            containerStatus.setMaster(master);
                        }
                    }
                }
            }
        }
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MQBrokerStatusDTO(io.fabric8.api.jmx.MQBrokerStatusDTO) CuratorFramework(org.apache.curator.framework.CuratorFramework) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) HashMap(java.util.HashMap) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 83 with Check

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

the class PatchServiceImplTest method testCheckRequirementsMissingPatches.

@Test
public void testCheckRequirementsMissingPatches() throws IOException {
    PatchServiceImpl.PatchDescriptor descriptor = getPatchDescriptor("test4.patch");
    Version version = buildVersion("1.1").withProfiles("karaf", "default", "patch-prereq4a", "patch-somethingelse").done();
    try {
        PatchServiceImpl.checkRequirements(version, descriptor);
        fail("Patch should not have passed requirements check - required patch is missing");
    } catch (PatchException e) {
        assertTrue(e.getMessage().toLowerCase().contains("required patch 'prereq4b' is missing"));
    }
}
Also used : Version(io.fabric8.api.Version) PatchException(io.fabric8.api.PatchException) Test(org.junit.Test)

Example 84 with Check

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

the class ResolverTest method testChildContainerResolver.

@Test
public void testChildContainerResolver() throws Exception {
    System.out.println(CommandSupport.executeCommand("fabric:create --force --clean -n --wait-for-provisioning"));
    // System.out.println(executeCommand("shell:info"));
    // System.out.println(executeCommand("fabric:info"));
    // System.out.println(executeCommand("fabric:profile-list"));
    BundleContext moduleContext = ServiceLocator.getSystemContext();
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(moduleContext, FabricService.class);
    try {
        FabricService fabricService = fabricProxy.getService();
        CuratorFramework curator = fabricService.adapt(CuratorFramework.class);
        Set<Container> containers = ContainerBuilder.create(1, 1).withName("basic.cntF").withProfiles("default").assertProvisioningResult().build(fabricService);
        try {
            Container cntF = containers.iterator().next();
            Assert.assertEquals("localhostname", getSubstitutedPath(curator, ZkPath.CONTAINER_RESOLVER.getPath(cntF.getId())));
            String sshUrlWithLocalhostResolver = cntF.getSshUrl();
            CommandSupport.executeCommand("fabric:container-resolver-set --container " + cntF.getId() + " localip");
            Assert.assertEquals("localip", getSubstitutedPath(curator, ZkPath.CONTAINER_RESOLVER.getPath(cntF.getId())));
            String sshUrlWithLocalIpResolver = cntF.getSshUrl();
            // Check that the SSH URL has been updated.
            System.out.println("SSH URL with " + sshUrlWithLocalhostResolver + " resolver: localhostname");
            System.out.println("SSH URL with " + sshUrlWithLocalIpResolver + " resolver: localip");
            Assert.assertNotSame(sshUrlWithLocalhostResolver, sshUrlWithLocalIpResolver);
            setData(curator, ZkPath.CONTAINER_PUBLIC_IP.getPath(cntF.getId()), "my.public.ip.address");
            CommandSupport.executeCommand("fabric:container-resolver-set --container " + cntF.getId() + " publicip");
            Assert.assertEquals("publicip", getSubstitutedPath(curator, ZkPath.CONTAINER_RESOLVER.getPath(cntF.getId())));
            String sshUrlWithPublicIpResolver = cntF.getSshUrl();
            System.out.println("SSH URL with " + sshUrlWithPublicIpResolver + " resolver: publicip");
            Assert.assertNotNull(sshUrlWithPublicIpResolver);
            Assert.assertTrue(sshUrlWithPublicIpResolver.startsWith("my.public.ip.address"));
            setData(curator, ZkPath.CONTAINER_MANUAL_IP.getPath(cntF.getId()), "my.manual.ip.address");
            CommandSupport.executeCommand("fabric:container-resolver-set --container " + cntF.getId() + " manualip");
            Assert.assertEquals("manualip", getSubstitutedPath(curator, ZkPath.CONTAINER_RESOLVER.getPath(cntF.getId())));
            String sshUrlWithManualIpResolver = cntF.getSshUrl();
            System.out.println("SSH URL with " + sshUrlWithManualIpResolver + " resolver: manualip");
            Assert.assertNotNull(sshUrlWithManualIpResolver);
            Assert.assertTrue(sshUrlWithManualIpResolver.startsWith("my.manual.ip.address"));
        } finally {
            ContainerBuilder.destroy(fabricService, containers);
        }
    } finally {
        fabricProxy.close();
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) Container(io.fabric8.api.Container) FabricService(io.fabric8.api.FabricService) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

Example 85 with Check

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

the class ResolverTest method testRootContainerResolver.

@Test
public void testRootContainerResolver() throws Exception {
    System.out.println(CommandSupport.executeCommand("fabric:create --force --clean -n --wait-for-provisioning"));
    // System.out.println(executeCommand("shell:info"));
    // System.out.println(executeCommand("fabric:info"));
    // System.out.println(executeCommand("fabric:profile-list"));
    BundleContext moduleContext = ServiceLocator.getSystemContext();
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(moduleContext, FabricService.class);
    try {
        FabricService fabricService = fabricProxy.getService();
        Container current = fabricService.getCurrentContainer();
        Assert.assertEquals("localhostname", current.getResolver());
        String sshUrlWithLocalhostResolver = current.getSshUrl();
        System.out.println(CommandSupport.executeCommand("fabric:container-resolver-set --container root localip"));
        Assert.assertEquals("localip", current.getResolver());
        String sshUrlWithLocalIpResolver = current.getSshUrl();
        // Check that the SSH URL has been updated.
        System.out.println("SSH URL with " + sshUrlWithLocalhostResolver + " resolver: localhostname");
        System.out.println("SSH URL with " + sshUrlWithLocalIpResolver + " resolver: localip");
        Assert.assertNotSame(sshUrlWithLocalhostResolver, sshUrlWithLocalIpResolver);
    } finally {
        fabricProxy.close();
    }
}
Also used : Container(io.fabric8.api.Container) FabricService(io.fabric8.api.FabricService) BundleContext(org.osgi.framework.BundleContext) Test(org.junit.Test)

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