Search in sources :

Example 16 with Context

use of io.fabric8.kubernetes.api.model.Context in project fabric8 by jboss-fuse.

the class WatcherSpringContext method addPath.

// Implementation
// -------------------------------------------------------------------------
protected void addPath(Path path) {
    String url = null;
    try {
        url = toUrlString(path);
    } catch (MalformedURLException e) {
        LOG.warn("Ignored path " + path + " due to: " + e, e);
    }
    if (url != null) {
        FileSystemXmlApplicationContext context = contextMap.get(url);
        if (context != null) {
            try {
                LOG.info("Refreshing context at path " + path + " context " + context);
                context.refresh();
            } catch (Exception e) {
                LOG.warn("Failed to refresh context at " + path + " context " + context + ". " + e, e);
            }
        } else {
            context = createContext(path, url);
            if (context != null) {
                contextMap.put(url, context);
                try {
                    LOG.info("Starting context at path " + path + " context " + context);
                    context.start();
                } catch (Exception e) {
                    LOG.warn("Failed to start context at " + path + " context " + context + ". " + e, e);
                }
            }
        }
    }
}
Also used : FileSystemXmlApplicationContext(org.springframework.context.support.FileSystemXmlApplicationContext) MalformedURLException(java.net.MalformedURLException) PathHelper.toUrlString(io.fabric8.watcher.PathHelper.toUrlString) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 17 with Context

use of io.fabric8.kubernetes.api.model.Context in project fabric8 by jboss-fuse.

the class EncryptedPropertyResolver method initialize.

/**
 * When {@link FabricService} becomes available, we can initialize this {@link PlaceholderResolver}
 * @param fabricService
 */
public void initialize(FabricService fabricService) {
    this.fabricService = fabricService;
    encryptor = getEncryptor(fabricService);
    if (bundleContext != null) {
        seRegistration = bundleContext.registerService(PBEStringEncryptor.class, encryptor, null);
        BundleContext context = FrameworkUtil.getBundle(PersistenceManager.class).getBundleContext();
        encryptingPersistenceManager = new EncryptingPersistenceManager(context, context.getProperty(ConfigurationManager.CM_CONFIG_DIR), encryptor);
        originalPersistenceManager = inject(configAdmin, encryptingPersistenceManager);
        passwordNodeCache = new NodeCacheExtended(fabricService.adapt(CuratorFramework.class), AUTHENTICATION_CRYPT_PASSWORD.getPath());
        passwordNodeCache.getListenable().addListener(this);
        alogrithmNodeCache = new NodeCacheExtended(fabricService.adapt(CuratorFramework.class), AUTHENTICATION_CRYPT_ALGORITHM.getPath());
        alogrithmNodeCache.getListenable().addListener(this);
        try {
            passwordNodeCache.start();
            alogrithmNodeCache.start();
        } catch (Exception e) {
            throw new FabricException(e);
        }
    }
}
Also used : NodeCacheExtended(org.apache.curator.framework.recipes.cache.NodeCacheExtended) EncryptingPersistenceManager(org.apache.felix.cm.file.EncryptingPersistenceManager) PersistenceManager(org.apache.felix.cm.PersistenceManager) FabricException(io.fabric8.api.FabricException) PBEStringEncryptor(org.jasypt.encryption.pbe.PBEStringEncryptor) StandardPBEStringEncryptor(org.jasypt.encryption.pbe.StandardPBEStringEncryptor) EncryptingPersistenceManager(org.apache.felix.cm.file.EncryptingPersistenceManager) FabricException(io.fabric8.api.FabricException) IOException(java.io.IOException) EncryptionOperationNotPossibleException(org.jasypt.exceptions.EncryptionOperationNotPossibleException) BundleContext(org.osgi.framework.BundleContext)

Example 18 with Context

use of io.fabric8.kubernetes.api.model.Context in project fabric8 by jboss-fuse.

the class CloudContainerInstallationTask method uploadToNode.

private void uploadToNode(ComputeServiceContext context, NodeMetadata node, LoginCredentials credentials, URL url, String path) {
    Utils utils = context.utils();
    SshClient ssh = credentials != null ? utils.sshForNode().apply(NodeMetadataBuilder.fromNodeMetadata(nodeMetadata).credentials(credentials).build()) : utils.sshForNode().apply(node);
    try (InputStream is = url.openStream()) {
        ssh.connect();
        File distro = Files.createTempFile("/tmp");
        Files.copy(is, new FileOutputStream(distro));
        ssh.put(path, Payloads.newFilePayload(distro));
        distro.delete();
    } catch (IOException e) {
        LOGGER.warn("Failed to upload. Will attempt downloading distribution via maven.");
    } finally {
        if (ssh != null) {
            ssh.disconnect();
        }
    }
}
Also used : SshClient(org.jclouds.ssh.SshClient) Utils(org.jclouds.compute.Utils) ContainerProviderUtils(io.fabric8.internal.ContainerProviderUtils) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File)

Example 19 with Context

use of io.fabric8.kubernetes.api.model.Context in project fabric8 by jboss-fuse.

the class ZooKeeperServerFactory method activateInternal.

private Destroyable activateInternal(BundleContext context, Map<String, ?> configuration) throws Exception {
    LOGGER.info("Creating zookeeper server with: {}", configuration);
    Properties props = new Properties();
    for (Entry<String, ?> entry : configuration.entrySet()) {
        props.put(entry.getKey(), entry.getValue());
    }
    // Remove the dependency on the current dir from dataDir
    String dataDir = props.getProperty("dataDir");
    if (dataDir != null && !Paths.get(dataDir).isAbsolute()) {
        dataDir = runtimeProperties.get().getDataPath().resolve(dataDir).toFile().getAbsolutePath();
        props.setProperty("dataDir", dataDir);
    }
    props.put("clientPortAddress", bootstrapConfiguration.get().getBindAddress());
    // Create myid file
    String serverId = (String) props.get("server.id");
    if (serverId != null) {
        props.remove("server.id");
        File myId = new File(dataDir, "myid");
        if (myId.exists() && !myId.delete()) {
            throw new IOException("Failed to delete " + myId);
        }
        if (myId.getParentFile() == null || (!myId.getParentFile().exists() && !myId.getParentFile().mkdirs())) {
            throw new IOException("Failed to create " + myId.getParent());
        }
        FileOutputStream fos = new FileOutputStream(myId);
        try {
            fos.write((serverId + "\n").getBytes());
        } finally {
            fos.close();
        }
    }
    QuorumPeerConfig peerConfig = getPeerConfig(props);
    if (!peerConfig.getServers().isEmpty()) {
        NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory();
        cnxnFactory.configure(peerConfig.getClientPortAddress(), peerConfig.getMaxClientCnxns());
        QuorumPeer quorumPeer = new QuorumPeer();
        quorumPeer.setClientPortAddress(peerConfig.getClientPortAddress());
        quorumPeer.setTxnFactory(new FileTxnSnapLog(new File(peerConfig.getDataLogDir()), new File(peerConfig.getDataDir())));
        quorumPeer.setQuorumPeers(peerConfig.getServers());
        quorumPeer.setElectionType(peerConfig.getElectionAlg());
        quorumPeer.setMyid(peerConfig.getServerId());
        quorumPeer.setTickTime(peerConfig.getTickTime());
        quorumPeer.setMinSessionTimeout(peerConfig.getMinSessionTimeout());
        quorumPeer.setMaxSessionTimeout(peerConfig.getMaxSessionTimeout());
        quorumPeer.setInitLimit(peerConfig.getInitLimit());
        quorumPeer.setSyncLimit(peerConfig.getSyncLimit());
        quorumPeer.setQuorumVerifier(peerConfig.getQuorumVerifier());
        quorumPeer.setCnxnFactory(cnxnFactory);
        quorumPeer.setZKDatabase(new ZKDatabase(quorumPeer.getTxnFactory()));
        quorumPeer.setLearnerType(peerConfig.getPeerType());
        try {
            LOGGER.debug("Starting quorum peer \"{}\" on address {}", quorumPeer.getMyid(), peerConfig.getClientPortAddress());
            quorumPeer.start();
            LOGGER.debug("Started quorum peer \"{}\"", quorumPeer.getMyid());
        } catch (Exception e) {
            LOGGER.warn("Failed to start quorum peer \"{}\", reason : {} ", quorumPeer.getMyid(), e.getMessage());
            quorumPeer.shutdown();
            throw e;
        }
        // Register stats provider
        ClusteredServer server = new ClusteredServer(quorumPeer);
        registration = context.registerService(QuorumStats.Provider.class, server, null);
        return server;
    } else {
        ServerConfig serverConfig = getServerConfig(peerConfig);
        ZooKeeperServer zkServer = new ZooKeeperServer();
        FileTxnSnapLog ftxn = new FileTxnSnapLog(new File(serverConfig.getDataLogDir()), new File(serverConfig.getDataDir()));
        zkServer.setTxnLogFactory(ftxn);
        zkServer.setTickTime(serverConfig.getTickTime());
        zkServer.setMinSessionTimeout(serverConfig.getMinSessionTimeout());
        zkServer.setMaxSessionTimeout(serverConfig.getMaxSessionTimeout());
        NIOServerCnxnFactory cnxnFactory = new NIOServerCnxnFactory() {

            protected void configureSaslLogin() throws IOException {
            }
        };
        cnxnFactory.configure(serverConfig.getClientPortAddress(), serverConfig.getMaxClientCnxns());
        try {
            LOGGER.debug("Starting ZooKeeper server on address {}", peerConfig.getClientPortAddress());
            cnxnFactory.startup(zkServer);
            LOGGER.debug("Started ZooKeeper server");
        } catch (Exception e) {
            LOGGER.warn("Failed to start ZooKeeper server, reason : {}", e);
            cnxnFactory.shutdown();
            throw e;
        }
        // Register stats provider
        SimpleServer server = new SimpleServer(zkServer, cnxnFactory);
        registration = context.registerService(ServerStats.Provider.class, server, null);
        startCleanupManager(serverConfig, props);
        return server;
    }
}
Also used : IOException(java.io.IOException) RuntimeProperties(io.fabric8.api.RuntimeProperties) Properties(java.util.Properties) FileTxnSnapLog(org.apache.zookeeper.server.persistence.FileTxnSnapLog) ConfigException(org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException) IOException(java.io.IOException) QuorumPeerConfig(org.apache.zookeeper.server.quorum.QuorumPeerConfig) FileOutputStream(java.io.FileOutputStream) QuorumPeer(org.apache.zookeeper.server.quorum.QuorumPeer) File(java.io.File)

Example 20 with Context

use of io.fabric8.kubernetes.api.model.Context 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)

Aggregations

Test (org.junit.Test)135 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)58 Async (io.vertx.ext.unit.Async)52 Expectations (mockit.Expectations)34 Probe (io.fabric8.kubernetes.api.model.Probe)33 Reconciliation (io.strimzi.controller.cluster.Reconciliation)24 File (java.io.File)23 Git (org.eclipse.jgit.api.Git)23 GitContext (io.fabric8.api.GitContext)21 IOException (java.io.IOException)21 ConfigMapOperator (io.strimzi.controller.cluster.operator.resource.ConfigMapOperator)20 ServiceOperator (io.strimzi.controller.cluster.operator.resource.ServiceOperator)20 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)18 HashMap (java.util.HashMap)17 LockHandle (io.fabric8.api.LockHandle)15 KubernetesListBuilder (io.fabric8.kubernetes.api.model.KubernetesListBuilder)15 NonNamespaceOperation (io.fabric8.kubernetes.client.dsl.NonNamespaceOperation)15 ProcessorConfig (io.fabric8.maven.core.config.ProcessorConfig)15 MixedOperation (io.fabric8.kubernetes.client.dsl.MixedOperation)14 Resource (io.fabric8.kubernetes.client.dsl.Resource)14