Search in sources :

Example 21 with Check

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

the class PatchServiceImplTest method testCheckRequirementsMultiplePatches.

@Test
public void testCheckRequirementsMultiplePatches() throws IOException {
    Collection<PatchServiceImpl.PatchDescriptor> patches = new LinkedList<PatchServiceImpl.PatchDescriptor>();
    patches.add(getPatchDescriptor("test3.patch"));
    patches.add(getPatchDescriptor("test4.patch"));
    Version version = buildVersion("1.1").withProfiles("karaf", "default", "patch-prereq4a", "patch-prereq3").done();
    try {
        PatchServiceImpl.checkRequirements(version, patches);
        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) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 22 with Check

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

the class MQServiceImpl method createOrUpdateMQProfile.

@Override
public Profile createOrUpdateMQProfile(String versionId, String profileId, String brokerName, Map<String, String> configs, boolean replicated) {
    Version version = profileService.getRequiredVersion(versionId);
    String parentProfileName = null;
    if (configs != null && configs.containsKey("parent")) {
        parentProfileName = configs.remove("parent");
    }
    if (Strings.isNullOrBlank(parentProfileName)) {
        parentProfileName = replicated ? MQ_PROFILE_REPLICATED : MQ_PROFILE_BASE;
    }
    Profile parentProfile = version.getRequiredProfile(parentProfileName);
    if (brokerName == null || profileId == null) {
        return parentProfile;
    }
    String pidName = getBrokerPID(brokerName);
    // lets check we have a config value
    ProfileBuilder builder;
    Profile overlay;
    // create a profile if it doesn't exist
    Map<String, String> config = null;
    boolean create = !version.hasProfile(profileId);
    if (create) {
        builder = ProfileBuilder.Factory.create(versionId, profileId);
        if (parentProfile != null) {
            builder.addParent(parentProfile.getId());
        }
        overlay = profileService.getOverlayProfile(parentProfile);
    } else {
        Profile profile = version.getRequiredProfile(profileId);
        builder = ProfileBuilder.Factory.createFrom(profile);
        config = builder.getConfiguration(pidName);
        overlay = profileService.getOverlayProfile(profile);
    }
    Map<String, String> parentProfileConfig = ProfileBuilder.Factory.createFrom(overlay).getConfiguration(MQ_PID_TEMPLATE);
    if (config == null) {
        config = parentProfileConfig;
    }
    if (configs != null && "true".equals(configs.get("ssl"))) {
        // Only generate the keystore file if it does not exist.
        // [TOOD] Fix direct data access! This should be part of the ProfileBuilder
        byte[] keystore = overlay.getFileConfiguration("keystore.jks");
        if (keystore == null) {
            try {
                String host = configs.get("keystore.cn");
                if (host == null) {
                    host = configs.get(GROUP);
                    if (host == null) {
                        host = "localhost";
                    }
                    configs.put("keystore.cn", host);
                }
                String password = configs.get("keystore.password");
                if (password == null) {
                    password = generatePassword(8);
                    configs.put("keystore.password", password);
                }
                File keystoreFile = io.fabric8.utils.Files.createTempFile(runtimeProperties.getDataPath());
                keystoreFile.delete();
                LOG.info("Generating ssl keystore...");
                int rc = system("keytool", "-genkey", "-storetype", "JKS", "-storepass", password, "-keystore", keystoreFile.getCanonicalPath(), "-keypass", password, "-alias", host, "-keyalg", "RSA", "-keysize", "4096", "-dname", String.format("cn=%s", host), "-validity", "3650");
                if (rc != 0) {
                    throw new IOException("keytool failed with exit code: " + rc);
                }
                keystore = Files.readBytes(keystoreFile);
                keystoreFile.delete();
                LOG.info("Keystore generated");
                builder.addFileConfiguration("keystore.jks", keystore);
                configs.put("keystore.file", "profile:keystore.jks");
            } catch (IOException e) {
                LOG.error("Failed to generate keystore.jks: " + e.getMessage(), e);
                throw new RuntimeException(e.getMessage(), e);
            }
        }
        // [TOOD] Fix direct data access! This should be part of the ProfileBuilder
        byte[] truststore = overlay.getFileConfiguration("truststore.jks");
        if (truststore == null && configs.get("keystore.password") != null) {
            try {
                String password = configs.get("truststore.password");
                if (password == null) {
                    password = configs.get("keystore.password");
                    configs.put("truststore.password", password);
                }
                File keystoreFile = io.fabric8.utils.Files.createTempFile(runtimeProperties.getDataPath());
                Files.writeToFile(keystoreFile, keystore);
                File certFile = io.fabric8.utils.Files.createTempFile(runtimeProperties.getDataPath());
                certFile.delete();
                LOG.info("Exporting broker certificate to create truststore.jks");
                int rc = system("keytool", "-exportcert", "-rfc", "-keystore", keystoreFile.getCanonicalPath(), "-storepass", configs.get("keystore.password"), "-alias", configs.get("keystore.cn"), "--file", certFile.getCanonicalPath());
                keystoreFile.delete();
                if (rc != 0) {
                    throw new IOException("keytool failed with exit code: " + rc);
                }
                LOG.info("Creating truststore.jks");
                File truststoreFile = io.fabric8.utils.Files.createTempFile(runtimeProperties.getDataPath());
                truststoreFile.delete();
                rc = system("keytool", "-importcert", "-noprompt", "-keystore", truststoreFile.getCanonicalPath(), "-storepass", password, "--file", certFile.getCanonicalPath());
                certFile.delete();
                if (rc != 0) {
                    throw new IOException("keytool failed with exit code: " + rc);
                }
                truststore = Files.readBytes(truststoreFile);
                truststoreFile.delete();
                builder.addFileConfiguration("truststore.jks", truststore);
                configs.put("truststore.file", "profile:truststore.jks");
            } catch (IOException e) {
                LOG.error("Failed to generate truststore.jks due: " + e.getMessage(), e);
                throw new RuntimeException(e.getMessage(), e);
            }
        }
    }
    config.put("broker-name", brokerName);
    if (configs != null) {
        config.putAll(configs);
    }
    // lets check we've a bunch of config values inherited from the template
    String[] propertiesToDefault = { CONFIG_URL, STANDBY_POOL, CONNECTORS };
    for (String key : propertiesToDefault) {
        if (config.get(key) == null) {
            String defaultValue = parentProfileConfig.get(key);
            if (Strings.isNotBlank(defaultValue)) {
                config.put(key, defaultValue);
            }
        }
    }
    // config map is not from "official" profile, so it doesn't have to use felix' Properties class
    builder.addConfiguration(pidName, config);
    Profile profile = builder.getProfile();
    return create ? profileService.createProfile(profile) : profileService.updateProfile(profile);
}
Also used : Version(io.fabric8.api.Version) IOException(java.io.IOException) ProfileBuilder(io.fabric8.api.ProfileBuilder) File(java.io.File) Profile(io.fabric8.api.Profile)

Example 23 with Check

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

the class ProfileMetadata method findMetadataForProfile.

protected void findMetadataForProfile(String versionId, String profileId, MetadataHandler handler) throws Exception {
    FabricService service = fabricService.get();
    Objects.notNull(service, "FabricService");
    ProfileService profileService = service.adapt(ProfileService.class);
    Objects.notNull(profileService, "ProfileService");
    DownloadManager downloadManager = DownloadManagers.createDownloadManager(service, executorService);
    Objects.notNull(downloadManager, "DownloadManager");
    Profile immediateProfile = profileService.getProfile(versionId, profileId);
    Objects.notNull(immediateProfile, "Profile for versionId: " + versionId + ", profileId: " + profileId);
    Profile profile = profileService.getOverlayProfile(immediateProfile);
    Set<String> pids = new HashSet<>();
    Map<String, File> fileMap = AgentUtils.downloadProfileArtifacts(service, downloadManager, profile);
    Set<Map.Entry<String, File>> entries = fileMap.entrySet();
    for (Map.Entry<String, File> entry : entries) {
        String uri = entry.getKey();
        File file = entry.getValue();
        if (!file.exists() || !file.isFile()) {
            LOG.warn("File " + file + " is not an existing file for " + uri + ". Ignoring");
            continue;
        }
        addMetaTypeInformation(handler, uri, file);
        pids.add(uri);
    }
    // lets check if the MetaType folder exists
    if (metaTypeFolder != null && metaTypeFolder.exists() && metaTypeFolder.isDirectory()) {
        Set<String> configurationFileNames = profile.getConfigurationFileNames();
        for (String configName : configurationFileNames) {
            if (configName.endsWith(PROPERTIES_SUFFIX) && configName.indexOf('/') < 0) {
                String pid = configName.substring(0, configName.length() - PROPERTIES_SUFFIX.length());
                addMetaTypeInformation(pids, handler, pid);
                String factoryPid = getFactoryPid(pid);
                addMetaTypeInformation(pids, handler, factoryPid);
            }
        }
    }
}
Also used : DownloadManager(io.fabric8.agent.download.DownloadManager) Profile(io.fabric8.api.Profile) JarEntry(java.util.jar.JarEntry) ProfileService(io.fabric8.api.ProfileService) FabricService(io.fabric8.api.FabricService) JarFile(java.util.jar.JarFile) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 24 with Check

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

the class ExampleCamelClusterTest method testRegistryEntries.

@Test
public void testRegistryEntries() throws Exception {
    System.out.println(executeCommand("fabric:create -n --wait-for-provisioning root"));
    // System.out.println(executeCommand("shell:info"));
    // System.out.println(executeCommand("fabric:info"));
    // System.out.println(executeCommand("fabric:profile-list"));
    ServiceProxy<FabricService> fabricProxy = ServiceProxy.createServiceProxy(bundleContext, FabricService.class);
    try {
        FabricService fabricService = fabricProxy.getService();
        CuratorFramework curator = fabricService.adapt(CuratorFramework.class);
        Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 3).withName("fabric-camel").assertProvisioningResult().build();
        try {
            // We will use the first container as a client and the rest as servers.
            LinkedList<Container> containerList = new LinkedList<Container>(containers);
            Container client = containerList.removeLast();
            LinkedList<Container> servers = new LinkedList<Container>(containerList);
            for (Container c : servers) {
                Profile p1 = c.getVersion().getRequiredProfile("feature-camel");
                Profile p2 = c.getVersion().getRequiredProfile("example-camel-cluster-cluster.server");
                c.setProfiles(new Profile[] { p1, p2 });
            }
            Provision.provisioningSuccess(servers, PROVISION_TIMEOUT);
            Profile p1 = client.getVersion().getRequiredProfile("feature-camel");
            Profile p2 = client.getVersion().getRequiredProfile("example-camel-cluster-cluster.client");
            client.setProfiles(new Profile[] { p1, p2 });
            Provision.provisioningSuccess(Arrays.asList(new Container[] { client }), PROVISION_TIMEOUT);
            System.out.println(executeCommand("fabric:container-list"));
            System.out.println(executeCommand("fabric:profile-display --overlay fabric-camel-server"));
            // Check that the entries have been properly propagated.
            Assert.assertNotNull(exists(curator, "/fabric/registry/camel/endpoints"));
            Assert.assertEquals(1, getChildren(curator, "/fabric/registry/camel/endpoints").size());
            Assert.assertTrue(Provision.waitForCondition(Arrays.asList(client), new ContainerCondition() {

                @Override
                public Boolean checkConditionOnContainer(final Container c) {
                    return getCompletedExchangesCount(c) > 0;
                }
            }, 60000L));
            // We want to kill all but one server, so we take out the first and keep it to the end.
            Container lastActiveServerContainer = servers.removeLast();
            for (Container c : servers) {
                try {
                    c.destroy(true);
                } catch (Exception ex) {
                // ignore.
                }
                // Get the number of exchanges completed before we kill the server.
                final int completed = getCompletedExchangesCount(client);
                // Ensure that we still have messages flowing
                Assert.assertTrue(Provision.waitForCondition(Arrays.asList(client), new ContainerCondition() {

                    @Override
                    public Boolean checkConditionOnContainer(final Container c) {
                        return getCompletedExchangesCount(c) > completed + 3;
                    }
                }, 60000L));
            }
            System.out.println(new AnsiString(executeCommand("fabric:container-connect -u admin -p admin " + client.getId() + " camel:route-info fabric-client")).getPlain().toString());
        } finally {
            ContainerBuilder.destroy(containers);
        }
    } finally {
        fabricProxy.close();
    }
}
Also used : AnsiString(org.fusesource.jansi.AnsiString) LinkedList(java.util.LinkedList) Profile(io.fabric8.api.Profile) ContainerCondition(io.fabric8.itests.paxexam.support.ContainerCondition) CuratorFramework(org.apache.curator.framework.CuratorFramework) Container(io.fabric8.api.Container) FabricService(io.fabric8.api.FabricService) ContainerProxy(io.fabric8.itests.paxexam.support.ContainerProxy) Test(org.junit.Test)

Example 25 with Check

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

the class ProxyServlet method executeProxyRequest.

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param proxyDetails
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException            Can be thrown by the {@link HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
    httpMethodProxyRequest.setDoAuthentication(false);
    httpMethodProxyRequest.setFollowRedirects(false);
    // Create a default HttpClient
    HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest);
    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES && /* 300 */
    intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED) /* 304 */
    {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(stringLocation.replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName));
        return;
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }
    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);
    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (!ProxySupport.isHopByHopHeader(header.getName())) {
            if (ProxySupport.isSetCookieHeader(header)) {
                HttpProxyRule proxyRule = proxyDetails.getProxyRule();
                String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain());
                httpServletResponse.setHeader(header.getName(), setCookie);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        }
    }
    // check if we got data, that is either the Content-Length > 0
    // or the response code != 204
    int code = httpMethodProxyRequest.getStatusCode();
    boolean noData = code == HttpStatus.SC_NO_CONTENT;
    if (!noData) {
        String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME);
        if (length != null && "0".equals(length.trim())) {
            noData = true;
        }
    }
    LOG.trace("Response has data? {}", !noData);
    if (!noData) {
        // Send the content to the client
        InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        int intNextByte;
        while ((intNextByte = bufferedInputStream.read()) != -1) {
            outputStreamClientResponse.write(intNextByte);
        }
    }
}
Also used : ServletException(javax.servlet.ServletException) Header(org.apache.commons.httpclient.Header) BufferedInputStream(java.io.BufferedInputStream) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) OutputStream(java.io.OutputStream) HttpProxyRule(io.fabric8.gateway.model.HttpProxyRule)

Aggregations

Test (org.junit.Test)35 IOException (java.io.IOException)21 File (java.io.File)17 ArrayList (java.util.ArrayList)16 HashMap (java.util.HashMap)14 FabricService (io.fabric8.api.FabricService)11 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)11 Container (io.fabric8.api.Container)9 PatchException (io.fabric8.patch.management.PatchException)9 Expectations (mockit.Expectations)9 Profile (io.fabric8.api.Profile)8 Map (java.util.Map)7 TreeMap (java.util.TreeMap)7 Version (io.fabric8.api.Version)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 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)5 Patch (io.fabric8.patch.management.Patch)5