Search in sources :

Example 11 with Component

use of org.apache.felix.dm.Component in project felix by apache.

the class DMCommand method showTopComponents.

/**
 * Displays components callbacks (init/start/stop/destroy) elapsed time.
 * The components are sorted (the most time consuming components are displayed first).
 * @param max the max number of components to display (0 means all components)
 */
private void showTopComponents(int max) {
    List<Component> components = new ArrayList<>();
    for (DependencyManager manager : DependencyManager.getDependencyManagers()) {
        components.addAll(manager.getComponents());
    }
    Collections.sort(components, new Comparator<Component>() {

        @Override
        public int compare(Component c1, Component c2) {
            Map<String, Long> c1Times = c1.getComponentDeclaration().getCallbacksTime();
            Map<String, Long> c2Times = c2.getComponentDeclaration().getCallbacksTime();
            Long c1Start = c1Times.get("start");
            Long c2Start = c2Times.get("start");
            if (c1Start != null) {
                if (c2Start != null) {
                    return c1Start > c2Start ? 1 : -1;
                } else {
                    return 1;
                }
            } else {
                if (c2Start != null) {
                    return -1;
                } else {
                    return 0;
                }
            }
        }
    });
    Collections.reverse(components);
    System.out.printf("%-100s %10s %10s%n%n", "Top components (sorted by start duration time)", "[init time]", "[start time]");
    if (components.size() > 0) {
        System.out.println();
        max = max == 0 ? components.size() : Math.min(components.size(), max);
        for (int i = 0; i < components.size() && i < max; i++) {
            ComponentDeclaration decl = components.get(i).getComponentDeclaration();
            System.out.printf("%-100s %10d %10d%n", decl.getClassName(), decl.getCallbacksTime().get("init"), decl.getCallbacksTime().get("start"));
        }
    }
}
Also used : ComponentDeclaration(org.apache.felix.dm.ComponentDeclaration) ArrayList(java.util.ArrayList) DependencyManager(org.apache.felix.dm.DependencyManager) Component(org.apache.felix.dm.Component) Map(java.util.Map)

Example 12 with Component

use of org.apache.felix.dm.Component in project felix by apache.

the class DMCommand method dm.

/**
 * Dependency Manager "dm" command. We use gogo annotations, in order to automate documentation,
 * and also to automatically manage optional flags/options and parameters ordering.
 *
 * @param session the gogo command session, used to get some variables declared in the shell
 *        This parameter is automatically passed by the gogo runtime.
 * @param nodeps false means that dependencies are not displayed
 * @param compact true means informations are displayed in a compact format. This parameter can also be
 *        set using the "dependencymanager.compact" gogo shell variable.
 * @param notavail only unregistered components / unavailable dependencies are displayed
 * @param stats true means some statistics are displayed
 * @param services an osgi filter used to filter on some given osgi service properties.  This parameter can also be
 *        set using the "dependencymanager.services" gogo shell variable.
 * @param components a regular expression to match either component implementation class names.  This parameter can also be
 *        set using the "dependencymanager.components" gogo shell variable.
 * @param componentIds only components matching one of the specified components ids are displayed
 * @param bundleIds a list of bundle ids or symbolic names, used to filter on some given bundles
 */
@Descriptor("List dependency manager components")
public void dm(CommandSession session, @Descriptor("Hides component dependencies") @Parameter(names = { "nodeps", "nd" }, presentValue = "true", absentValue = "false") boolean nodeps, @Descriptor("Displays components using a compact form") @Parameter(names = { "compact", "cp" }, presentValue = "true", absentValue = "") String compact, @Descriptor("Only displays unavailable components") @Parameter(names = { "notavail", "na" }, presentValue = "true", absentValue = "false") boolean notavail, @Descriptor("Detects where are the root failures") @Parameter(names = { "wtf" }, presentValue = "true", absentValue = "false") boolean wtf, @Descriptor("Displays components statistics") @Parameter(names = { "stats", "stat", "st" }, presentValue = "true", absentValue = "false") boolean stats, @Descriptor("<OSGi filter used to filter some service properties>") @Parameter(names = { "services", "s" }, absentValue = "") String services, @Descriptor("<Regex(s) used to filter on component implementation class names (comma separated), can be negated using \"!\" prefix>") @Parameter(names = { "components", "c" }, absentValue = "") String components, @Descriptor("<List of component identifiers to display (comma separated)>") @Parameter(names = { "componentIds", "cid", "ci" }, absentValue = "") String componentIds, @Descriptor("<List of bundle ids or bundle symbolic names to display (comma separated)>") @Parameter(names = { "bundleIds", "bid", "bi", "b" }, absentValue = "") String bundleIds, @Descriptor("<Max number of top components to display (0=all)> This command displays components callbacks (init/start) times>") @Parameter(names = { "top" }, absentValue = "-1") int top) throws Throwable {
    boolean comp = Boolean.parseBoolean(getParam(session, ENV_COMPACT, compact));
    services = getParam(session, ENV_SERVICES, services);
    String[] componentsRegex = getParams(session, ENV_COMPONENTS, components);
    // list of bundle ids or bundle symbolic names
    ArrayList<String> bids = new ArrayList<String>();
    // list of component ids
    ArrayList<Long> cids = new ArrayList<Long>();
    // Parse and check componentIds option
    StringTokenizer tok = new StringTokenizer(componentIds, ", ");
    while (tok.hasMoreTokens()) {
        try {
            cids.add(Long.parseLong(tok.nextToken()));
        } catch (NumberFormatException e) {
            System.out.println("Invalid value for componentIds option");
            return;
        }
    }
    // Parse services filter
    Filter servicesFilter = null;
    try {
        if (services != null) {
            servicesFilter = m_context.createFilter(services);
        }
    } catch (InvalidSyntaxException e) {
        System.out.println("Invalid services OSGi filter: " + services);
        e.printStackTrace(System.err);
        return;
    }
    // Parse and check bundleIds option
    tok = new StringTokenizer(bundleIds, ", ");
    while (tok.hasMoreTokens()) {
        bids.add(tok.nextToken());
    }
    if (top != -1) {
        showTopComponents(top);
        return;
    }
    if (wtf) {
        wtf();
        return;
    }
    DependencyGraph graph = null;
    if (notavail) {
        graph = DependencyGraph.getGraph(ComponentState.UNREGISTERED, DependencyState.ALL_UNAVAILABLE);
    } else {
        graph = DependencyGraph.getGraph(ComponentState.ALL, DependencyState.ALL);
    }
    List<ComponentDeclaration> allComponents = graph.getAllComponents();
    Collections.sort(allComponents, COMPONENT_DECLARATION_COMPARATOR);
    long numberOfComponents = 0;
    long numberOfDependencies = 0;
    long lastBundleId = -1;
    for (ComponentDeclaration cd : allComponents) {
        Bundle bundle = cd.getBundleContext().getBundle();
        if (!matchBundle(bundle, bids)) {
            continue;
        }
        Component component = (Component) cd;
        String name = cd.getName();
        if (!mayDisplay(component, servicesFilter, componentsRegex, cids)) {
            continue;
        }
        numberOfComponents++;
        long bundleId = bundle.getBundleId();
        if (lastBundleId != bundleId) {
            lastBundleId = bundleId;
            if (comp) {
                System.out.println("[" + bundleId + "] " + compactName(bundle.getSymbolicName()));
            } else {
                System.out.println("[" + bundleId + "] " + bundle.getSymbolicName());
            }
        }
        if (comp) {
            System.out.print(" [" + cd.getId() + "] " + compactName(name) + " " + compactState(ComponentDeclaration.STATE_NAMES[cd.getState()]));
        } else {
            System.out.println(" [" + cd.getId() + "] " + name + " " + ComponentDeclaration.STATE_NAMES[cd.getState()]);
        }
        if (!nodeps) {
            List<ComponentDependencyDeclaration> dependencies = graph.getDependecies(cd);
            if (!dependencies.isEmpty()) {
                numberOfDependencies += dependencies.size();
                if (comp) {
                    System.out.print('(');
                }
                for (int j = 0; j < dependencies.size(); j++) {
                    ComponentDependencyDeclaration dep = dependencies.get(j);
                    String depName = dep.getName();
                    String depType = dep.getType();
                    int depState = dep.getState();
                    if (comp) {
                        if (j > 0) {
                            System.out.print(' ');
                        }
                        System.out.print(compactName(depName) + " " + compactState(depType) + " " + compactState(ComponentDependencyDeclaration.STATE_NAMES[depState]));
                    } else {
                        System.out.println("    " + depName + " " + depType + " " + ComponentDependencyDeclaration.STATE_NAMES[depState]);
                    }
                }
                if (comp) {
                    System.out.print(')');
                }
            }
        }
        if (comp) {
            System.out.println();
        }
    }
    if (stats) {
        System.out.println("Statistics:");
        System.out.println(" - Dependency managers: " + DependencyManager.getDependencyManagers().size());
        System.out.println(" - Components: " + numberOfComponents);
        if (!nodeps) {
            System.out.println(" - Dependencies: " + numberOfDependencies);
        }
    }
}
Also used : ComponentDeclaration(org.apache.felix.dm.ComponentDeclaration) Bundle(org.osgi.framework.Bundle) ArrayList(java.util.ArrayList) ComponentDependencyDeclaration(org.apache.felix.dm.ComponentDependencyDeclaration) DependencyGraph(org.apache.felix.dm.diagnostics.DependencyGraph) StringTokenizer(java.util.StringTokenizer) Filter(org.osgi.framework.Filter) InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) Component(org.apache.felix.dm.Component) Descriptor(org.apache.felix.service.command.Descriptor)

Example 13 with Component

use of org.apache.felix.dm.Component in project felix by apache.

the class DMCommandTest method testComponentThatHaveCycliclyDependencyOnAOtheComponentShouldRegisterAsFailure.

@Test
public void testComponentThatHaveCycliclyDependencyOnAOtheComponentShouldRegisterAsFailure() {
    OUT.println("testComponentThatHaveCycliclyDependencyOnAOtheComponentShouldRegisterAsFailure");
    setupEmptyBundles();
    DependencyManager dm = new DependencyManager(m_bundleContext);
    DependencyManager.getDependencyManagers().add(dm);
    Component component1 = dm.createComponent().setImplementation(Cipher.class).setInterface(Cipher.class.getName(), null).add(dm.createServiceDependency().setService(Math.class).setRequired(true));
    dm.add(component1);
    Component component2 = dm.createComponent().setImplementation(Math.class).setInterface(Math.class.getName(), null).add(dm.createServiceDependency().setService(Cipher.class).setRequired(true));
    dm.add(component2);
    dme.wtf();
    String output = outContent.toString();
    assertTrue(output.contains("-> java.lang.Math -> javax.crypto.Cipher -> java.lang.Math") || output.contains("-> javax.crypto.Cipher -> java.lang.Math -> javax.crypto.Cipher"));
    // remove the mess
    dm.remove(component1);
    dm.remove(component2);
}
Also used : DependencyManager(org.apache.felix.dm.DependencyManager) Component(org.apache.felix.dm.Component) Test(org.junit.Test)

Example 14 with Component

use of org.apache.felix.dm.Component in project felix by apache.

the class AbstractDecorator method addDependency.

/**
 * Add a Dependency to all already instantiated services.
 */
public void addDependency(Dependency... dependencies) {
    for (Component component : m_services.values()) {
        Dependency[] copy = Stream.of(dependencies).map(d -> (DependencyContext) d).map(dc -> dc.createCopy()).toArray(Dependency[]::new);
        for (int i = 0; i < dependencies.length; i++) {
            m_depclones.put(dependencies[i], copy[i]);
        }
        component.add(copy);
    }
}
Also used : Component(org.apache.felix.dm.Component) Dependency(org.apache.felix.dm.Dependency) URL(java.net.URL) ComponentStateListener(org.apache.felix.dm.ComponentStateListener) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) DependencyContext(org.apache.felix.dm.context.DependencyContext) BundleContext(org.osgi.framework.BundleContext) Stream(java.util.stream.Stream) ComponentContext(org.apache.felix.dm.context.ComponentContext) ConfigurationException(org.osgi.service.cm.ConfigurationException) Map(java.util.Map) DependencyManager(org.apache.felix.dm.DependencyManager) Bundle(org.osgi.framework.Bundle) Dictionary(java.util.Dictionary) ServiceReference(org.osgi.framework.ServiceReference) ServiceRegistration(org.osgi.framework.ServiceRegistration) Dependency(org.apache.felix.dm.Dependency) Component(org.apache.felix.dm.Component)

Example 15 with Component

use of org.apache.felix.dm.Component in project felix by apache.

the class AbstractDecorator method removed.

public void removed(Bundle bundle) {
    Component newService;
    newService = (Component) m_services.remove(bundle);
    if (newService == null) {
        throw new IllegalStateException("Service should not be null here.");
    }
    m_manager.remove(newService);
}
Also used : Component(org.apache.felix.dm.Component)

Aggregations

Component (org.apache.felix.dm.Component)271 DependencyManager (org.apache.felix.dm.DependencyManager)227 Ensure (org.apache.felix.dm.itest.util.Ensure)91 DependencyManagerActivator.component (org.apache.felix.dm.lambda.DependencyManagerActivator.component)65 Hashtable (java.util.Hashtable)59 Assert (org.junit.Assert)46 Dictionary (java.util.Dictionary)32 ServiceReference (org.osgi.framework.ServiceReference)25 Map (java.util.Map)23 DependencyManagerActivator.aspect (org.apache.felix.dm.lambda.DependencyManagerActivator.aspect)21 Bundle (org.osgi.framework.Bundle)17 ServiceRegistration (org.osgi.framework.ServiceRegistration)17 DependencyManagerActivator.adapter (org.apache.felix.dm.lambda.DependencyManagerActivator.adapter)15 ArrayList (java.util.ArrayList)14 ComponentDeclaration (org.apache.felix.dm.ComponentDeclaration)13 HashMap (java.util.HashMap)12 ServiceDependency (org.apache.felix.dm.ServiceDependency)12 Test (org.junit.Test)11 Properties (java.util.Properties)10 DependencyGraph (org.apache.felix.dm.diagnostics.DependencyGraph)10