Search in sources :

Example 26 with Start

use of io.fabric8.arquillian.kubernetes.event.Start in project fabric8 by jboss-fuse.

the class ExtendedBurnIn method lotsOfClientLoad.

@Test
public void lotsOfClientLoad() throws Exception {
    startRestEndpoint();
    startHttpGateway();
    DetectingGateway gateway = startDetectingGateway();
    final ShutdownTracker tracker = new ShutdownTracker();
    // Run some concurrent load against the broker via the gateway...
    final StompJmsConnectionFactory factory = new StompJmsConnectionFactory();
    factory.setBrokerURI("tcp://localhost:" + gateway.getBoundPort());
    for (int client = 0; client < 10; client++) {
        new Thread("JMS Client: " + client) {

            @Override
            public void run() {
                while (tracker.attemptRetain()) {
                    try {
                        Connection connection = factory.createConnection();
                        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                        MessageConsumer consumer = session.createConsumer(session.createTopic("FOO"));
                        MessageProducer producer = session.createProducer(session.createTopic("FOO"));
                        producer.send(session.createTextMessage("Hello"));
                        consumer.receive(1000);
                        connection.close();
                    } catch (JMSException e) {
                        e.printStackTrace();
                    } finally {
                        tracker.release();
                    }
                }
            }
        }.start();
    }
    int httpPort = gateway.getBoundPort();
    final URL httpUrl = new URL("http://localhost:" + httpPort + "/hello/world");
    for (int client = 0; client < 10; client++) {
        new Thread("HTTP Client: " + client) {

            @Override
            public void run() {
                while (tracker.attemptRetain()) {
                    try {
                        InputStream is = httpUrl.openConnection().getInputStream();
                        try {
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            int c = 0;
                            while ((c = is.read()) >= 0) {
                                baos.write(c);
                            }
                            assertEquals("Hello World!", new String(baos.toByteArray()));
                        } finally {
                            is.close();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        tracker.release();
                    }
                }
            }
        }.start();
    }
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    // Lets monitor memory usage for 5 min..
    for (int i = 0; i < 60 * 5; i++) {
        Thread.sleep(900);
        Runtime.getRuntime().gc();
        Thread.sleep(100);
        long usedMB = ((Long) ((CompositeData) mBeanServer.getAttribute(new ObjectName("java.lang:type=Memory"), "HeapMemoryUsage")).get("used")).longValue() / (1024 * 1024);
        System.out.println("Using " + usedMB + " MB of heap.");
    }
    tracker.stop();
}
Also used : DetectingGateway(io.fabric8.gateway.handlers.detecting.DetectingGateway) InputStream(java.io.InputStream) CompositeData(javax.management.openmbean.CompositeData) ByteArrayOutputStream(java.io.ByteArrayOutputStream) URL(java.net.URL) ObjectName(javax.management.ObjectName) ShutdownTracker(io.fabric8.common.util.ShutdownTracker) StompJmsConnectionFactory(org.fusesource.stomp.jms.StompJmsConnectionFactory) MBeanServer(javax.management.MBeanServer) Test(org.junit.Test)

Example 27 with Start

use of io.fabric8.arquillian.kubernetes.event.Start in project fabric8 by jboss-fuse.

the class ContainerTest method testProfilerStrategy.

@Test
public void testProfilerStrategy() throws Exception {
    Profiler profiler = new Profiler();
    Breadcrumbs breadcrumbs = new Breadcrumbs();
    CamelContext context = new DefaultCamelContext();
    profiler.manage(context);
    breadcrumbs.manage(context);
    context.addRoutes(new RouteBuilder() {

        @Override
        public void configure() throws Exception {
            from("direct:a").doTry().to("seda:polyglot").choice().when(body().isEqualTo("<hello/>")).to("seda:english").throwException(new Exception("Error processing exchange")).endChoice().when(body().isEqualTo("<hallo/>")).to("seda:dutch").delay(2).to("seda:german").endChoice().otherwise().to("seda:french").endDoTry().doCatch(Throwable.class).to("seda:errors");
            String[] eps = { "polyglot", "english", "dutch", "german", "french", "errors" };
            for (String s : eps) {
                from("seda:" + s).aggregate(constant("ok"), new BodyInAggregatingStrategy()).completionSize(3).to("mock:" + s);
            }
        }
    });
    context.start();
    final ProducerTemplate template = new DefaultProducerTemplate(context);
    template.start();
    final String[] values = { "<hello/>", "<hallo/>", "<bonjour/>" };
    final Random rnd = new Random();
    for (int i = 0; i < 100; i++) {
        template.sendBody("direct:a", values[rnd.nextInt(values.length)]);
    }
    profiler.reset();
    long t0 = System.nanoTime();
    int nbThreads = 10;
    final CountDownLatch latch = new CountDownLatch(nbThreads);
    for (int t = 0; t < nbThreads; t++) {
        new Thread() {

            public void run() {
                for (int i = 0; i < 1000; i++) {
                    template.sendBody("direct:a", values[rnd.nextInt(values.length)]);
                }
                latch.countDown();
            }
        }.start();
    }
    latch.await();
    long t1 = System.nanoTime();
    System.out.println("Total time: " + TimeUnit.MILLISECONDS.convert(t1 - t0, TimeUnit.NANOSECONDS));
    print(profiler.getStatistics());
    System.out.println();
    MBeanServer mbeanServer = context.getManagementStrategy().getManagementAgent().getMBeanServer();
    ObjectName on = context.getManagementStrategy().getManagementNamingStrategy().getObjectNameForCamelContext(context);
    String xml = (String) mbeanServer.invoke(on, "dumpRoutesStatsAsXml", new Object[] { false, true }, new String[] { "boolean", "boolean" });
    System.out.println(xml);
}
Also used : CamelContext(org.apache.camel.CamelContext) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) DefaultProducerTemplate(org.apache.camel.impl.DefaultProducerTemplate) ProducerTemplate(org.apache.camel.ProducerTemplate) RouteBuilder(org.apache.camel.builder.RouteBuilder) Breadcrumbs(io.fabric8.insight.camel.breadcrumb.Breadcrumbs) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) DefaultProducerTemplate(org.apache.camel.impl.DefaultProducerTemplate) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) ObjectName(javax.management.ObjectName) Profiler(io.fabric8.insight.camel.profiler.Profiler) Random(java.util.Random) MBeanServer(javax.management.MBeanServer) Test(org.junit.Test)

Example 28 with Start

use of io.fabric8.arquillian.kubernetes.event.Start in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceIT method rollbackInstalledRollupPatch.

@Test
public void rollbackInstalledRollupPatch() throws IOException, GitAPIException {
    freshKarafStandaloneDistro();
    GitPatchRepository repository = patchManagement();
    PatchManagement management = (PatchManagement) pm;
    preparePatchZip("src/test/resources/content/patch1", "target/karaf/patches/source/patch-1.zip", false);
    preparePatchZip("src/test/resources/content/patch4", "target/karaf/patches/source/patch-4.zip", false);
    List<PatchData> patches = management.fetchPatches(new File("target/karaf/patches/source/patch-1.zip").toURI().toURL());
    Patch patch1 = management.trackPatch(patches.get(0));
    patches = management.fetchPatches(new File("target/karaf/patches/source/patch-4.zip").toURI().toURL());
    Patch patch4 = management.trackPatch(patches.get(0));
    Git fork = repository.cloneRepository(repository.findOrCreateMainGitRepository(), true);
    ObjectId master1 = fork.getRepository().resolve(GitPatchRepository.HISTORY_BRANCH);
    String tx = management.beginInstallation(PatchKind.ROLLUP);
    management.install(tx, patch4, null);
    management.commitInstallation(tx);
    // install P patch to check if rolling back rollup patch will remove P patch's tag
    tx = management.beginInstallation(PatchKind.NON_ROLLUP);
    management.install(tx, patch1, null);
    management.commitInstallation(tx);
    fork = repository.cloneRepository(repository.findOrCreateMainGitRepository(), true);
    assertTrue(repository.containsTag(fork, "patch-my-patch-1"));
    management.rollback(patch4.getPatchData());
    repository.closeRepository(fork, true);
    fork = repository.cloneRepository(repository.findOrCreateMainGitRepository(), true);
    ObjectId master2 = fork.getRepository().resolve(GitPatchRepository.HISTORY_BRANCH);
    assertThat(master1, not(equalTo(master2)));
    assertThat(fork.tagList().call().size(), equalTo(2));
    assertTrue(repository.containsTag(fork, "patch-management"));
    assertTrue(repository.containsTag(fork, "baseline-6.2.0"));
    assertFalse("When rolling back rollup patch, newer P patches' tags should be removed", repository.containsTag(fork, "patch-my-patch-1"));
    assertThat(repository.findCurrentBaseline(fork).getTagName(), equalTo("baseline-6.2.0"));
// TODO: There should be version restored from backed up conflict
// but we've changed the way rolledback R patch handled - we copy entire WC after rollback
// String binStart = FileUtils.readFileToString(new File(karafHome, "bin/start"));
// assertTrue("bin/start should be at previous version",
// binStart.contains("echo \"This is user's change\""));
}
Also used : Git(org.eclipse.jgit.api.Git) ObjectId(org.eclipse.jgit.lib.ObjectId) GitPatchRepository(io.fabric8.patch.management.impl.GitPatchRepository) File(java.io.File) Test(org.junit.Test)

Example 29 with Start

use of io.fabric8.arquillian.kubernetes.event.Start in project fabric8 by jboss-fuse.

the class PatchManagementIT method init.

@Before
public void init() throws IOException, GitAPIException {
    super.init(true, true);
    pm = new GitPatchManagementServiceImpl(bundleContext);
    ((GitPatchManagementServiceImpl) pm).start();
    // prepare some ZIP patches
    preparePatchZip("src/test/resources/content/patch1", "target/karaf/patches/source/patch-1.zip", false);
    preparePatchZip("src/test/resources/content/patch3", "target/karaf/patches/source/patch-3.zip", false);
}
Also used : GitPatchManagementServiceImpl(io.fabric8.patch.management.impl.GitPatchManagementServiceImpl) Before(org.junit.Before)

Example 30 with Start

use of io.fabric8.arquillian.kubernetes.event.Start in project fabric8 by jboss-fuse.

the class ServiceImpl method rollback.

@Override
public void rollback(final Patch patch, boolean simulate, boolean force) throws PatchException {
    final PatchResult result = !patchManagement.isStandaloneChild() ? patch.getResult() : patch.getResult().getChildPatches().get(System.getProperty("karaf.name"));
    if (result == null) {
        throw new PatchException("Patch " + patch.getPatchData().getId() + " is not installed");
    }
    if (patch.getPatchData().isRollupPatch()) {
        // we already have the "state" (feature repositories, features, bundles and their states, datafiles
        // and start-level info) stored in *.result file
        Presentation.displayFeatureUpdates(result.getFeatureUpdates(), false);
        Presentation.displayBundleUpdates(result.getBundleUpdates(), false);
        try {
            if (!simulate) {
                // let's backup data files before configadmin detects changes to etc/* files.
                backupService.backupDataFiles(result, Pending.ROLLUP_ROLLBACK);
                for (Bundle b : this.bundleContext.getBundles()) {
                    if (b.getSymbolicName() != null && Utils.stripSymbolicName(b.getSymbolicName()).equals("org.apache.felix.fileinstall")) {
                        b.stop(Bundle.STOP_TRANSIENT);
                        break;
                    }
                }
                patchManagement.rollback(patch.getPatchData());
                result.setPending(Pending.ROLLUP_ROLLBACK);
                if (patchManagement.isStandaloneChild()) {
                    result.getParent().store();
                } else {
                    result.store();
                }
                if (isJvmRestartNeeded(result)) {
                    boolean handlesFullRestart = Boolean.getBoolean("karaf.restart.jvm.supported");
                    if (handlesFullRestart) {
                        System.out.println("Rollup patch " + patch.getPatchData().getId() + " rolled back. Restarting Karaf..");
                        System.setProperty("karaf.restart.jvm", "true");
                    } else {
                        System.out.println("Rollup patch " + patch.getPatchData().getId() + " rolled back. Shutting down Karaf, please restart...");
                    }
                } else {
                    // We don't need a JVM restart, so lets just do a OSGi framework restart
                    System.setProperty("karaf.restart", "true");
                }
                File karafData = new File(bundleContext.getProperty("karaf.data"));
                File cleanCache = new File(karafData, "clean_cache");
                cleanCache.createNewFile();
                bundleContext.getBundle(0l).stop();
                // stop/shutdown occurs on another thread
                return;
            } else {
                System.out.println("Simulation only - no files and runtime data will be modified.");
                return;
            }
        } catch (Exception e) {
            e.printStackTrace(System.err);
            System.err.flush();
            throw new PatchException(e.getMessage(), e);
        }
    }
    // continue with NON_ROLLUP patch
    // current state of the framework
    Bundle[] allBundles = bundleContext.getBundles();
    // check if all the bundles that were updated in patch are available (installed)
    List<BundleUpdate> badUpdates = new ArrayList<BundleUpdate>();
    for (BundleUpdate update : result.getBundleUpdates()) {
        boolean found = false;
        Version v = Version.parseVersion(update.getNewVersion() == null ? update.getPreviousVersion() : update.getNewVersion());
        for (Bundle bundle : allBundles) {
            if (bundle.getSymbolicName() == null || update.getSymbolicName() == null) {
                continue;
            }
            if (stripSymbolicName(bundle.getSymbolicName()).equals(stripSymbolicName(update.getSymbolicName())) && bundle.getVersion().equals(v)) {
                found = true;
                break;
            }
        }
        if (!found) {
            badUpdates.add(update);
        }
    }
    if (!badUpdates.isEmpty() && !force) {
        StringBuilder sb = new StringBuilder();
        sb.append("Unable to rollback patch ").append(patch.getPatchData().getId()).append(" because of the following missing bundles:\n");
        for (BundleUpdate up : badUpdates) {
            String version = up.getNewVersion() == null ? up.getPreviousVersion() : up.getNewVersion();
            sb.append(" - ").append(up.getSymbolicName()).append("/").append(version).append("\n");
        }
        throw new PatchException(sb.toString());
    }
    if (!simulate) {
        // bundle -> old location of the bundle to downgrade from
        final Map<Bundle, String> toUpdate = new HashMap<Bundle, String>();
        for (BundleUpdate update : result.getBundleUpdates()) {
            Version v = Version.parseVersion(update.getNewVersion() == null ? update.getPreviousVersion() : update.getNewVersion());
            for (Bundle bundle : allBundles) {
                if (bundle.getSymbolicName() == null || update.getSymbolicName() == null) {
                    continue;
                }
                if (stripSymbolicName(bundle.getSymbolicName()).equals(stripSymbolicName(update.getSymbolicName())) && bundle.getVersion().equals(v)) {
                    toUpdate.put(bundle, update.getPreviousLocation());
                }
            }
        }
        final boolean isStandaloneChild = patchManagement.isStandaloneChild();
        patchManagement.rollback(patch.getPatchData());
        Executors.newSingleThreadExecutor().execute(new Runnable() {

            @Override
            public void run() {
                try {
                    applyChanges(toUpdate);
                } catch (Exception e) {
                    throw new PatchException("Unable to rollback patch " + patch.getPatchData().getId() + ": " + e.getMessage(), e);
                }
                patch.setResult(null);
                File file = new File(patchDir, result.getPatchData().getId() + ".patch.result");
                if (isStandaloneChild) {
                    file = new File(patchDir, result.getPatchData().getId() + "." + System.getProperty("karaf.name") + ".patch.result");
                }
                file.delete();
            }
        });
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) PatchException(io.fabric8.patch.management.PatchException) BundleException(org.osgi.framework.BundleException) IOException(java.io.IOException) Version(org.osgi.framework.Version) PatchResult(io.fabric8.patch.management.PatchResult) PatchException(io.fabric8.patch.management.PatchException) File(java.io.File) BundleUpdate(io.fabric8.patch.management.BundleUpdate)

Aggregations

Test (org.junit.Test)25 IOException (java.io.IOException)24 File (java.io.File)18 HashMap (java.util.HashMap)15 Map (java.util.Map)10 Git (org.eclipse.jgit.api.Git)10 GitPatchRepository (io.fabric8.patch.management.impl.GitPatchRepository)8 ArrayList (java.util.ArrayList)8 Bundle (org.osgi.framework.Bundle)8 PatchException (io.fabric8.patch.management.PatchException)7 URISyntaxException (java.net.URISyntaxException)7 BundleException (org.osgi.framework.BundleException)7 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 CuratorFramework (org.apache.curator.framework.CuratorFramework)6 Container (io.fabric8.api.Container)5 CreateContainerMetadata (io.fabric8.api.CreateContainerMetadata)5 FabricService (io.fabric8.api.FabricService)5 GitPatchManagementServiceImpl (io.fabric8.patch.management.impl.GitPatchManagementServiceImpl)5 MalformedURLException (java.net.MalformedURLException)5 URI (java.net.URI)5