Search in sources :

Example 36 with Message

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Message in project fabric8 by jboss-fuse.

the class Log4jLogQuery method toLogEvent.

protected LogEvent toLogEvent(LoggingEvent element) {
    LogEvent answer = new LogEvent();
    answer.setClassName(element.getFQNOfLoggerClass());
    // TODO
    // answer.setContainerName(element.get);
    ThrowableInformation throwableInformation = element.getThrowableInformation();
    if (throwableInformation != null) {
        ThrowableFormatter renderer = new ThrowableFormatter();
        String[] stack = renderer.doRender(throwableInformation.getThrowable());
        if (stack == null) {
            stack = element.getThrowableStrRep();
        }
        answer.setException(stack);
    }
    LocationInfo locationInformation = element.getLocationInformation();
    if (locationInformation != null) {
        answer.setFileName(locationInformation.getFileName());
        answer.setClassName(locationInformation.getClassName());
        answer.setMethodName(locationInformation.getMethodName());
        answer.setLineNumber(locationInformation.getLineNumber());
    }
    Level level = element.getLevel();
    if (level != null) {
        answer.setLevel(level.toString());
    }
    // TODO
    answer.setLogger(element.getLoggerName());
    Category logger = element.getLogger();
    Object message = element.getMessage();
    if (message != null) {
        // TODO marshal differently?
        answer.setMessage(message.toString());
    }
    answer.setProperties(element.getProperties());
    // TODO
    answer.setSeq(element.getTimeStamp());
    answer.setTimestamp(new Date(element.getTimeStamp()));
    answer.setThread(element.getThreadName());
    answer.setHost(getHostName());
    return answer;
}
Also used : Category(org.apache.log4j.Category) LogEvent(io.fabric8.insight.log.LogEvent) ThrowableInformation(org.apache.log4j.spi.ThrowableInformation) Level(org.apache.log4j.Level) Date(java.util.Date) LocationInfo(org.apache.log4j.spi.LocationInfo)

Example 37 with Message

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Message in project fabric8 by jboss-fuse.

the class FabricDosgiCamelTest method testFeatureProvisioning.

@Test
public void testFeatureProvisioning() 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);
        waitForFabricCommands();
        Set<ContainerProxy> containers = ContainerBuilder.create(fabricProxy, 2).withName("dosgi").withProfiles("karaf").assertProvisioningResult().build();
        try {
            List<Container> containerList = new ArrayList<Container>(containers);
            List<Container> dosgiProviderContainers = containerList.subList(0, containerList.size() / 2);
            List<Container> dosgiCamelContainers = containerList.subList(containerList.size() / 2, containerList.size());
            for (Container c : dosgiProviderContainers) {
                setData(curator, ZkPath.CONTAINER_PROVISION_RESULT.getPath(c.getId()), "changing profile");
                Profile p = c.getVersion().getRequiredProfile("example-dosgi-camel.provider");
                c.setProfiles(new Profile[] { p });
            }
            for (Container c : dosgiCamelContainers) {
                setData(curator, ZkPath.CONTAINER_PROVISION_RESULT.getPath(c.getId()), "changing profile");
                Profile p = c.getVersion().getRequiredProfile("example-dosgi-camel.consumer");
                c.setProfiles(new Profile[] { p });
            }
            Provision.provisioningSuccess(dosgiProviderContainers, PROVISION_TIMEOUT);
            Provision.provisioningSuccess(dosgiCamelContainers, PROVISION_TIMEOUT);
            Assert.assertTrue(Provision.waitForCondition(dosgiCamelContainers, new ContainerCondition() {

                @Override
                public Boolean checkConditionOnContainer(final Container c) {
                    String response = executeCommand("fabric:container-connect -u admin -p admin " + c.getId() + " log:display | grep \"Message from distributed service to\"");
                    System.out.println(executeCommand("fabric:container-connect -u admin -p admin " + c.getId() + " camel:route-info fabric-client"));
                    Assert.assertNotNull(response);
                    System.out.println(response);
                    String[] lines = response.split("\n");
                    // TODO: This assertion is very relaxed and guarantees nothing.
                    return lines.length >= 1;
                }
            }, 20000L));
        } finally {
            ContainerBuilder.destroy(containers);
        }
    } finally {
        fabricProxy.close();
    }
}
Also used : CuratorFramework(org.apache.curator.framework.CuratorFramework) Container(io.fabric8.api.Container) FabricService(io.fabric8.api.FabricService) ArrayList(java.util.ArrayList) ContainerProxy(io.fabric8.itests.paxexam.support.ContainerProxy) Profile(io.fabric8.api.Profile) ContainerCondition(io.fabric8.itests.paxexam.support.ContainerCondition) Test(org.junit.Test)

Example 38 with Message

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Message in project fabric8 by jboss-fuse.

the class CamelAutoTestService method onConfigured.

@Override
protected void onConfigured() throws Exception {
    LOG.debug("onConfigured. mockOutputs: " + mockOutputs + " mockInputs: " + mockInputs + " messageFolder: " + messageFolder);
    FabricService fabricService = this.fabricService.getOptional();
    // lets find the camel contexts to test in this container
    MBeanServer mbeanServerValue = mbeanServer;
    if (mbeanServerValue != null && fabricService != null) {
        Profile overlayProfile = fabricService.getCurrentContainer().getOverlayProfile();
        Profile effectiveProfile = Profiles.getEffectiveProfile(fabricService, overlayProfile);
        Set<String> configurationFileNames = effectiveProfile.getConfigurationFileNames();
        for (CamelContext camelContext : camelContexts.values()) {
            String camelContextID = camelContext.getName();
            // check we only add testing stuff to each context once
            if (camelContext instanceof ModelCamelContext) {
                final ModelCamelContext modelCamelContext = (ModelCamelContext) camelContext;
                List<RouteDefinition> routeDefinitions = modelCamelContext.getRouteDefinitions();
                if (camelContextsConfigured.add(camelContextID)) {
                    NodeIdFactory nodeIdFactory = camelContext.getNodeIdFactory();
                    if (mockInputs || mockOutputs) {
                        for (RouteDefinition routeDefinition : routeDefinitions) {
                            String routeId = routeDefinition.idOrCreate(nodeIdFactory);
                            modelCamelContext.stopRoute(routeId);
                            final String routeKey = camelContextID + "." + routeId;
                            LOG.info("Mocking Camel route: " + routeKey);
                            routeDefinition.adviceWith(modelCamelContext, new AdviceWithRouteBuilder() {

                                @Override
                                public void configure() throws Exception {
                                    if (mockOutputs) {
                                        modelCamelContext.addRegisterEndpointCallback(strategy);
                                    }
                                }
                            });
                        // the advised route is automatic restarted
                        }
                    }
                    String path = messageFolder;
                    if (Strings.isNotBlank(path)) {
                        path += "/";
                    }
                    path += camelContextID;
                    ProducerTemplate producerTemplate = camelContext.createProducerTemplate();
                    try {
                        for (RouteDefinition routeDefinition : routeDefinitions) {
                            String routeId = routeDefinition.idOrCreate(nodeIdFactory);
                            String routePath = path + "/" + routeId + "/";
                            List<FromDefinition> inputs = routeDefinition.getInputs();
                            for (FromDefinition input : inputs) {
                                Endpoint endpoint = input.getEndpoint();
                                if (endpoint == null) {
                                    String uri = input.getUri();
                                    if (Strings.isNullOrBlank(uri)) {
                                        String ref = input.getRef();
                                        if (Strings.isNotBlank(ref)) {
                                            uri = "ref:" + ref;
                                        }
                                    }
                                    if (Strings.isNotBlank(uri)) {
                                        endpoint = camelContext.getEndpoint(uri);
                                    }
                                }
                                if (endpoint == null) {
                                    LOG.warn("Cannot find endpoint, uri or ref of input " + input + " on route " + routeId + " camelContext: " + camelContextID);
                                } else {
                                    for (String configFile : configurationFileNames) {
                                        if (configFile.startsWith(routePath)) {
                                            LOG.info("Sending file: " + configFile + " to " + endpoint);
                                            byte[] data = effectiveProfile.getFileConfiguration(configFile);
                                            if (data != null) {
                                                // lest send this message to this endpoint
                                                producerTemplate.sendBody(endpoint, data);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } finally {
                        producerTemplate.stop();
                    }
                }
            }
        }
    }
}
Also used : CamelContext(org.apache.camel.CamelContext) ModelCamelContext(org.apache.camel.model.ModelCamelContext) ProducerTemplate(org.apache.camel.ProducerTemplate) FromDefinition(org.apache.camel.model.FromDefinition) Profile(io.fabric8.api.Profile) ModelCamelContext(org.apache.camel.model.ModelCamelContext) AdviceWithRouteBuilder(org.apache.camel.builder.AdviceWithRouteBuilder) NodeIdFactory(org.apache.camel.spi.NodeIdFactory) RouteDefinition(org.apache.camel.model.RouteDefinition) Endpoint(org.apache.camel.Endpoint) FabricService(io.fabric8.api.FabricService) MBeanServer(javax.management.MBeanServer)

Example 39 with Message

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Message in project fabric8 by jboss-fuse.

the class Agent method provision.

public void provision(Map<String, Feature> allFeatures, Set<String> features, Set<String> bundles, Set<String> reqs, Set<String> overrides, Set<String> optionals, Map<String, Map<VersionRange, Map<String, String>>> metadata) throws Exception {
    Callable<Map<String, Resource>> res = loadResources(manager, metadata, optionals);
    // TODO: requirements should be able to be assigned to a region
    Map<String, Set<String>> requirements = new HashMap<>();
    for (String feature : features) {
        addToMapSet(requirements, ROOT_REGION, "feature:" + feature);
    }
    for (String bundle : bundles) {
        addToMapSet(requirements, ROOT_REGION, "bundle:" + bundle);
    }
    for (String req : reqs) {
        addToMapSet(requirements, ROOT_REGION, "req:" + req);
    }
    Deployer.DeploymentRequest request = new Deployer.DeploymentRequest();
    request.updateSnaphots = updateSnaphots;
    request.bundleUpdateRange = bundleUpdateRange;
    request.featureResolutionRange = featureResolutionRange;
    request.globalRepository = new StaticRepository(res.call().values());
    request.overrides = overrides;
    request.requirements = requirements;
    request.stateChanges = Collections.emptyMap();
    request.options = options;
    request.metadata = metadata;
    request.bundleStartTimeout = bundleStartTimeout;
    Deployer.DeploymentState dstate = new Deployer.DeploymentState();
    // Service bundle
    dstate.serviceBundle = serviceBundle;
    // Start level
    FrameworkStartLevel fsl = systemBundleContext.getBundle().adapt(FrameworkStartLevel.class);
    dstate.initialBundleStartLevel = fsl.getInitialBundleStartLevel();
    dstate.currentStartLevel = fsl.getStartLevel();
    // Bundles
    dstate.bundles = new HashMap<>();
    for (Bundle bundle : systemBundleContext.getBundles()) {
        dstate.bundles.put(bundle.getBundleId(), bundle);
    }
    // Features
    dstate.features = allFeatures;
    // Region -> bundles mapping
    // Region -> policy mapping
    dstate.bundlesPerRegion = new HashMap<>();
    dstate.filtersPerRegion = new HashMap<>();
    if (digraph == null) {
        for (Long id : dstate.bundles.keySet()) {
            addToMapSet(dstate.bundlesPerRegion, ROOT_REGION, id);
        }
    } else {
        RegionDigraph clone = digraph.copy();
        for (Region region : clone.getRegions()) {
            // Get bundles
            dstate.bundlesPerRegion.put(region.getName(), new HashSet<>(region.getBundleIds()));
            // Get policies
            Map<String, Map<String, Set<String>>> edges = new HashMap<>();
            for (RegionDigraph.FilteredRegion fr : clone.getEdges(region)) {
                Map<String, Set<String>> policy = new HashMap<>();
                Map<String, Collection<String>> current = fr.getFilter().getSharingPolicy();
                for (String ns : current.keySet()) {
                    for (String f : current.get(ns)) {
                        addToMapSet(policy, ns, f);
                    }
                }
                edges.put(fr.getRegion().getName(), policy);
            }
            dstate.filtersPerRegion.put(region.getName(), edges);
        }
    }
    final State state = new State();
    try {
        storage.load(state);
    } catch (IOException e) {
        LOGGER.warn("Error loading agent state", e);
    }
    if (state.managedBundles.isEmpty()) {
        for (Bundle b : systemBundleContext.getBundles()) {
            if (b.getBundleId() != 0) {
                addToMapSet(state.managedBundles, ROOT_REGION, b.getBundleId());
            }
        }
    }
    // corresponding jar url and use that one to compute the checksum of the bundle.
    for (Map.Entry<Long, Bundle> entry : dstate.bundles.entrySet()) {
        long id = entry.getKey();
        Bundle bundle = entry.getValue();
        if (id > 0 && isUpdateable(bundle) && !state.bundleChecksums.containsKey(id)) {
            try {
                URL url = bundle.getResource("META-INF/MANIFEST.MF");
                URLConnection con = url.openConnection();
                Method method = con.getClass().getDeclaredMethod("getLocalURL");
                method.setAccessible(true);
                String jarUrl = ((URL) method.invoke(con)).toExternalForm();
                if (jarUrl.startsWith("jar:")) {
                    String jar = jarUrl.substring("jar:".length(), jarUrl.indexOf("!/"));
                    jar = new URL(jar).getFile();
                    long checksum = ChecksumUtils.checksumFile(new File(jar));
                    state.bundleChecksums.put(id, checksum);
                }
            } catch (Throwable t) {
                LOGGER.debug("Error calculating checksum for bundle: %s", bundle, t);
            }
        }
    }
    dstate.state = state;
    Set<String> prereqs = new HashSet<>();
    while (true) {
        try {
            Deployer.DeployCallback callback = new BaseDeployCallback() {

                @Override
                public void phase(String message) {
                    Agent.this.updateStatus(message);
                }

                @Override
                public void saveState(State newState) {
                    state.replace(newState);
                    try {
                        Agent.this.saveState(newState);
                    } catch (IOException e) {
                        LOGGER.warn("Error storing agent state", e);
                    }
                }

                @Override
                public void provisionList(Set<Resource> resources) {
                    Agent.this.provisionList(resources);
                }

                @Override
                public void restoreConfigAdminIfNeeded() {
                    if (configInstaller != null) {
                        configInstaller.restoreConfigAdminIfNeeded();
                    }
                }

                @Override
                public boolean done(boolean agentStarted, List<String> urls) {
                    return Agent.this.done(agentStarted, urls);
                }
            };
            // FABRIC-790, FABRIC-981 - wait for ProfileUrlHandler before attempting to load bundles (in subsystem.resolve())
            // (which may be the case with bundle.xxx=blueprint:profile:xxx URLs in io.fabric8.agent PID)
            // https://developer.jboss.org/message/920681 - 30 seconds is too low sometimes
            // there was "url.handler.timeouts" option for agent, but it was removed during migration to karaf 4.x resolver
            // LOGGER.debug("Waiting for ProfileUrlHandler");
            // awaitService(URLStreamHandlerService.class, "(url.handler.protocol=profile)", 30, TimeUnit.SECONDS);
            // LOGGER.debug("Waiting for ProfileUrlHandler finished");
            Deployer deployer = new Deployer(manager, callback);
            deployer.setDeploymentAgentId(deploymentAgentId);
            deployer.deploy(dstate, request);
            break;
        } catch (Deployer.PartialDeploymentException e) {
            if (!prereqs.containsAll(e.getMissing())) {
                prereqs.addAll(e.getMissing());
            } else {
                throw new Exception("Deployment aborted due to loop in missing prerequisites: " + e.getMissing());
            }
        }
    }
}
Also used : EnumSet(java.util.EnumSet) Set(java.util.Set) MapUtils.addToMapSet(io.fabric8.agent.internal.MapUtils.addToMapSet) HashSet(java.util.HashSet) HashMap(java.util.HashMap) URL(java.net.URL) List(java.util.List) HashSet(java.util.HashSet) RegionDigraph(org.eclipse.equinox.region.RegionDigraph) Bundle(org.osgi.framework.Bundle) IOException(java.io.IOException) Method(java.lang.reflect.Method) FrameworkStartLevel(org.osgi.framework.startlevel.FrameworkStartLevel) URLConnection(java.net.URLConnection) BundleException(org.osgi.framework.BundleException) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) MultiException(io.fabric8.common.util.MultiException) Region(org.eclipse.equinox.region.Region) Collection(java.util.Collection) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) StaticRepository(io.fabric8.agent.repository.StaticRepository)

Example 40 with Message

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Message in project fabric8 by jboss-fuse.

the class ActiveMQBlobMessage method onSend.

public void onSend() throws OpenwireException {
    super.onSend();
    // message
    if (blobUploader != null) {
        try {
            URL value = blobUploader.upload(this);
            setURL(value);
        } catch (IOException e) {
            throw new OpenwireException(e);
        }
    }
}
Also used : OpenwireException(io.fabric8.gateway.handlers.detecting.protocol.openwire.support.OpenwireException) IOException(java.io.IOException) URL(java.net.URL)

Aggregations

IOException (java.io.IOException)12 HashMap (java.util.HashMap)9 File (java.io.File)8 Profile (io.fabric8.api.Profile)7 Map (java.util.Map)7 Message (io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Message)6 ArrayList (java.util.ArrayList)5 PatchException (io.fabric8.patch.management.PatchException)4 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 Container (io.fabric8.api.Container)3 Version (io.fabric8.api.Version)3 Date (java.util.Date)3 LinkedList (java.util.LinkedList)3 List (java.util.List)3 ZipFile (org.apache.commons.compress.archivers.zip.ZipFile)3 MojoFailureException (org.apache.maven.plugin.MojoFailureException)3 Git (org.eclipse.jgit.api.Git)3 GitAPIException (org.eclipse.jgit.api.errors.GitAPIException)3 RevCommit (org.eclipse.jgit.revwalk.RevCommit)3 Test (org.junit.Test)3