Search in sources :

Example 51 with Server

use of io.fabric8.insight.metrics.model.Server in project fabric8 by jboss-fuse.

the class DataStoreBootstrapTemplate method doWith.

@Override
public void doWith(ProfileRegistry profileRegistry, DataStore dataStore) throws Exception {
    String versionId = options.getVersion();
    int minimumPort = options.getMinimumPort();
    int maximumPort = options.getMaximumPort();
    String zooKeeperServerHost = options.getBindAddress();
    int zooKeeperServerPort = options.getZooKeeperServerPort();
    int zooKeeperServerConnectionPort = options.getZooKeeperServerConnectionPort();
    int mappedPort = Ports.mapPortToRange(zooKeeperServerPort, minimumPort, maximumPort);
    CuratorFramework curator = null;
    try {
        curator = createCuratorFramework(connectionUrl, options);
        curator.start();
        curator.getZookeeperClient().blockUntilConnectedOrTimedOut();
        LockHandle writeLock = profileRegistry.aquireWriteLock();
        try {
            // Make the import path absolute
            File importPath = new File(options.getImportPath());
            if (!importPath.isAbsolute()) {
                importPath = new File(homeDir, options.getImportPath());
            }
            // Import data into the DataStore
            if (options.isAutoImportEnabled()) {
                if (importPath.isDirectory()) {
                    profileRegistry.importFromFileSystem(importPath.getAbsolutePath());
                } else {
                    LOGGER.warn("Profile import dir does not exist: {}", importPath);
                }
            }
            // set the fabric configuration
            ZooKeeperUtils.setData(curator, ZkPath.CONFIG_DEFAULT_VERSION.getPath(), versionId);
            // Default JAAS config
            Map<String, String> jaasConfig = Collections.singletonMap("encryption.enabled", "${zk:/fabric/authentication/encryption.enabled}");
            // Default Zookeeper config
            Properties zkProps = new Properties();
            zkProps.setProperty("zookeeper.url", "${zk:" + ZkPath.CONFIG_ENSEMBLE_URL.getPath() + "}");
            zkProps.setProperty("zookeeper.password", "${zk:" + ZkPath.CONFIG_ENSEMBLE_PASSWORD.getPath() + "}");
            // Create or update default profile
            Profile defaultProfile = profileRegistry.getProfile(versionId, "default");
            if (defaultProfile == null) {
                ProfileBuilder prfBuilder = ProfileBuilder.Factory.create(versionId, "default");
                prfBuilder.addConfiguration("io.fabric8.jaas", jaasConfig);
                prfBuilder.addFileConfiguration("io.fabric8.zookeeper.properties", DataStoreUtils.toBytes(zkProps));
                Profile profile = prfBuilder.getProfile();
                if (profileRegistry.hasVersion(versionId)) {
                    profileRegistry.createProfile(profile);
                } else {
                    VersionBuilder verBuilder = VersionBuilder.Factory.create(versionId);
                    Version version = verBuilder.addProfile(profile).getVersion();
                    profileRegistry.createVersion(version);
                }
            } else {
                ProfileBuilder builder = ProfileBuilder.Factory.createFrom(defaultProfile);
                // be careful not to mess with existing *.properties files - for better "diffability"
                // during git-based patching
                Map<String, String> existingJaasConfig = builder.getConfiguration("io.fabric8.jaas");
                Map<String, String> existingZkConfig = builder.getConfiguration("io.fabric8.zookeeper");
                existingJaasConfig.putAll(jaasConfig);
                existingZkConfig.put("zookeeper.url", zkProps.getProperty("zookeeper.url"));
                existingZkConfig.put("zookeeper.password", zkProps.getProperty("zookeeper.password"));
                builder.addConfiguration("io.fabric8.jaas", existingJaasConfig);
                builder.addConfiguration("io.fabric8.zookeeper", existingZkConfig);
                profileRegistry.updateProfile(builder.getProfile());
            }
            ZooKeeperUtils.setData(curator, ZkPath.CONFIG_ENSEMBLE_URL.getPath(), "${zk:" + name + "/ip}:" + zooKeeperServerConnectionPort);
            ZooKeeperUtils.setData(curator, ZkPath.CONFIG_ENSEMBLE_PASSWORD.getPath(), PasswordEncoder.encode(options.getZookeeperPassword()));
            // Ensemble properties
            Properties ensembleProps = new Properties();
            ensembleProps.put("tickTime", String.valueOf(options.getZooKeeperServerTickTime()));
            ensembleProps.put("initLimit", String.valueOf(options.getZooKeeperServerInitLimit()));
            ensembleProps.put("syncLimit", String.valueOf(options.getZooKeeperServerSyncLimit()));
            ensembleProps.put("snapRetainCount", String.valueOf(options.getZookeeperSnapRetainCount()));
            ensembleProps.put("purgeInterval", String.valueOf(options.getZookeeperPurgeInterval()));
            ensembleProps.put("dataDir", options.getZooKeeperServerDataDir() + File.separator + "0000");
            loadPropertiesFrom(ensembleProps, importPath + "/fabric/profiles/default.profile/io.fabric8.zookeeper.server.properties");
            // Create ensemble profile
            String profileId = "fabric-ensemble-0000";
            IllegalStateAssertion.assertFalse(profileRegistry.hasProfile(versionId, profileId), "Profile already exists: " + versionId + "/" + profileId);
            ProfileBuilder ensembleProfileBuilder = ProfileBuilder.Factory.create(versionId, profileId);
            ensembleProfileBuilder.addAttribute(Profile.ABSTRACT, "true").addAttribute(Profile.HIDDEN, "true");
            ensembleProfileBuilder.addFileConfiguration("io.fabric8.zookeeper.server-0000.properties", DataStoreUtils.toBytes(ensembleProps));
            String ensembleProfileId = profileRegistry.createProfile(ensembleProfileBuilder.getProfile());
            // Ensemble server properties
            Properties serverProps = new Properties();
            serverProps.put("clientPort", String.valueOf(mappedPort));
            serverProps.put("clientPortAddress", zooKeeperServerHost);
            // Create ensemble server profile
            profileId = "fabric-ensemble-0000-1";
            IllegalStateAssertion.assertFalse(profileRegistry.hasProfile(versionId, profileId), "Profile already exists: " + versionId + "/" + profileId);
            ProfileBuilder serverProfileBuilder = ProfileBuilder.Factory.create(versionId, profileId);
            serverProfileBuilder.addAttribute(Profile.HIDDEN, "true").addAttribute(Profile.PARENTS, ensembleProfileId);
            serverProfileBuilder.addFileConfiguration("io.fabric8.zookeeper.server-0000.properties", DataStoreUtils.toBytes(serverProps));
            profileRegistry.createProfile(serverProfileBuilder.getProfile());
            ZooKeeperUtils.setData(curator, ZkPath.CONFIG_ENSEMBLES.getPath(), "0000");
            ZooKeeperUtils.setData(curator, ZkPath.CONFIG_ENSEMBLE.getPath("0000"), name);
            // configure fabric profile
            Profile fabricProfile = profileRegistry.getProfile(versionId, "fabric");
            if (fabricProfile == null) {
                ProfileBuilder builder = ProfileBuilder.Factory.create(versionId, "fabric");
                Properties agentProps = new Properties();
                agentProps.put("feature.fabric-commands", "fabric-commands");
                builder.addFileConfiguration("io.fabric8.agent.properties", DataStoreUtils.toBytes(agentProps));
                String createdId = profileRegistry.createProfile(builder.getProfile());
                fabricProfile = profileRegistry.getRequiredProfile(versionId, createdId);
            } else {
                ProfileBuilder builder = ProfileBuilder.Factory.createFrom(fabricProfile);
                Map<String, String> agentProps = builder.getConfiguration(Constants.AGENT_PID);
                agentProps.put("feature.fabric-commands", "fabric-commands");
                builder.addConfiguration(Constants.AGENT_PID, agentProps);
                String updatedId = profileRegistry.updateProfile(builder.getProfile());
                fabricProfile = profileRegistry.getRequiredProfile(versionId, updatedId);
            }
        } finally {
            writeLock.unlock();
        }
        ZooKeeperUtils.createDefault(curator, ZkPath.CONFIG_CONTAINER.getPath(name), versionId);
        StringBuilder profilesBuilder = new StringBuilder();
        Set<String> profiles = options.getProfiles();
        profilesBuilder.append("fabric").append(" ").append("fabric-ensemble-0000-1");
        for (String p : profiles) {
            if (!(p.equals("fabric") || p.equals("fabric-ensemble-0000-1"))) {
                profilesBuilder.append(" ").append(p);
            }
        }
        if (!options.isAgentEnabled()) {
            profilesBuilder.append(" ").append("unmanaged");
        }
        ZooKeeperUtils.createDefault(curator, ZkPath.CONFIG_VERSIONS_CONTAINER.getPath(versionId, name), profilesBuilder.toString());
        // outside of the profile storage area, so we'll keep these in zk
        EncryptionSupport encryption = addUsersToZookeeper(curator, options.getUsers());
        ZooKeeperUtils.createDefault(curator, "/fabric/authentication/encryption.enabled", Boolean.valueOf(encryption != null).toString());
        ZooKeeperUtils.createDefault(curator, "/fabric/authentication/domain", "karaf");
        ZooKeeperUtils.createDefault(curator, ZkPath.AUTHENTICATION_CRYPT_ALGORITHM.getPath(), "PBEWithMD5AndDES");
        ZooKeeperUtils.createDefault(curator, ZkPath.AUTHENTICATION_CRYPT_PASSWORD.getPath(), PasswordEncoder.encode(options.getZookeeperPassword()));
        // Ensure ACLs are from the beggining of the fabric tree.
        aclManager.fixAcl(curator, "/fabric", true);
    } finally {
        if (curator != null) {
            curator.close();
        }
    }
}
Also used : LockHandle(io.fabric8.api.LockHandle) Properties(java.util.Properties) ProfileBuilder(io.fabric8.api.ProfileBuilder) Profile(io.fabric8.api.Profile) CuratorFramework(org.apache.curator.framework.CuratorFramework) Version(io.fabric8.api.Version) VersionBuilder(io.fabric8.api.VersionBuilder) File(java.io.File) EncryptionSupport(org.apache.karaf.jaas.modules.encryption.EncryptionSupport)

Example 52 with Server

use of io.fabric8.insight.metrics.model.Server in project fabric8 by jboss-fuse.

the class MavenProxyServletSupportTest method testUpload.

private Map<String, String> testUpload(String path, final byte[] contents, String location, String profile, String version, boolean hasLocationHeader) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));
    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        }
    });
    server.start();
    try {
        int localPort = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort, "fuse", "fuse", null);
        MavenUploadProxyServlet servlet = new MavenUploadProxyServlet(resolver, props, projectDeployer, new File("target/upload"), 0);
        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        EasyMock.expect(request.getPathInfo()).andReturn(path);
        EasyMock.expect(request.getContentType()).andReturn("text/plain").anyTimes();
        EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() {

            private int i;

            @Override
            public int read() throws IOException {
                if (i >= contents.length) {
                    return -1;
                }
                return (contents[i++] & 0xFF);
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        });
        EasyMock.expect(request.getHeader("X-Location")).andReturn(location);
        EasyMock.expect(request.getParameter("profile")).andReturn(profile);
        EasyMock.expect(request.getParameter("version")).andReturn(version);
        final Map<String, String> headers = new HashMap<>();
        HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class);
        HttpServletResponse response = new HttpServletResponseWrapper(rm) {

            @Override
            public void addHeader(String name, String value) {
                headers.put(name, value);
            }
        };
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        EasyMock.replay(request, rm);
        servlet.start();
        servlet.doPut(request, response);
        EasyMock.verify(request, rm);
        Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location"));
        return headers;
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}
Also used : Server(org.eclipse.jetty.server.Server) HashMap(java.util.HashMap) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponseWrapper(javax.servlet.http.HttpServletResponseWrapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ReadListener(javax.servlet.ReadListener) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServerConnector(org.eclipse.jetty.server.ServerConnector) ServletInputStream(javax.servlet.ServletInputStream) MavenResolver(io.fabric8.maven.MavenResolver) File(java.io.File) AbstractRuntimeProperties(io.fabric8.api.scr.AbstractRuntimeProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties)

Example 53 with Server

use of io.fabric8.insight.metrics.model.Server in project fabric8 by jboss-fuse.

the class MavenProxyServletSupportTest method testDownloadMetadata.

@Test(timeout = 30000)
public void testDownloadMetadata() throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));
    Server server = new Server(0);
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            String result = null;
            if ("/repo1/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata>\n" + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n" + "  <versioning>\n" + "    <latest>2.14.0</latest>\n" + "    <release>2.14.0</release>\n" + "    <versions>\n" + "      <version>1.6.1</version>\n" + "      <version>1.6.2</version>\n" + "      <version>1.6.3</version>\n" + "      <version>1.6.4</version>\n" + "      <version>2.0-M2</version>\n" + "      <version>2.0-M3</version>\n" + "      <version>2.0.0</version>\n" + "      <version>2.1.0</version>\n" + "      <version>2.2.0</version>\n" + "      <version>2.3.0</version>\n" + "      <version>2.4.0</version>\n" + "      <version>2.5.0</version>\n" + "      <version>2.6.0</version>\n" + "      <version>2.7.0</version>\n" + "      <version>2.7.1</version>\n" + "      <version>2.7.2</version>\n" + "      <version>2.7.3</version>\n" + "      <version>2.7.4</version>\n" + "      <version>2.7.5</version>\n" + "      <version>2.8.0</version>\n" + "      <version>2.8.1</version>\n" + "      <version>2.8.2</version>\n" + "      <version>2.8.3</version>\n" + "      <version>2.8.4</version>\n" + "      <version>2.8.5</version>\n" + "      <version>2.8.6</version>\n" + "      <version>2.9.0-RC1</version>\n" + "      <version>2.9.0</version>\n" + "      <version>2.9.1</version>\n" + "      <version>2.9.2</version>\n" + "      <version>2.9.3</version>\n" + "      <version>2.9.4</version>\n" + "      <version>2.9.5</version>\n" + "      <version>2.9.6</version>\n" + "      <version>2.9.7</version>\n" + "      <version>2.9.8</version>\n" + "      <version>2.10.0</version>\n" + "      <version>2.10.1</version>\n" + "      <version>2.10.2</version>\n" + "      <version>2.10.3</version>\n" + "      <version>2.10.4</version>\n" + "      <version>2.10.5</version>\n" + "      <version>2.10.6</version>\n" + "      <version>2.10.7</version>\n" + "      <version>2.11.0</version>\n" + "      <version>2.11.1</version>\n" + "      <version>2.11.2</version>\n" + "      <version>2.11.3</version>\n" + "      <version>2.11.4</version>\n" + "      <version>2.12.0</version>\n" + "      <version>2.12.1</version>\n" + "      <version>2.12.2</version>\n" + "      <version>2.12.3</version>\n" + "      <version>2.12.4</version>\n" + "      <version>2.13.0</version>\n" + "      <version>2.13.1</version>\n" + "      <version>2.13.2</version>\n" + "      <version>2.14.0</version>\n" + "    </versions>\n" + "    <lastUpdated>20140918132816</lastUpdated>\n" + "  </versioning>\n" + "</metadata>\n" + "\n";
            } else if ("/repo2/org/apache/camel/camel-core/maven-metadata.xml".equals(target)) {
                result = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<metadata modelVersion=\"1.1.0\">\n" + "  <groupId>org.apache.camel</groupId>\n" + "  <artifactId>camel-core</artifactId>\n" + "  <versioning>\n" + "    <latest>2.14.0.redhat-620034</latest>\n" + "    <release>2.14.0.redhat-620034</release>\n" + "    <versions>\n" + "      <version>2.10.0.redhat-60074</version>\n" + "      <version>2.12.0.redhat-610312</version>\n" + "      <version>2.12.0.redhat-610328</version>\n" + "      <version>2.12.0.redhat-610355</version>\n" + "      <version>2.12.0.redhat-610378</version>\n" + "      <version>2.12.0.redhat-610396</version>\n" + "      <version>2.12.0.redhat-610399</version>\n" + "      <version>2.12.0.redhat-610401</version>\n" + "      <version>2.12.0.redhat-610402</version>\n" + "      <version>2.12.0.redhat-611403</version>\n" + "      <version>2.12.0.redhat-611405</version>\n" + "      <version>2.12.0.redhat-611406</version>\n" + "      <version>2.12.0.redhat-611408</version>\n" + "      <version>2.12.0.redhat-611409</version>\n" + "      <version>2.12.0.redhat-611410</version>\n" + "      <version>2.12.0.redhat-611411</version>\n" + "      <version>2.12.0.redhat-611412</version>\n" + "      <version>2.14.0.redhat-620031</version>\n" + "      <version>2.14.0.redhat-620033</version>\n" + "      <version>2.14.0.redhat-620034</version>\n" + "    </versions>\n" + "    <lastUpdated>20141019130841</lastUpdated>\n" + "  </versioning>\n" + "</metadata>\n" + "\n";
            }
            if (result == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                baseRequest.setHandled(true);
                response.getOutputStream().close();
            } else {
                response.setStatus(HttpServletResponse.SC_OK);
                baseRequest.setHandled(true);
                response.getOutputStream().write(result.getBytes());
                response.getOutputStream().close();
            }
        }
    });
    server.start();
    try {
        int localPort = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/repo1@id=repo1,http://relevant.not/repo2@id=repo2");
        RuntimeProperties props = new MockRuntimeProperties();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort, "fuse", "fuse", null);
        MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(resolver, props, projectDeployer, 5, 0);
        AsyncContext context = EasyMock.createMock(AsyncContext.class);
        EasyMock.makeThreadSafe(context, true);
        final Map<String, Object> attributes = new HashMap<>();
        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        HttpServletRequest requestWrapper = new HttpServletRequestWrapper(request) {

            @Override
            public Object getAttribute(String name) {
                return attributes.get(name);
            }

            @Override
            public void setAttribute(String name, Object o) {
                attributes.put(name, o);
            }
        };
        EasyMock.makeThreadSafe(request, true);
        EasyMock.expect(request.getMethod()).andReturn("GET");
        EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();
        context.addListener((AsyncListener) EasyMock.anyObject());
        EasyMock.expectLastCall();
        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        EasyMock.makeThreadSafe(response, true);
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall().anyTimes();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall().anyTimes();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        response.flushBuffer();
        EasyMock.expectLastCall().anyTimes();
        final CountDownLatch latchDispatch = new CountDownLatch(1);
        context.dispatch();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

            @Override
            public Object answer() throws Throwable {
                latchDispatch.countDown();
                return null;
            }
        });
        EasyMock.replay(request, response, context);
        servlet.start();
        servlet.doGet(requestWrapper, response);
        latchDispatch.await();
        EasyMock.verify(request, response, context);
        EasyMock.reset(request, response, context);
        EasyMock.expect(request.getPathInfo()).andReturn("org/apache/camel/camel-core/maven-metadata.xml");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();
        context.addListener((AsyncListener) EasyMock.anyObject());
        EasyMock.expectLastCall();
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        EasyMock.expect(response.getOutputStream()).andReturn(new ServletOutputStream() {

            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {
            }
        }).anyTimes();
        response.flushBuffer();
        EasyMock.expectLastCall().anyTimes();
        final CountDownLatch latchComplete = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

            @Override
            public Object answer() throws Throwable {
                latchComplete.countDown();
                return null;
            }
        });
        EasyMock.replay(request, response, context);
        servlet.doGet(requestWrapper, response);
        EasyMock.verify(request, response, context);
        org.apache.maven.artifact.repository.metadata.Metadata m = new MetadataXpp3Reader().read(new ByteArrayInputStream(baos.toByteArray()), false);
        assertEquals("2.14.0.redhat-620034", m.getVersioning().getLatest());
        assertTrue(m.getVersioning().getVersions().contains("2.10.4"));
        assertTrue(m.getVersioning().getVersions().contains("2.12.0.redhat-610399"));
        EasyMock.verify(request, response, context);
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}
Also used : Server(org.eclipse.jetty.server.Server) HashMap(java.util.HashMap) ServletOutputStream(javax.servlet.ServletOutputStream) MetadataXpp3Reader(org.apache.maven.artifact.repository.metadata.io.xpp3.MetadataXpp3Reader) AsyncContext(javax.servlet.AsyncContext) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) MavenResolver(io.fabric8.maven.MavenResolver) WriteListener(javax.servlet.WriteListener) AbstractRuntimeProperties(io.fabric8.api.scr.AbstractRuntimeProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CountDownLatch(java.util.concurrent.CountDownLatch) ByteArrayInputStream(java.io.ByteArrayInputStream) File(java.io.File)

Example 54 with Server

use of io.fabric8.insight.metrics.model.Server in project fabric8 by jboss-fuse.

the class MavenProxyServletSupportTest method testDownload.

private void testDownload(Handler serverHandler) throws Exception {
    final String old = System.getProperty("karaf.data");
    System.setProperty("karaf.data", new File("target").getCanonicalPath());
    FileUtils.deleteDirectory(new File("target/tmp"));
    Server server = new Server(0);
    server.setHandler(serverHandler);
    server.start();
    try {
        int localPort = ((ServerConnector) server.getConnectors()[0]).getLocalPort();
        List<String> remoteRepos = Arrays.asList("http://relevant.not/maven2@id=central");
        RuntimeProperties props = new MockRuntimeProperties();
        // TODO: local repo should point to target/tmp
        MavenResolver resolver = createResolver("target/tmp", remoteRepos, "http", "localhost", localPort, "fuse", "fuse", null);
        MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet(resolver, props, projectDeployer, 5, 0);
        AsyncContext context = EasyMock.createMock(AsyncContext.class);
        EasyMock.makeThreadSafe(context, true);
        final Map<String, Object> attributes = new HashMap<>();
        HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class);
        HttpServletRequest requestWrapper = new HttpServletRequestWrapper(request) {

            @Override
            public Object getAttribute(String name) {
                return attributes.get(name);
            }

            @Override
            public void setAttribute(String name, Object o) {
                attributes.put(name, o);
            }
        };
        EasyMock.makeThreadSafe(request, true);
        EasyMock.expect(request.getMethod()).andReturn("GET");
        EasyMock.expect(request.getPathInfo()).andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();
        context.addListener((AsyncListener) EasyMock.anyObject());
        EasyMock.expectLastCall();
        HttpServletResponse response = EasyMock.createMock(HttpServletResponse.class);
        EasyMock.makeThreadSafe(response, true);
        response.setStatus(EasyMock.anyInt());
        EasyMock.expectLastCall();
        response.setContentLength(EasyMock.anyInt());
        EasyMock.expectLastCall();
        response.setContentType((String) EasyMock.anyObject());
        EasyMock.expectLastCall();
        response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong());
        EasyMock.expectLastCall();
        response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject());
        EasyMock.expectLastCall().anyTimes();
        final CountDownLatch latchDispatch = new CountDownLatch(1);
        context.dispatch();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

            @Override
            public Object answer() throws Throwable {
                latchDispatch.countDown();
                return null;
            }
        });
        EasyMock.replay(request, response, context);
        servlet.start();
        servlet.doGet(requestWrapper, response);
        latchDispatch.await();
        EasyMock.verify(request, response, context);
        // 
        // Subsequent call
        // 
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ServletOutputStream outputStream = new ServletOutputStream() {

            @Override
            public void write(int b) throws IOException {
                baos.write(b);
            }

            @Override
            public void write(byte[] b, int off, int len) throws IOException {
                baos.write(b, off, len);
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setWriteListener(WriteListener writeListener) {
            }
        };
        while (true) {
            long size = (Long) attributes.get(AsynchronousFileChannel.class.getName() + ".size");
            long pos = (Long) attributes.get(AsynchronousFileChannel.class.getName() + ".position");
            ByteBuffer buffer = (ByteBuffer) attributes.get(ByteBuffer.class.getName());
            if (pos + buffer.position() >= size) {
                break;
            }
            EasyMock.reset(request, response, context);
            EasyMock.expect(request.getPathInfo()).andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");
            EasyMock.expect(request.startAsync()).andReturn(context);
            context.setTimeout(EasyMock.anyInt());
            EasyMock.expectLastCall();
            context.addListener((AsyncListener) EasyMock.anyObject());
            EasyMock.expectLastCall();
            final CountDownLatch latch = new CountDownLatch(1);
            context.dispatch();
            EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

                @Override
                public Object answer() throws Throwable {
                    latch.countDown();
                    return null;
                }
            });
            EasyMock.expect(response.getOutputStream()).andReturn(outputStream);
            EasyMock.replay(request, response, context);
            servlet.doGet(requestWrapper, response);
            latch.await();
            EasyMock.verify(request, response, context);
        }
        // 
        // Last calls
        // 
        EasyMock.reset(request, response, context);
        EasyMock.expect(request.getPathInfo()).andReturn("org.apache.camel/camel-core/2.13.0/camel-core-2.13.0-sources.jar");
        EasyMock.expect(request.startAsync()).andReturn(context);
        context.setTimeout(EasyMock.anyInt());
        EasyMock.expectLastCall();
        context.addListener((AsyncListener) EasyMock.anyObject());
        EasyMock.expectLastCall();
        final CountDownLatch latchComplete = new CountDownLatch(1);
        context.complete();
        EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

            @Override
            public Object answer() throws Throwable {
                latchComplete.countDown();
                return null;
            }
        });
        EasyMock.expect(response.getOutputStream()).andReturn(outputStream);
        response.flushBuffer();
        EasyMock.expectLastCall();
        EasyMock.replay(request, response, context);
        servlet.doGet(requestWrapper, response);
        latchComplete.await();
        EasyMock.verify(request, response, context);
        Assert.assertArrayEquals(new byte[] { 0x42 }, baos.toByteArray());
    } finally {
        server.stop();
        if (old != null) {
            System.setProperty("karaf.data", old);
        }
    }
}
Also used : Server(org.eclipse.jetty.server.Server) HashMap(java.util.HashMap) ServletOutputStream(javax.servlet.ServletOutputStream) AsyncContext(javax.servlet.AsyncContext) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) AsynchronousFileChannel(java.nio.channels.AsynchronousFileChannel) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) MavenResolver(io.fabric8.maven.MavenResolver) WriteListener(javax.servlet.WriteListener) AbstractRuntimeProperties(io.fabric8.api.scr.AbstractRuntimeProperties) RuntimeProperties(io.fabric8.api.RuntimeProperties) HttpServletResponse(javax.servlet.http.HttpServletResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) File(java.io.File)

Example 55 with Server

use of io.fabric8.insight.metrics.model.Server in project fabric8 by jboss-fuse.

the class AetherTimeoutTest method readTimeout.

@Test
public void readTimeout() throws Exception {
    // case 1: resolution fails because of timeout
    // - aether uses 500ms read timeout
    // - server responds with 1000ms delay
    // - we interrupt resolution after 3000ms in case read timeout in socket.setSoTimeout() is set to 0
    MavenConfigurationImpl mavenConfiguration = basicMavenConfiguration(500);
    mavenConfiguration.setSettings(settingsWithJettyRepository());
    Future<Boolean> task = pool.submit(new ResolveArtifactTask(mavenConfiguration, 1000));
    try {
        boolean resolved = task.get(3000, TimeUnit.MILLISECONDS);
        assertFalse("Should not be resolved due to read timeout", resolved);
    } catch (TimeoutException e) {
        task.cancel(true);
        fail("Should fail due to socket read timeout earlier, not due to future.get() timeout.");
    }
    // case 2: resolution doesn't fail, we're cancelling the task earlier
    // - aether uses 6s read timeout
    // - server responds with 3s delay
    // - we interrupt resolution after 2s ensuring that Aether resolution didn't end on timeout yet
    mavenConfiguration = basicMavenConfiguration(6000);
    mavenConfiguration.setSettings(settingsWithJettyRepository());
    task = pool.submit(new ResolveArtifactTask(mavenConfiguration, 3000));
    boolean timedOut;
    try {
        task.get(2000, TimeUnit.MILLISECONDS);
        timedOut = false;
        fail("Task should not be completed yet");
    } catch (TimeoutException e) {
        timedOut = true;
        task.cancel(true);
    }
    assertTrue("Resolution task should be interrupted", timedOut);
}
Also used : MavenConfigurationImpl(io.fabric8.maven.util.MavenConfigurationImpl) TimeoutException(java.util.concurrent.TimeoutException) Test(org.junit.Test)

Aggregations

HashMap (java.util.HashMap)20 Test (org.junit.Test)19 IOException (java.io.IOException)18 File (java.io.File)9 Map (java.util.Map)9 ClientInvokerImpl (io.fabric8.dosgi.tcp.ClientInvokerImpl)8 ServerInvokerImpl (io.fabric8.dosgi.tcp.ServerInvokerImpl)8 ArrayList (java.util.ArrayList)8 Profile (io.fabric8.api.Profile)7 ServerInvoker (io.fabric8.dosgi.io.ServerInvoker)7 InvocationHandler (java.lang.reflect.InvocationHandler)7 DispatchQueue (org.fusesource.hawtdispatch.DispatchQueue)7 Container (io.fabric8.api.Container)6 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)6 Version (io.fabric8.api.Version)5 CuratorFramework (org.apache.curator.framework.CuratorFramework)5 FabricException (io.fabric8.api.FabricException)4 RuntimeProperties (io.fabric8.api.RuntimeProperties)4 InputStream (java.io.InputStream)4 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)3