Search in sources :

Example 6 with StatusHolder

use of com.cosylab.acs.maci.StatusHolder in project ACS by ACS-Community.

the class ManagerImplTest method testContainerToManagerStateTransferComponents.

public void testContainerToManagerStateTransferComponents() {
    TestComponent mount1COB = new TestComponent("MOUNT1");
    TestComponent mount2COB = new TestComponent("MOUNT2");
    Map supportedComponents = new HashMap();
    supportedComponents.put("MOUNT1", mount1COB);
    supportedComponents.put("MOUNT2", mount2COB);
    try {
        // dummy container
        TestContainer dummyContainer = new TestContainer("Container", ClientType.CONTAINER, true);
        ClientInfo dummyContainerInfo = manager.login(dummyContainer);
        dummyContainer.setSupportedComponents(supportedComponents);
        try {
            Thread.sleep(STARTUP_COBS_SLEEP_TIME_MS);
        } catch (InterruptedException ie) {
        }
        TestAdministrator client = new TestAdministrator(administratorName);
        ClientInfo info = manager.login(client);
        // activate MOUNT2
        //
        URI mount2URI;
        try {
            mount2URI = new URI("MOUNT2");
            StatusHolder status = new StatusHolder();
            Component ref = manager.getComponent(info.getHandle(), mount2URI, true, status);
            assertEquals(mount2COB, ref);
            assertEquals(ComponentStatus.COMPONENT_ACTIVATED, status.getStatus());
        } catch (Exception ex) {
            fail();
        }
        manager.logout(dummyContainerInfo.getHandle());
        // try to confuse with recovery mode
        TestContainer container = new TestContainer("Container", ClientType.CONTAINER, true);
        container.setSupportedComponents(supportedComponents);
        // add Components to container
        ComponentInfo mount1COBInfo = new ComponentInfo(HandleConstants.COMPONENT_MASK + 1, "MOUNT1", "IDL:alma/MOUNT_ACS/Mount:1.0", "acsexmplMount", mount1COB);
        mount1COBInfo.setInterfaces(mount1COB.implementedInterfaces());
        mount1COBInfo.setContainer(dummyContainerInfo.getHandle());
        mount1COBInfo.setContainerName(dummyContainerInfo.getName());
        container.getActivatedComponents().put(new Integer(mount1COBInfo.getHandle()), mount1COBInfo);
        ComponentInfo mount2COBInfo = new ComponentInfo(HandleConstants.COMPONENT_MASK + 2, "MOUNT2", "IDL:alma/MOUNT_ACS/Mount:1.0", "acsexmplMount", mount2COB);
        mount2COBInfo.setInterfaces(mount2COB.implementedInterfaces());
        mount2COBInfo.setContainer(dummyContainerInfo.getHandle());
        mount2COBInfo.setContainerName(dummyContainerInfo.getName());
        container.getActivatedComponents().put(new Integer(mount2COBInfo.getHandle()), mount2COBInfo);
        // container login
        ClientInfo containerInfo = manager.login(container);
        try {
            Thread.sleep(STARTUP_COBS_SLEEP_TIME_MS);
        } catch (InterruptedException ie) {
        }
        // there should be 2 Components activated
        ComponentInfo[] infos = manager.getComponentInfo(info.getHandle(), new int[0], "*", "*", true);
        Arrays.sort(infos);
        assertEquals(2, infos.length);
        assertEquals("MOUNT1", infos[0].getName());
        assertEquals("MOUNT2", infos[1].getName());
        // container2 took over
        assertEquals(containerInfo.getHandle(), infos[0].getContainer());
        assertEquals(containerInfo.getHandle(), infos[1].getContainer());
        // manager
        assertEquals(1, infos[0].getClients().size());
        assertTrue(infos[0].getClients().contains(HandleConstants.MANAGER_MASK));
        // client only
        assertEquals(1, infos[1].getClients().size());
        assertTrue(infos[1].getClients().contains(info.getHandle()));
    } catch (AcsJNoPermissionEx e) {
        fail("No permission");
    }
}
Also used : HashMap(java.util.HashMap) URI(java.net.URI) RemoteException(com.cosylab.acs.maci.RemoteException) URISyntaxException(java.net.URISyntaxException) BadParametersException(com.cosylab.acs.maci.BadParametersException) NoResourcesException(com.cosylab.acs.maci.NoResourcesException) NoDefaultComponentException(com.cosylab.acs.maci.NoDefaultComponentException) StatusHolder(com.cosylab.acs.maci.StatusHolder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AcsJNoPermissionEx(alma.maciErrType.wrappers.AcsJNoPermissionEx) ClientInfo(com.cosylab.acs.maci.ClientInfo) ComponentInfo(com.cosylab.acs.maci.ComponentInfo) Component(com.cosylab.acs.maci.Component) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with StatusHolder

use of com.cosylab.acs.maci.StatusHolder in project ACS by ACS-Community.

the class ManagerImpl method containerPostLoginActivation.

/**
	 * Container post login activation, activate startup and unavailable components.
	 * NOTE: to be run in separate thread.
	 *
	 * @param	containerInfo	container info for which to perform post login activation.
	 * @param	recoverContainer	recovery mode flag.
	 */
private void containerPostLoginActivation(final ContainerInfo containerInfo, boolean recoverContainer) {
    // give containers some time to fully initialize
    if (containerInfo.getImplLang() == ImplLang.cpp || containerInfo.getImplLang() == ImplLang.not_specified) {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException ie) {
        }
    }
    // shutdown check
    if (isShuttingDown())
        return;
    // CDB startup
    if (cdbActivation != null && containerInfo.getName().equals(cdbActivation.getContainer())) {
        try {
            StatusHolder status = new StatusHolder();
            ComponentInfo cdbInfo = internalRequestComponent(this.getHandle(), cdbActivation.getName(), cdbActivation.getType(), cdbActivation.getCode(), cdbActivation.getContainer(), RELEASE_IMMEDIATELY, status, true);
            if (status.getStatus() != ComponentStatus.COMPONENT_ACTIVATED)
                logger.log(Level.SEVERE, "Failed to activate CDB, reason: '" + status.getStatus() + "'.");
            else if (cdbInfo == null || cdbInfo.getHandle() == 0 || cdbInfo.getComponent() == null)
                logger.log(Level.SEVERE, "Failed to activate CDB, invalid ComponentInfo returned: '" + cdbInfo + "'.");
            else {
                logger.log(Level.INFO, "CDB activated on container '" + containerInfo.getName() + "'.");
            }
        } catch (Throwable ex) {
            logger.log(Level.SEVERE, "Failed to activate CDB on container '" + containerInfo.getName() + "'.", ex);
        }
    }
    // used for fast lookups
    Map<String, Integer> activationRequests = new HashMap<String, Integer>();
    // order is important, preserve it
    ArrayList<URI> activationRequestsList = new ArrayList<URI>();
    // get CDB access daos
    DAOProxy dao = getManagerDAOProxy();
    DAOProxy componentsDAO = getComponentsDAOProxy();
    //
    if (dao != null && componentsDAO != null) {
        try {
            // query startup components
            String[] startup = dao.get_string_seq("Startup");
            final Integer managerHandle = new Integer(this.getHandle());
            for (int i = 0; i < startup.length; i++) {
                // TODO simulator test workaround
                if (startup[i].length() == 0)
                    continue;
                // read container field
                String containerName = readStringCharacteristics(componentsDAO, startup[i] + "/Container");
                if (containerName == null) {
                    logger.log(Level.WARNING, "Misconfigured CDB, there is no container of component '" + startup[i] + "' defined.");
                    continue;
                }
                // if container name matches, add activation request
                if (containerInfo.getName().equals(containerName)) {
                    try {
                        URI curl = CURLHelper.createURI(startup[i]);
                        // check CURL
                        try {
                            checkCURL(curl);
                        } catch (RuntimeException e) {
                            // @todo Auto-generated catch block
                            e.printStackTrace();
                        }
                        activationRequestsList.add(curl);
                        activationRequests.put(startup[i], managerHandle);
                    } catch (URISyntaxException usi) {
                        logger.log(Level.WARNING, "Failed to create URI from component name '" + startup[i] + "'.", usi);
                    }
                }
            }
        } catch (Throwable th) {
            logger.log(Level.WARNING, "Failed to retrieve list of startup components.", th);
        }
    }
    //
    // autostart components (<component>.Autostart attribute)
    //
    final String TRUE_STRING = "true";
    if (componentsDAO != null) {
        try {
            final Integer managerHandle = new Integer(this.getHandle());
            // get names of all components
            // TODO here to check if CDB is available
            componentsDAO.get_field_data("");
            /*String[] ids =*/
            String[] ids = getComponentsList();
            // test names
            for (int i = 0; i < ids.length; i++) {
                // read name
                //readStringCharacteristics(componentsDAO, ids[i]+"/Name");
                String name = ids[i];
                if (name == null) {
                    logger.log(Level.WARNING, "Misconfigured CDB, there is no name of component '" + ids[i] + "' defined.");
                    continue;
                }
                // read autostart silently
                String autostart = readStringCharacteristics(componentsDAO, ids[i] + "/Autostart", true);
                if (autostart == null) {
                    logger.log(Level.WARNING, "Misconfigured CDB, there is no autostart attribute of component '" + ids[i] + "' defined.");
                    continue;
                } else if (autostart.equalsIgnoreCase(TRUE_STRING) && !activationRequests.containsKey(name)) /* TODO to be removed */
                {
                    // read container silently
                    String componentContainer = readStringCharacteristics(componentsDAO, ids[i] + "/Container", true);
                    if (componentContainer == null) {
                        logger.log(Level.WARNING, "Misconfigured CDB, there is no container attribute of component '" + ids[i] + "' defined.");
                        continue;
                    } else if (!containerInfo.getName().equals(componentContainer))
                        continue;
                    try {
                        URI curl = CURLHelper.createURI(name);
                        // check CURL, no non-local curls
                        try {
                            checkCURL(curl, false);
                        } catch (RuntimeException e) {
                            reportException(e);
                        }
                        activationRequestsList.add(curl);
                        activationRequests.put(name, managerHandle);
                    } catch (URISyntaxException usi) {
                        logger.log(Level.WARNING, "Failed to create URI from component name '" + name + "'.", usi);
                    }
                }
            }
        } catch (Throwable ex) {
            logger.log(Level.WARNING, "Failed to retrieve list of components.", ex);
        }
    }
    // list of componentInfo to be cleaned up (cannot be immediately, due to lock)
    ArrayList<ComponentInfo> cleanupList = new ArrayList<ComponentInfo>();
    // check unavailable components
    if (unavailableComponents.size() > 0) {
        if (componentsDAO != null) {
            try {
                final Integer reactivateHandle = new Integer(0);
                synchronized (unavailableComponents) {
                    String[] names = unavailableComponents.keySet().toArray(new String[unavailableComponents.size()]);
                    // reverse
                    for (int i = names.length - 1; i >= 0; i--) {
                        String name = names[i];
                        boolean reactivate = false;
                        // dynamic component check
                        ComponentInfo componentInfo = unavailableComponents.get(name);
                        if (componentInfo != null && componentInfo.isDynamic() && componentInfo.getDynamicContainerName() != null && componentInfo.getDynamicContainerName().equals(containerInfo.getName())) {
                            // reactivate dynamic component
                            reactivate = true;
                        } else {
                            // read container field
                            String containerName = readStringCharacteristics(componentsDAO, name + "/Container");
                            if (containerName == null) {
                                logger.log(Level.WARNING, "Misconfigured CDB, there is no container of component '" + name + "' defined.");
                            //continue;
                            } else // if container name matches, add (override) activation request
                            if (containerInfo.getName().equals(containerName)) {
                                reactivate = true;
                            }
                        }
                        if (reactivate) {
                            // clean up if in non-recovery mode
                            if (!recoverContainer) {
                                // and if not already in activation list (startup component)
                                if (!activationRequests.containsKey(name)) {
                                    cleanupList.add(componentInfo);
                                    continue;
                                }
                            }
                            // this Component needs reactivation
                            if (activationRequests.containsKey(name)) {
                                activationRequests.put(name, reactivateHandle);
                            } else // put to activation list
                            {
                                try {
                                    activationRequestsList.add(CURLHelper.createURI(name));
                                    activationRequests.put(name, reactivateHandle);
                                } catch (URISyntaxException usi) {
                                    logger.log(Level.WARNING, "Failed to create URI from component name '" + name + "'.", usi);
                                }
                            }
                        }
                    }
                }
            } catch (Throwable ex) {
                CoreException ce = new CoreException("Failed to obtain component data from the CDB.", ex);
                reportException(ce);
            }
        }
    }
    if (cleanupList.size() > 0) {
        Iterator<ComponentInfo> iter = cleanupList.iterator();
        while (iter.hasNext()) {
            ComponentInfo componentInfo = iter.next();
            componentsLock.lock();
            try {
                // remove from its owners list ...
                int[] owners = componentInfo.getClients().toArray();
                for (int j = 0; j < owners.length; j++) removeComponentOwner(componentInfo.getHandle(), owners[j]);
                // ... and deallocate
                executeCommand(new ComponentCommandDeallocate(componentInfo.getHandle() & HANDLE_MASK, componentInfo.getHandle(), WhyUnloadedReason.REMOVED));
                executeCommand(new UnavailableComponentCommandRemove(componentInfo.getName()));
                // remove component from container component list
                synchronized (containerInfo.getComponents()) {
                    if (containerInfo.getComponents().contains(componentInfo.getHandle()))
                        executeCommand(new ContainerInfoCommandComponentRemove(containerInfo.getHandle() & HANDLE_MASK, componentInfo.getHandle()));
                }
            } finally {
                componentsLock.unlock();
            }
        // unbind from remote directory
        //unbind(convertToHiearachical(componentInfo.getName()), "O");
        }
    }
    logger.log(Level.INFO, "Container '" + containerInfo.getName() + "' startup statistics: " + activationRequestsList.size() + " components queued to be activated.");
    // send message to the container
    sendMessage(containerInfo.getContainer(), "Startup statistics: " + activationRequestsList.size() + " components queued to be activated.", MessageType.MSG_INFORMATION, ClientOperations.MSGID_AUTOLOAD_START);
    // activate startup components
    int activated = 0;
    StatusHolder status = new StatusHolder();
    Iterator<URI> iterator = activationRequestsList.iterator();
    while (iterator.hasNext()) {
        URI uri = iterator.next();
        try {
            String name = extractName(uri);
            int requestor = activationRequests.get(name);
            internalRequestComponent(requestor, uri, status);
            if (status.getStatus() != ComponentStatus.COMPONENT_ACTIVATED)
                logger.log(Level.WARNING, "Failed to activate autostart component '" + uri + "', reason: '" + status.getStatus() + "'.");
            else
                activated++;
        } catch (Throwable ex) {
            logger.log(Level.WARNING, "Failed to activate autostart component '" + uri + "'.", ex);
        }
    }
    logger.log(Level.INFO, "Container '" + containerInfo.getName() + "' startup statistics: " + activated + " of " + activationRequestsList.size() + " components activated.");
    // send message to the container
    sendMessage(containerInfo.getContainer(), "Startup statistics: " + activated + " of " + activationRequestsList.size() + " components activated.", MessageType.MSG_INFORMATION, ClientOperations.MSGID_AUTOLOAD_END);
    // notify about new container login
    synchronized (containerLoggedInMonitor) {
        containerLoggedInMonitor.notifyAll();
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) UnavailableComponentCommandRemove(com.cosylab.acs.maci.manager.recovery.UnavailableComponentCommandRemove) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) StatusHolder(com.cosylab.acs.maci.StatusHolder) ContainerInfoCommandComponentRemove(com.cosylab.acs.maci.manager.recovery.ContainerInfoCommandComponentRemove) DAOProxy(com.cosylab.cdb.client.DAOProxy) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CoreException(com.cosylab.acs.maci.CoreException) ComponentCommandDeallocate(com.cosylab.acs.maci.manager.recovery.ComponentCommandDeallocate) ComponentInfo(com.cosylab.acs.maci.ComponentInfo)

Example 8 with StatusHolder

use of com.cosylab.acs.maci.StatusHolder in project ACS by ACS-Community.

the class ManagerImpl method internalRequestDefaultComponent.

/**
	 * Internal method for requesting default components.
	 * @param	requestor	requestor of the component.
	 * @param	typr		type of the component
	 * @return	componentInfo	<code>ComponentInfo</code> of requested default component.
	 */
private ComponentInfo internalRequestDefaultComponent(int requestor, String type) throws NoDefaultComponentException {
    String defaultComponentName = null;
    ComponentInfo defaultComponentInfo = null;
    // first check default components table
    synchronized (defaultComponents) {
        defaultComponentInfo = defaultComponents.get(type);
    }
    if (defaultComponentInfo != null)
        defaultComponentName = defaultComponentInfo.getName();
    // if not found, search for the default component in the CDB
    if (defaultComponentName == null) {
        DAOProxy componentsDAO = getComponentsDAOProxy();
        if (componentsDAO != null) {
            try {
                // get names of all components
                // @todo here to check if CDB is available
                componentsDAO.get_field_data("");
                /*String[] ids =*/
                String[] ids = getComponentsList();
                // test names
                for (int i = 0; i < ids.length; i++) {
                    // read name
                    //readStringCharacteristics(componentsDAO, ids[i]+"/Name");
                    String name = ids[i];
                    if (name == null) {
                        logger.log(Level.WARNING, "Misconfigured CDB, there is no type of component '" + ids[i] + "' defined.");
                        continue;
                    }
                    // do not search dynamic components (they cannot be marked as default in CDB anyway)
                    if (!name.equals(ComponentSpec.COMPSPEC_ANY)) {
                        // read type
                        String componentType = readStringCharacteristics(componentsDAO, ids[i] + "/Type");
                        if (type == null) {
                            logger.log(Level.WARNING, "Misconfigured CDB, there is no type of component '" + name + "' defined.");
                            continue;
                        }
                        // test type
                        final String TRUE_STRING = "true";
                        if (type.equals(componentType)) {
                            // check if it is default, read silently
                            String isDefault = readStringCharacteristics(componentsDAO, ids[i] + "/Default", true);
                            if (isDefault == null || !isDefault.equalsIgnoreCase(TRUE_STRING))
                                continue;
                            // got the match
                            defaultComponentName = name;
                            break;
                        }
                    }
                }
            } catch (Throwable ex) {
                CoreException ce = new CoreException("Failed to obtain component data from the CDB.", ex);
                reportException(ce);
            }
        }
    }
    // if found get the component
    if (defaultComponentInfo != null) {
        try {
            StatusHolder status = new StatusHolder();
            ContainerInfo containerInfo = getContainerInfo(defaultComponentInfo.getContainer());
            if (containerInfo == null) {
                CoreException huse = new CoreException("Failed to return default component: '" + defaultComponentName + "', container with '" + HandleHelper.toString(defaultComponentInfo.getContainer()) + "' not logged in.");
                reportException(huse);
                return null;
            }
            ComponentInfo componentInfo = internalRequestComponent(requestor, defaultComponentInfo.getName(), defaultComponentInfo.getType(), defaultComponentInfo.getCode(), containerInfo.getName(), RELEASE_IMMEDIATELY, status, true);
            if (componentInfo == null || status.getStatus() != ComponentStatus.COMPONENT_ACTIVATED) {
                CoreException huse = new CoreException("Failed to obtain default component: '" + defaultComponentName + "'.");
                reportException(huse);
                // no error handling...
                return null;
            }
            return componentInfo;
        } catch (Throwable t) {
            CoreException huse = new CoreException("Failed to return default component: '" + defaultComponentName + "'.", t);
            reportException(huse);
            return null;
        }
    } else if (defaultComponentName != null) {
        // create CURL
        URI curl = null;
        try {
            curl = CURLHelper.createURI(defaultComponentName);
        } catch (URISyntaxException use) {
            CoreException huse = new CoreException("Failed to create CURL from default component name: '" + defaultComponentName + "'.", use);
            reportException(huse);
            return null;
        }
        try {
            // request for component
            StatusHolder status = new StatusHolder();
            Component component = internalRequestComponent(requestor, curl, status, true);
            if (component == null || status.getStatus() != ComponentStatus.COMPONENT_ACTIVATED) {
                CoreException huse = new CoreException("Failed to obtain default component: '" + defaultComponentName + "'.");
                reportException(huse);
                return null;
            }
            // return component info
            ComponentInfo[] componentInfo = getComponentInfo(requestor, new int[0], defaultComponentName, type, true);
            if (componentInfo == null || componentInfo.length != 1) {
                CoreException huse = new CoreException("Failed to obtain activated default component ComponentInfo: '" + defaultComponentName + "'.");
                reportException(huse);
                return null;
            } else
                return componentInfo[0];
        } catch (Throwable t) {
            CoreException huse = new CoreException("Failed to return default component: '" + defaultComponentName + "'.", t);
            reportException(huse);
            return null;
        }
    }
    // not found
    NoDefaultComponentException ndce = new NoDefaultComponentException("No default component for type '" + type + "' found.");
    throw ndce;
}
Also used : URISyntaxException(java.net.URISyntaxException) DAOProxy(com.cosylab.cdb.client.DAOProxy) URI(java.net.URI) NoDefaultComponentException(com.cosylab.acs.maci.NoDefaultComponentException) StatusHolder(com.cosylab.acs.maci.StatusHolder) CoreException(com.cosylab.acs.maci.CoreException) ContainerInfo(com.cosylab.acs.maci.ContainerInfo) ComponentInfo(com.cosylab.acs.maci.ComponentInfo) Component(com.cosylab.acs.maci.Component)

Example 9 with StatusHolder

use of com.cosylab.acs.maci.StatusHolder in project ACS by ACS-Community.

the class ManagerImpl method internalRequestDynamicComponent.

/**
	 * Internal method for requesting dynamic components.
	 *
	 * Resolution:
	 * <code>component_name</code> and <code>component_type</code> can be considered as "determinator" fields,
	 * they play important role in search algorithm.
	 * <code>component_code</code> and <code>container_name</code> can be considered as "override" fields,
	 * they only help to find closest match.
	 * Rule: unspecified <code>component_name</code> case implies that a new component will be activated.
	 * Search points (8,4,2,1): <code>component_name</code>, <code>component_type</code>, <code>component_code</code>, <code>container_name</code>.
	 * <pre>
	 *
	 *  name | type | search criteria
	 * -----------------------------
	 *    *  |   *  | throw IncompleteComponentSpecException
	 *    X  |   *  | (equals, wildcard)
	 *    *  |   X  | (equals, equals) w/ name generation
	 *    X  |   X  | (wildcard, equals) - overriding type is not allowed
	 *
	 * </pre>
	 * 'name' can be also something like "ANT1/*" (ends with) and is threated just like "*".
	 *
	 * @param	requestor	requestor of the component.
	 * @param	componentSpec	requested component <code>ComponentSpec</code>
	 * @return	componentInfo	<code>ComponentInfo</code> of requested dynamic component.
	 */
private ComponentInfo internalRequestDynamicComponent(int requestor, ComponentSpec componentSpec) throws AcsJCannotGetComponentEx, AcsJSyncLockFailedEx, AcsJNoPermissionEx, AcsJIncompleteComponentSpecEx, AcsJInvalidComponentSpecEx, AcsJComponentSpecIncompatibleWithActiveComponentEx {
    boolean unspecifiedName = componentSpec.getName().endsWith(ComponentSpec.COMPSPEC_ANY);
    boolean unspecifiedType = componentSpec.getType().equals(ComponentSpec.COMPSPEC_ANY);
    //   *  |   *  | throw IncompleteComponentSpecException
    if (unspecifiedName && unspecifiedType) {
        AcsJInvalidComponentSpecEx ex = new AcsJInvalidComponentSpecEx();
        ex.setReason("'name' and 'type' cannot be both '" + ComponentSpec.COMPSPEC_ANY + "'.");
        throw ex;
    } else // all fields are fully specified, no search needed
    if (!unspecifiedName && !unspecifiedType && !componentSpec.getCode().equals(ComponentSpec.COMPSPEC_ANY) && !componentSpec.getContainer().equals(ComponentSpec.COMPSPEC_ANY)) {
        StatusHolder statusHolder = new StatusHolder();
        // We let exceptions occurring here fly up
        return internalRequestComponent(requestor, componentSpec.getName(), componentSpec.getType(), componentSpec.getCode(), componentSpec.getContainer(), RELEASE_TIME_UNDEFINED, statusHolder, true);
    }
    //
    // prepare search conditions
    //
    final String[] fieldNames = new String[] { "Name", "Type", "Code", "Container" };
    final String[] requiredValues = new String[] { componentSpec.getName(), componentSpec.getType(), componentSpec.getCode(), componentSpec.getContainer() };
    final int[] equalityPoints = new int[] { 8, 4, /* never used */
    2, 1 };
    boolean[] equalityRequired = null;
    boolean allowNameGeneration = false;
    boolean prohibitSearch = false;
    //   X  |   X  | (wildcard, equals)
    if (!unspecifiedName && !unspecifiedType) {
        equalityRequired = new boolean[] { false, true, false, false };
        allowNameGeneration = true;
    } else //   X  |   *  | (equals, wildcard)
    if (!unspecifiedName && unspecifiedType) {
        equalityRequired = new boolean[] { true, false, false, false };
    } else //  prefix* |   X  | (equals, equals) w/ name generation
    if (unspecifiedName && !unspecifiedType) {
        equalityRequired = new boolean[] { true, true, false, false };
        // no search needed case...
        if (!componentSpec.getCode().equals(ComponentSpec.COMPSPEC_ANY) && !componentSpec.getContainer().equals(ComponentSpec.COMPSPEC_ANY))
            prohibitSearch = true;
        allowNameGeneration = true;
    }
    // search
    IntHolder keepAliveTimeHolder = new IntHolder(RELEASE_TIME_UNDEFINED);
    String[] result = prohibitSearch ? null : searchDynamicComponent(fieldNames, requiredValues, equalityRequired, equalityPoints, keepAliveTimeHolder);
    // none found
    if (result == null) {
        boolean failed = true;
        // only name or container not speficied...
        if ((allowNameGeneration || !unspecifiedName) && !unspecifiedType && !componentSpec.getCode().equals(ComponentSpec.COMPSPEC_ANY)) {
            // container name already specified, i.e. name is *, which is OK
            if (!componentSpec.getContainer().equals(ComponentSpec.COMPSPEC_ANY)) {
                result = new String[] { componentSpec.getName(), componentSpec.getType(), componentSpec.getCode(), componentSpec.getContainer() };
                failed = false;
            } else // container name is *, use load balancing if available
            if (loadBalancingStrategy != null) {
                String containerName = loadBalancingStrategy.selectContainer(getClientInfo(requestor), getContainersInfo());
                if (containerName != null) {
                    result = new String[] { componentSpec.getName(), componentSpec.getType(), componentSpec.getCode(), containerName };
                    failed = false;
                }
            }
        }
        if (failed) {
            AcsJInvalidComponentSpecEx ex = new AcsJInvalidComponentSpecEx();
            ex.setReason("Requested ComponentSpec does not match any entry in the CDB.");
            throw ex;
        }
    }
    // override...
    for (int i = 0; i < result.length; i++) if (!requiredValues[i].equals(ComponentSpec.COMPSPEC_ANY))
        result[i] = requiredValues[i];
    // check completeness
    int i = 0;
    if (allowNameGeneration)
        i++;
    for (; i < result.length; i++) if (result[i].equals(ComponentSpec.COMPSPEC_ANY)) {
        // if load balancing strategy is registered, use it to determine container name
        if (fieldNames[i].equals("Container") && loadBalancingStrategy != null) {
            String containerName = loadBalancingStrategy.selectContainer(getClientInfo(requestor), getContainersInfo());
            if (containerName != null) {
                result[i] = containerName;
                continue;
            }
        }
        AcsJIncompleteComponentSpecEx ex = new AcsJIncompleteComponentSpecEx();
        ex.setReason("'" + fieldNames[i] + "' equals '" + ComponentSpec.COMPSPEC_ANY + "'.");
        throw ex;
    }
    // generate name if necessary
    if (allowNameGeneration && result[0].endsWith(ComponentSpec.COMPSPEC_ANY)) {
        synchronized (this) {
            /// @todo not perfect
            if (result[0].equals(ComponentSpec.COMPSPEC_ANY))
                result[0] = result[1] + "_" + System.currentTimeMillis();
            else
                // ends with case
                result[0] = result[0].substring(0, result[0].length() - 1) + "_" + System.currentTimeMillis();
            // flatten hierarchical name (remove IDL separators)
            if (result[0].indexOf('/') >= 0)
                result[0] = result[0].replaceAll("/", "_");
        }
    }
    StatusHolder statusHolder = new StatusHolder();
    // Same exceptions are let flying up
    return internalRequestComponent(requestor, result[0], result[1], result[2], result[3], keepAliveTimeHolder.value, statusHolder, true);
}
Also used : AcsJInvalidComponentSpecEx(alma.maciErrType.wrappers.AcsJInvalidComponentSpecEx) IntHolder(org.omg.CORBA.IntHolder) StatusHolder(com.cosylab.acs.maci.StatusHolder) AcsJIncompleteComponentSpecEx(alma.maciErrType.wrappers.AcsJIncompleteComponentSpecEx)

Example 10 with StatusHolder

use of com.cosylab.acs.maci.StatusHolder in project ACS by ACS-Community.

the class ManagerImpl method internalNoSyncRequestComponent.

/**
	 * Internal method for requesting components (non sync).
	 * @param	requestor		requestor of the component.
	 * @param	name			name of component to be requested, non-<code>null</code>.
	 * @param	type			type of component to be requested; if <code>null</code> CDB will be queried.
	 * @param	code			code of component to be requested; if <code>null</code> CDB will be queried.
	 * @param	containerName	container name of component to be requested; if <code>null</code> CDB will be queried.
	 * @param	status			returned completion status of the request.
	 * @param	activate		<code>true</code> if component has to be activated
	 * @return	componentInfo	<code>ComponentInfo</code> of requested component.
	 */
private ComponentInfo internalNoSyncRequestComponent(int requestor, String name, String type, String code, String containerName, int keepAliveTime, StatusHolder status, boolean activate) throws AcsJCannotGetComponentEx, AcsJComponentSpecIncompatibleWithActiveComponentEx {
    AcsJCannotGetComponentEx bcex = null;
    if (name == null) {
        bcex = new AcsJCannotGetComponentEx();
        bcex.setReason("Cannot activate component with NULL name.");
        throw bcex;
    }
    if (status == null) {
        bcex = new AcsJCannotGetComponentEx();
        bcex.setReason("Component " + name + " has NULL status.");
        throw bcex;
    }
    boolean isOtherDomainComponent = name.startsWith(CURL_URI_SCHEMA);
    boolean isDynamicComponent = isOtherDomainComponent ? false : (type != null || code != null || containerName != null);
    //
    // check if component is already activated
    //
    int h;
    // if true, component with handle h will be reactivated
    boolean reactivate = false;
    ComponentInfo componentInfo = null;
    componentsLock.lock();
    try {
        h = components.first();
        while (h != 0) {
            componentInfo = (ComponentInfo) components.get(h);
            if (componentInfo.getName().equals(name)) {
                // check if component is unavailable
                synchronized (unavailableComponents) {
                    if (unavailableComponents.containsKey(name)) {
                        // try to reactivate, possible component reallocation
                        reactivate = true;
                    }
                }
                // check for consistency
                ContainerInfo containerInfo = getContainerInfo(componentInfo.getContainer());
                if ((type != null && !componentInfo.getType().equals(type)) || (code != null && componentInfo.getCode() != null && !componentInfo.getCode().equals(code)) || (!reactivate && containerInfo != null && containerName != null && !containerInfo.getName().equals(containerName))) {
                    AcsJComponentSpecIncompatibleWithActiveComponentEx ciwace = new AcsJComponentSpecIncompatibleWithActiveComponentEx();
                    ciwace.setCURL(componentInfo.getName());
                    ciwace.setComponentType(componentInfo.getType());
                    ciwace.setComponentCode(componentInfo.getCode() != null ? componentInfo.getCode() : "<unknown>");
                    ciwace.setContainerName(containerInfo != null ? containerInfo.getName() : "<none>");
                    throw ciwace;
                }
                if (activate) {
                    // bail out and reactivate
                    if (reactivate)
                        break;
                    // add client/component as an owner (if requestor is not 'reactivation')
                    if (requestor != 0) {
                        // !!! ACID
                        if (!componentInfo.getClients().contains(requestor))
                            executeCommand(new ComponentCommandClientAdd(componentInfo.getHandle() & HANDLE_MASK, requestor));
                    //componentInfo.getClients().add(requestor);
                    }
                    // add component to client component list (if requestor is not manager or 'reactivation')
                    if (requestor != this.getHandle() && requestor != 0)
                        addComponentOwner(componentInfo.getHandle(), requestor);
                    // inform administrators about component request
                    notifyComponentRequested(new int[] { requestor }, new int[] { componentInfo.getHandle() }, System.currentTimeMillis());
                    // on complete system shutdown sort will be done anyway
                    if ((requestor & TYPE_MASK) == COMPONENT_MASK) {
                        ComponentInfo requestorComponentInfo = getComponentInfo(requestor);
                        if (requestorComponentInfo != null && requestorComponentInfo.getContainerName() != null && requestorComponentInfo.getContainerName().equals(componentInfo.getContainerName()))
                            topologySortManager.notifyTopologyChange(componentInfo.getContainer());
                    }
                    // return info
                    status.setStatus(ComponentStatus.COMPONENT_ACTIVATED);
                    return componentInfo;
                } else {
                    if (reactivate)
                        status.setStatus(ComponentStatus.COMPONENT_NOT_ACTIVATED);
                    else
                        status.setStatus(ComponentStatus.COMPONENT_ACTIVATED);
                    return componentInfo;
                }
            }
            h = components.next(h);
        }
    } finally {
        componentsLock.unlock();
    }
    // and do not touch CDB
    if (reactivate && componentInfo.isDynamic()) {
        if (componentInfo.getType() == null || componentInfo.getCode() == null || componentInfo.getDynamicContainerName() == null) {
            // failed
            bcex = new AcsJCannotGetComponentEx();
            bcex.setReason("Failed to reactivate dynamic component '" + componentInfo + "'.");
            status.setStatus(ComponentStatus.COMPONENT_DOES_NO_EXIST);
            throw bcex;
        } else {
            // reread info
            type = componentInfo.getType();
            code = componentInfo.getCode();
            containerName = componentInfo.getDynamicContainerName();
            keepAliveTime = componentInfo.getKeepAliveTime();
        }
    } else // is CDB lookup needed
    if (!isOtherDomainComponent && (type == null || code == null || containerName == null)) {
        //
        // read component info from CDB / remote directory lookup
        //
        DAOProxy dao = getComponentsDAOProxy();
        if (dao == null || readStringCharacteristics(dao, name, true) == null) {
            // component with this name does not exists,
            // make a remote directory lookup
            Object ref = lookup(name, null);
            if (ref != null) {
                // found
                status.setStatus(ComponentStatus.COMPONENT_ACTIVATED);
                return new ComponentInfo(0, name, null, null, new ServiceComponent(ref));
            } else {
                // not found
                bcex = new AcsJCannotGetComponentEx();
                bcex.setReason("Component " + name + " not found in CDB.");
                status.setStatus(ComponentStatus.COMPONENT_DOES_NO_EXIST);
                throw bcex;
            }
        }
        if (code == null) {
            code = readStringCharacteristics(dao, name + "/Code");
            if (code == null) {
                bcex = new AcsJCannotGetComponentEx();
                bcex.setReason("Misconfigured CDB, there is no code of component '" + name + "' defined.");
                status.setStatus(ComponentStatus.COMPONENT_DOES_NO_EXIST);
                throw bcex;
            }
        }
        if (type == null) {
            type = readStringCharacteristics(dao, name + "/Type");
            if (type == null) {
                bcex = new AcsJCannotGetComponentEx();
                bcex.setReason("Misconfigured CDB, there is no type of component '" + name + "' defined.");
                status.setStatus(ComponentStatus.COMPONENT_DOES_NO_EXIST);
                throw bcex;
            }
        }
        if (containerName == null) {
            containerName = readStringCharacteristics(dao, name + "/Container");
            if (containerName == null) {
                bcex = new AcsJCannotGetComponentEx();
                bcex.setReason("Misconfigured CDB, there is no container of component '" + name + "' defined.");
                status.setStatus(ComponentStatus.COMPONENT_DOES_NO_EXIST);
                throw bcex;
            }
        }
        if (keepAliveTime == RELEASE_TIME_UNDEFINED) {
            // defaults to 0 == RELEASE_IMMEDIATELY
            keepAliveTime = readLongCharacteristics(dao, name + "/KeepAliveTime", RELEASE_IMMEDIATELY, true);
        }
    }
    // we have keepAlive missing, try to get it
    if (keepAliveTime == RELEASE_TIME_UNDEFINED) {
        DAOProxy dao = getComponentsDAOProxy();
        if (dao != null) {
            // defaults to 0 == RELEASE_IMMEDIATELY
            keepAliveTime = readLongCharacteristics(dao, name + "/KeepAliveTime", RELEASE_IMMEDIATELY, true);
        } else {
            // this is a case where all data for dynamic component is specified and there is not entry in CDB
            keepAliveTime = RELEASE_IMMEDIATELY;
        }
    }
    // read impl. language.
    DAOProxy dao = getComponentsDAOProxy();
    String componentImplLang = null;
    if (dao != null) {
        // silent read
        componentImplLang = readStringCharacteristics(dao, name + "/ImplLang", true);
    }
    // if requestor did not request activation we are finished
    if (!activate) {
        status.setStatus(ComponentStatus.COMPONENT_NOT_ACTIVATED);
        return null;
    }
    /****************** component activation ******************/
    //
    // get container/remote manager
    //
    Container container = null;
    ContainerInfo containerInfo = null;
    Manager remoteManager = null;
    if (isOtherDomainComponent) {
        // @todo MF do the login?
        try {
            String domainName = CURLHelper.createURI(name).getAuthority();
            remoteManager = getManagerForDomain(domainName);
            if (remoteManager == null) {
                bcex = new AcsJCannotGetComponentEx();
                bcex.setReason("Failed to obtain manager for domain '" + domainName + "'.");
                throw bcex;
            }
        } catch (Throwable th) {
            bcex = new AcsJCannotGetComponentEx(th);
            bcex.setReason("Failed to obtain non-local manager required by component '" + name + "'.'");
            status.setStatus(ComponentStatus.COMPONENT_NOT_ACTIVATED);
            throw bcex;
        }
    } else {
        // search for container by its name
        containerInfo = getContainerInfo(containerName);
        // try to start-up container
        if (containerInfo == null)
            containerInfo = startUpContainer(containerName);
        // check state and get container
        if (containerInfo != null) {
            checkContainerShutdownState(containerInfo);
            container = containerInfo.getContainer();
        }
        // required container is not logged in
        if (container == null) {
            bcex = new AcsJCannotGetComponentEx();
            bcex.setReason("Container '" + containerName + "' required by component '" + name + "' is not logged in.");
            status.setStatus(ComponentStatus.COMPONENT_NOT_ACTIVATED);
            throw bcex;
        }
    }
    // check container vs component ImplLang
    ImplLang containerImplLang = containerInfo.getImplLang();
    if (containerImplLang != null && containerImplLang != ImplLang.not_specified) {
        if (componentImplLang != null && ImplLang.fromString(componentImplLang) != containerImplLang) {
            AcsJCannotGetComponentEx af = new AcsJCannotGetComponentEx();
            af.setReason("Component and container implementation language do not match (" + componentImplLang + " != " + containerImplLang.name() + ")");
            throw af;
        }
    }
    //
    // get handle
    //
    // obtain handle
    componentsLock.lock();
    try {
        // only preallocate (if necessary)
        if (!reactivate) {
            // !!! ACID 2
            Integer objHandle = (Integer) executeCommand(new ComponentCommandPreallocate());
            h = (objHandle == null) ? 0 : objHandle.intValue();
        //h = components.preallocate();
        }
        // failed to obtain handle
        if (h == 0) {
            AcsJCannotGetComponentEx af = new AcsJCannotGetComponentEx();
            af.setReason("Preallocation of new handle failed, too many registered components.");
            throw af;
        }
        // create temporary ComponentInfo - to allow hierarchical components
        if (!reactivate) {
            ComponentInfo data = new ComponentInfo(h | COMPONENT_MASK, name, type, code, null);
            data.setKeepAliveTime(keepAliveTime);
            // !!! ACID
            executeCommand(new ComponentCommandSet(h, data));
            // add to pending activation list
            synchronized (pendingActivations) {
                pendingActivations.put(name, data);
            }
            // add component to client component list to allow dependency checks
            if ((requestor & TYPE_MASK) == COMPONENT_MASK)
                addComponentOwner(data.getHandle(), requestor);
        }
    } finally {
        componentsLock.unlock();
    }
    //
    // invoke get_component
    //
    componentInfo = null;
    long executionId = 0;
    long activationTime = 0;
    boolean timeoutError = false;
    if (isOtherDomainComponent) {
        try {
            URI curlName = CURLHelper.createURI(name);
            StatusHolder statusHolder = new StatusHolder();
            // @todo MF tmp (handle)
            remoteManager.getComponent(INTERDOMAIN_MANAGER_HANDLE, curlName, true, statusHolder);
            activationTime = System.currentTimeMillis();
            if (statusHolder.getStatus() == ComponentStatus.COMPONENT_ACTIVATED) {
                // local name to be used
                String localName = curlName.getPath();
                if (localName.charAt(0) == '/')
                    localName = localName.substring(1);
                /// @TODO MF tmp (handle)
                ComponentInfo[] infos = remoteManager.getComponentInfo(INTERDOMAIN_MANAGER_HANDLE, new int[0], localName, "*", true);
                if (infos != null && infos.length == 1) {
                    componentInfo = infos[0];
                    // fix container name
                    componentInfo.setContainerName(CURL_URI_SCHEMA + curlName.getAuthority() + "/" + componentInfo.getContainerName());
                }
            //else
            //    throw new RemoteException("Failed to obtain component info for '"+name+"' from remote manager.");
            }
        //else
        //    throw new RemoteException("Failed to obtain component '"+name+"' from remote manager, status: " + statusHolder.getStatus() + ".");
        } catch (Throwable ex) {
            bcex = new AcsJCannotGetComponentEx(ex);
            bcex.setReason("Failed to obtain component '" + name + "' from remote manager.");
            timeoutError = (ex instanceof TimeoutRemoteException);
        }
    } else {
        //
        // invoke get_component on container
        //
        // log info
        String handleReadable = HandleHelper.toString(h | COMPONENT_MASK);
        logger.log(Level.INFO, "Activating component '" + name + "' (" + handleReadable + ") on container '" + containerInfo.getName() + "'.");
        boolean callSyncActivate = System.getProperties().containsKey(NAME_SYNC_ACTIVATE);
        if (callSyncActivate) {
            // sync
            try {
                executionId = generateExecutionId();
                activationTime = System.currentTimeMillis();
                componentInfo = container.activate_component(h | COMPONENT_MASK, executionId, name, code, type);
            } catch (Throwable ex) {
                bcex = new AcsJCannotGetComponentEx(ex);
                bcex.setReason("Failed to activate component '" + name + "' on container '" + containerName + "'.");
                timeoutError = (ex instanceof TimeoutRemoteException);
            }
        } else {
            // async
            try {
                executionId = generateExecutionId();
                activationTime = System.currentTimeMillis();
                ComponentInfoCompletionCallbackImpl callback = new ComponentInfoCompletionCallbackImpl(requestor, name, type, code, containerName, keepAliveTime, status, isOtherDomainComponent, isDynamicComponent, h, reactivate, container, containerInfo, executionId, activationTime);
                addPendingContainerAsyncRequest(containerName, callback);
                try {
                    container.activate_component_async(h | COMPONENT_MASK, executionId, name, code, type, callback);
                } catch (Throwable t) {
                    // failed call, remove async request from the list
                    removePendingContainerAsyncRequest(containerName, callback);
                    throw t;
                }
                logger.log(AcsLogLevel.DELOUSE, "Asynchronous activation of component '" + name + "' (" + handleReadable + ") is running on container '" + containerInfo.getName() + "'.");
                ComponentInfo ret;
                try {
                    ret = callback.waitUntilActivated(getLockTimeout());
                } catch (Throwable t) {
                    // failed call (most likely timeout), remove async request from the list
                    removePendingContainerAsyncRequest(containerName, callback);
                    throw t;
                }
                logger.log(AcsLogLevel.DELOUSE, "Asynchronous activation of component '" + name + "' (" + handleReadable + ") has finished on container '" + containerInfo.getName() + "'.");
                return ret;
            } catch (Throwable ex) {
                bcex = new AcsJCannotGetComponentEx(ex);
                bcex.setReason("Failed to activate component '" + name + "' on container '" + containerName + "'.");
                throw bcex;
            }
        }
    }
    // call this immediately if bcex != null or sync call
    return internalNoSyncRequestComponentPhase2(requestor, name, type, code, containerName, keepAliveTime, status, bcex, isOtherDomainComponent, isDynamicComponent, h, reactivate, componentInfo, container, containerInfo, executionId, activationTime, timeoutError);
}
Also used : AcsJComponentSpecIncompatibleWithActiveComponentEx(alma.maciErrType.wrappers.AcsJComponentSpecIncompatibleWithActiveComponentEx) ComponentCommandClientAdd(com.cosylab.acs.maci.manager.recovery.ComponentCommandClientAdd) DAOProxy(com.cosylab.cdb.client.DAOProxy) Manager(com.cosylab.acs.maci.Manager) URI(java.net.URI) AcsJCannotGetComponentEx(alma.maciErrType.wrappers.AcsJCannotGetComponentEx) StatusHolder(com.cosylab.acs.maci.StatusHolder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Container(com.cosylab.acs.maci.Container) ComponentCommandSet(com.cosylab.acs.maci.manager.recovery.ComponentCommandSet) ContainerInfo(com.cosylab.acs.maci.ContainerInfo) TimeoutRemoteException(com.cosylab.acs.maci.TimeoutRemoteException) ComponentInfo(com.cosylab.acs.maci.ComponentInfo) ImplLang(com.cosylab.acs.maci.ImplLang) ComponentCommandPreallocate(com.cosylab.acs.maci.manager.recovery.ComponentCommandPreallocate)

Aggregations

StatusHolder (com.cosylab.acs.maci.StatusHolder)24 URI (java.net.URI)23 Component (com.cosylab.acs.maci.Component)19 URISyntaxException (java.net.URISyntaxException)19 AcsJNoPermissionEx (alma.maciErrType.wrappers.AcsJNoPermissionEx)18 BadParametersException (com.cosylab.acs.maci.BadParametersException)17 NoResourcesException (com.cosylab.acs.maci.NoResourcesException)17 ClientInfo (com.cosylab.acs.maci.ClientInfo)16 NoDefaultComponentException (com.cosylab.acs.maci.NoDefaultComponentException)16 RemoteException (com.cosylab.acs.maci.RemoteException)16 HashMap (java.util.HashMap)16 ComponentInfo (com.cosylab.acs.maci.ComponentInfo)15 Map (java.util.Map)15 AcsJCannotGetComponentEx (alma.maciErrType.wrappers.AcsJCannotGetComponentEx)8 AcsJBadParameterEx (alma.ACSErrTypeCommon.wrappers.AcsJBadParameterEx)6 CoreException (com.cosylab.acs.maci.CoreException)5 DAOProxy (com.cosylab.cdb.client.DAOProxy)4 AcsJComponentSpecIncompatibleWithActiveComponentEx (alma.maciErrType.wrappers.AcsJComponentSpecIncompatibleWithActiveComponentEx)3 AcsJIncompleteComponentSpecEx (alma.maciErrType.wrappers.AcsJIncompleteComponentSpecEx)3 AcsJInvalidComponentSpecEx (alma.maciErrType.wrappers.AcsJInvalidComponentSpecEx)3