Search in sources :

Example 1 with Manager

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

the class ManagerImpl method getComponentInfo.

/**
	 * @see com.cosylab.acs.maci.Manager#getComponentInfo(int, int[], String, String, boolean)
	 */
// TODO MF all (using wildchars match for domain names) interdomain queries
public ComponentInfo[] getComponentInfo(int id, int[] handles, String name_wc, String type_wc, boolean activeOnly) throws AcsJNoPermissionEx {
    if (handles == null) {
        // BAD_PARAM
        BadParametersException af = new BadParametersException("Non-null 'handles' sequence expected.");
        throw af;
    } else if (handles.length == 0 && (name_wc == null || type_wc == null)) {
        // BAD_PARAM
        BadParametersException af = new BadParametersException("Non-null 'names_wc' or' type_wc' sequence expected.");
        throw af;
    }
    /****************************************************************/
    // the caller must have INTROSPECT_MANAGER access rights,
    // or it must have adequate privileges to access the component (the same as with the get_component method).
    securityCheck(id, AccessRights.NONE);
    // info to be returned
    ComponentInfo[] info = null;
    // get info of requested handles
    if (handles.length > 0) {
        info = new ComponentInfo[handles.length];
        for (int i = 0; i < handles.length; i++) {
            // access rights to be checked here...
            info[i] = getComponentInfo(handles[i]);
            // filter out unavailable
            if (info[i] != null && info[i].getComponent() == null)
                info[i] = null;
        }
    } else // use name_wc and type_wc as search criteria
    {
        // check for inter-domain search
        if (name_wc.startsWith(CURL_URI_SCHEMA)) {
            URI curl = null;
            try {
                curl = CURLHelper.createURI(name_wc);
                if (curl.getAuthority() != null && curl.getAuthority().indexOf('*') >= 0)
                    throw new IllegalArgumentException("Wildchars not supported in domain names.");
            } catch (URISyntaxException e) {
                // BAD_PARAM
                BadParametersException af = new BadParametersException("Invalid CURL syntax in 'names_wc'.");
                throw af;
            }
            name_wc = extractName(curl);
            Manager remoteManager = null;
            // if not local do inter-domain query
            if (name_wc.startsWith(CURL_URI_SCHEMA)) {
                // TODO MF do the login?
                try {
                    String domainName = curl.getAuthority();
                    remoteManager = getManagerForDomain(domainName);
                    if (remoteManager == null)
                        throw new CoreException("Failed to obtain manager for domain '" + domainName + "'.");
                } catch (Throwable th) {
                    logger.log(Level.WARNING, "Failed to obtain non-local manager required by CURL '" + curl + "'.", th);
                    return null;
                }
            }
            try {
                // local name to be used
                String localName = curl.getPath();
                if (localName.charAt(0) == '/')
                    localName = localName.substring(1);
                ComponentInfo[] infos = remoteManager.getComponentInfo(INTERDOMAIN_MANAGER_HANDLE, handles, localName, type_wc, false);
                if (infos != null) {
                    // prefix names
                    final String prefix = CURL_URI_SCHEMA + curl.getAuthority() + "/";
                    for (int i = 0; i < infos.length; i++) {
                        if (!infos[i].getName().startsWith(CURL_URI_SCHEMA))
                            infos[i].setName(prefix + infos[i].getName());
                        String containerName = infos[i].getContainerName();
                        if (containerName != null && !containerName.startsWith(CURL_URI_SCHEMA))
                            infos[i].setContainerName(prefix + containerName);
                    }
                }
                return infos;
            } catch (Exception ex) {
                RemoteException re = new RemoteException("Failed to obtain component infos for CURL '" + curl + "' from remote manager.", ex);
                reportException(re);
                return null;
            }
        }
        // map of components to be returned
        Map<String, ComponentInfo> map = new HashMap<String, ComponentInfo>();
        // read active/registered components
        componentsLock.lock();
        try {
            int h = components.first();
            while (h != 0) {
                ComponentInfo componentInfo = (ComponentInfo) components.get(h);
                if (componentInfo.getComponent() != null && WildcharMatcher.match(name_wc, componentInfo.getName()) && WildcharMatcher.match(type_wc, componentInfo.getType())) {
                    // access rights to be checked here...
                    // found the match, add existing info to list
                    map.put(componentInfo.getName(), componentInfo);
                }
                h = components.next(h);
            }
        } finally {
            componentsLock.unlock();
        }
        // add also non-active, if requested
        if (!activeOnly) {
            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 name of component '" + ids[i] + "' defined.");
                            continue;
                        }
                        // add if not already added and matches criteria
                        if (!map.containsKey(name) && //!name.equals(ComponentSpec.COMPSPEC_ANY) &&
                        name.indexOf(ComponentSpec.COMPSPEC_ANY) != 0 && WildcharMatcher.match(name_wc, name)) {
                            // read type
                            String type = 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
                            if (!type.equals(ComponentSpec.COMPSPEC_ANY) && WildcharMatcher.match(type_wc, type)) {
                                // read code
                                String code = readStringCharacteristics(componentsDAO, ids[i] + "/Code");
                                if (code == null) {
                                    logger.log(Level.WARNING, "Misconfigured CDB, there is no code of component '" + name + "' defined.");
                                    continue;
                                }
                                // test code
                                if (code.equals(ComponentSpec.COMPSPEC_ANY))
                                    continue;
                                // read container
                                String container = readStringCharacteristics(componentsDAO, ids[i] + "/Container");
                                if (container == null) {
                                    logger.log(Level.WARNING, "Misconfigured CDB, there is no container name of component '" + name + "' defined.");
                                    continue;
                                }
                                // test container
                                if (container.equals(ComponentSpec.COMPSPEC_ANY))
                                    continue;
                                // got the match
                                // access rights to be checked here...
                                // create info and put it into list
                                ComponentInfo retInfo = new ComponentInfo(0, name, type, code, null);
                                retInfo.setContainerName(container);
                                map.put(name, retInfo);
                            }
                        }
                    }
                } catch (Exception ex) {
                    CoreException ce = new CoreException("Failed to obtain component data from the CDB.", ex);
                    reportException(ce);
                }
            }
        }
        // copy to array
        info = new ComponentInfo[map.size()];
        map.values().toArray(info);
    }
    return info;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) URISyntaxException(java.net.URISyntaxException) Manager(com.cosylab.acs.maci.Manager) DAOProxy(com.cosylab.cdb.client.DAOProxy) URI(java.net.URI) AcsJException(alma.acs.exceptions.AcsJException) NoDefaultComponentException(com.cosylab.acs.maci.NoDefaultComponentException) RemoteTransientException(com.cosylab.acs.maci.RemoteTransientException) NameNotFoundException(javax.naming.NameNotFoundException) NameAlreadyBoundException(javax.naming.NameAlreadyBoundException) IOException(java.io.IOException) NoResourcesException(com.cosylab.acs.maci.NoResourcesException) URISyntaxException(java.net.URISyntaxException) NamingException(javax.naming.NamingException) BadParametersException(com.cosylab.acs.maci.BadParametersException) CoreException(com.cosylab.acs.maci.CoreException) RemoteException(com.cosylab.acs.maci.RemoteException) TimeoutRemoteException(com.cosylab.acs.maci.TimeoutRemoteException) BadParametersException(com.cosylab.acs.maci.BadParametersException) CoreException(com.cosylab.acs.maci.CoreException) ComponentInfo(com.cosylab.acs.maci.ComponentInfo) RemoteException(com.cosylab.acs.maci.RemoteException) TimeoutRemoteException(com.cosylab.acs.maci.TimeoutRemoteException)

Example 2 with Manager

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

the class ManagerImpl method initialize.

/**
	 * Initializes Manager.
	 * @param	prevayler			implementation of prevayler system
	 * @param	context				remote directory implementation
	 */
public void initialize(Prevayler prevayler, CDBAccess cdbAccess, Context context, final Logger logger, ManagerContainerServices managerContainerServices) {
    this.prevayler = prevayler;
    this.remoteDirectory = context;
    this.logger = logger;
    // needs to be done here, since deserialization is used
    initializeDefaultConfiguration();
    if (cdbAccess != null)
        setCDBAccess(cdbAccess);
    readManagerConfiguration();
    componentsLock = (ProfilingReentrantLock.isProfilingEnabled ? new ProfilingReentrantLock("componentsLock") : new ReentrantLock());
    random = new Random();
    heartbeatTask = new Timer(true);
    delayedDeactivationTask = new Timer(true);
    containerLoggedInMonitor = new Object();
    activationSynchronization = new HashMap<String, ReferenceCountingLock>();
    activationPendingRWLock = new ReaderPreferenceReadWriteLock();
    shutdown = new AtomicBoolean(false);
    threadPool = new ThreadPoolExecutor(poolThreads, poolThreads, Long.MAX_VALUE, TimeUnit.NANOSECONDS, new LinkedBlockingQueue(), new DaemonThreadFactory("managerThreadPool"));
    managerCache = new HashMap<String, Manager>();
    pendingActivations = new HashMap<String, ComponentInfo>();
    pendingContainerShutdown = Collections.synchronizedSet(new HashSet<String>());
    pendingContainerAsyncRequests = new HashMap<String, Deque<ComponentInfoCompletionCallback>>();
    clientMessageQueue = new HashMap<Client, LinkedList<ClientMessageTask>>();
    groupedNotifyTaskMap = new HashMap<Object, GroupedNotifyTask>();
    threadsUsedPercentage = new AtomicInteger(0);
    // create threads
    threadPool.prestartAllCoreThreads();
    // read CDB startup
    try {
        String componentSpec = System.getProperty(NAME_CDB_COMPONENTSPEC);
        if (componentSpec != null) {
            cdbActivation = new ComponentSpec(componentSpec);
            logger.log(Level.INFO, "Using CDB component specification: '" + cdbActivation + "'.");
        }
    } catch (Throwable t) {
        logger.log(Level.WARNING, "Failed to parse '" + NAME_CDB_COMPONENTSPEC + "' variable, " + t.getMessage(), t);
    }
    // check load balancing strategy
    checkLoadBalancingStrategy();
    // establish connect to the alarm system
    try {
        alarmSource = new AlarmSourceImpl(managerContainerServices);
        alarmSource.start();
    } catch (Throwable ex) {
        logger.log(Level.SEVERE, "Failed to initialize Alarm System Interface " + ex.getMessage(), ex);
        alarmSource = null;
    }
    // register ping tasks
    initializePingTasks();
    // handle monitoring removal task
    final long timeInMs = enableHandleMonitoringDurationMins * 60L * 1000;
    if (enableHandleMonitoring && enableHandleMonitoringDurationMins > 0) {
        heartbeatTask.schedule(new TimerTask() {

            @Override
            public void run() {
                try {
                    logHandleCleanup(timeInMs);
                } catch (Throwable th) {
                    logger.log(Level.SEVERE, "Unexpected exception in handle log cleanup task.", th);
                }
            }
        }, 0, timeInMs);
    }
    // start topology sort manager
    topologySortManager = new ComponentInfoTopologicalSortManager(components, containers, activationPendingRWLock, pendingContainerShutdown, threadPool, logger);
    if (prevayler == null)
        statePersitenceFlag.set(false);
    String enDis = statePersitenceFlag.get() ? "enabled" : "disabled";
    logger.info("Manager initialized with state persistence " + enDis + ".");
}
Also used : DaemonThreadFactory(alma.acs.concurrent.DaemonThreadFactory) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Manager(com.cosylab.acs.maci.Manager) Random(java.util.Random) TimerTask(java.util.TimerTask) AlarmSourceImpl(alma.acs.alarmsystem.source.AlarmSourceImpl) Client(com.cosylab.acs.maci.Client) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) ReentrantLock(java.util.concurrent.locks.ReentrantLock) ComponentSpec(com.cosylab.acs.maci.ComponentSpec) ArrayDeque(java.util.ArrayDeque) Deque(java.util.Deque) LinkedList(java.util.LinkedList) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Timer(java.util.Timer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ComponentInfo(com.cosylab.acs.maci.ComponentInfo)

Example 3 with Manager

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

the class ManagerImpl method getManagerForDomain.

/**
     * Get manager for given domain.
     * @param domainName	domain name.
     * @return manager for given domain, <code>null</code> if not found.
     */
private synchronized Manager getManagerForDomain(String domainName) {
    // cache lookup
    if (managerCache.containsKey(domainName))
        return managerCache.get(domainName);
    final Object obj = lookup(federationDirectory, dottedToHierarchical(domainName) + "/Manager", null);
    if (obj == null)
        return null;
    /// @todo CORBA specific
    Manager remoteManager = new ManagerProxy(obj);
    // store into cache
    managerCache.put(domainName, remoteManager);
    return remoteManager;
}
Also used : ManagerProxy(com.cosylab.acs.maci.plug.ManagerProxy) Manager(com.cosylab.acs.maci.Manager)

Example 4 with Manager

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

the class ManagerImpl method internalNoSyncDeactivateComponent.

/**
	 * Deactivate component, issue deactivate reeust to container (or other manager).
	 * @param componentInfo	info about component to be deactivated.
	 */
private void internalNoSyncDeactivateComponent(ComponentInfo componentInfo) throws Throwable {
    // unbind from remote directory
    //unbind(convertToHiearachical(componentInfo.getName()), "O");
    int handle = componentInfo.getHandle() & HANDLE_MASK;
    int owners = componentInfo.getClients().size();
    try {
        //
        // get container/remote manager
        //
        String name = componentInfo.getName();
        boolean isOtherDomainComponent = name.startsWith(CURL_URI_SCHEMA);
        if (isOtherDomainComponent) {
            Manager remoteManager = null;
            // @todo MF do the login?
            try {
                String domainName = CURLHelper.createURI(name).getAuthority();
                remoteManager = getManagerForDomain(domainName);
                if (remoteManager == null)
                    throw new CoreException("Failed to obtain manager for domain '" + domainName + "'.");
            } catch (Throwable th) {
                logger.log(Level.WARNING, "Failed to obtain non-local manager required by component '" + name + "'.", th);
                throw th;
            }
            // release component
            try {
                URI curlName = CURLHelper.createURI(name);
                // @todo MF tmp (handle)
                remoteManager.releaseComponent(INTERDOMAIN_MANAGER_HANDLE, curlName);
            } catch (Throwable th) {
                logger.log(Level.WARNING, "Failed to release component '" + componentInfo.getName() + "' on remote manager.'", th);
                throw th;
            }
        } else {
            //
            // search for container by its name
            //
            Container container = null;
            ContainerInfo containerInfo = null;
            int containerHandle = componentInfo.getContainer();
            // if containerHandle equals 0, we have unavailable or registered component
            if (containerHandle != 0) {
                containerInfo = getContainerInfo(containerHandle);
                if (containerInfo != null) {
                    // remove component from container component list
                    synchronized (containerInfo.getComponents()) {
                        // !!! ACID
                        if (containerInfo.getComponents().contains(componentInfo.getHandle()))
                            executeCommand(new ContainerInfoCommandComponentRemove(containerInfo.getHandle() & HANDLE_MASK, componentInfo.getHandle()));
                    //containerInfo.getComponents().remove(componentInfo.getHandle());
                    }
                    // we allow this (since releasing components is part of container shutdown procedure)
                    //checkContainerState(containerInfo);
                    container = containerInfo.getContainer();
                }
                // required container is not logged in
                if (container == null) {
                    // then simply do not do the deactivation
                    String containerName;
                    if (containerInfo != null)
                        containerName = containerInfo.getName();
                    else
                        containerName = HandleHelper.toString(componentInfo.getContainer());
                    logger.log(Level.WARNING, "Container '" + containerName + "' required by component '" + componentInfo.getName() + "' is not logged in.");
                }
            }
            if (container != null) {
                // log info
                logger.log(Level.INFO, "Deactivating component '" + componentInfo.getName() + "' (" + HandleHelper.toString(componentInfo.getHandle()) + ") on container '" + containerInfo.getName() + "'.");
                // destruct
                try {
                    componentInfo.getComponent().destruct();
                } catch (Throwable ex) {
                    RemoteException re = new RemoteException("Failed to destruct component '" + componentInfo.getName() + "', exception caught when invoking 'destruct()' method.", ex);
                    logger.log(Level.SEVERE, re.getMessage(), re);
                    throw ex;
                }
                long deactivationTime = 0;
                // deactivate component in anycase
                try {
                    container.deactivate_component(componentInfo.getHandle());
                    deactivationTime = System.currentTimeMillis();
                } catch (AcsJException aex) {
                    logger.log(Level.SEVERE, aex.getMessage(), aex);
                    throw aex;
                } catch (Throwable ex) {
                    RemoteException re = new RemoteException("Failed to deactivate component '" + componentInfo.getName() + "' (" + HandleHelper.toString(componentInfo.getHandle()) + ") on container '" + containerInfo.getName() + "'.", ex);
                    logger.log(Level.SEVERE, re.getMessage(), re);
                    throw ex;
                }
                // notify administrators about deactivation, but not if failed
                if (deactivationTime != 0)
                    notifyComponentDeactivated(componentInfo.getHandle(), deactivationTime);
                // shutdown container if required (and necessary)
                conditionalShutdownContainer(containerInfo);
            }
        }
    } finally {
        if (owners == 0) {
            // deallocate Component
            componentsLock.lock();
            try {
                executeCommand(new ComponentCommandDeallocate(handle, componentInfo.getHandle(), WhyUnloadedReason.REMOVED));
            //components.deallocate(handle);
            } finally {
                componentsLock.unlock();
            }
        }
    }
    // log info
    logger.log(Level.INFO, "Component '" + componentInfo.getName() + "' (" + HandleHelper.toString(componentInfo.getHandle()) + ") deactivated.");
    // release all subcomponents (just like client logoff)
    // component should have already done this by itself, but take care of clean cleanup
    // what about that: if subcomponent becomes unavailable, does component also becomes?!
    // no, it is notified and it handles situation by its own way (e.g. changes component state).
    // Just like it already handles activation (manager does not care for dependecy trees).
    int[] subcomponents = null;
    // no not hold the lock
    synchronized (componentInfo.getComponents()) {
        if (componentInfo.getComponents().size() > 0) {
            IntArray toCleanupList = new IntArray();
            IntArray comps = componentInfo.getComponents();
            for (int i = 0; i < comps.size(); i++) if (components.isAllocated(comps.get(i) & HANDLE_MASK))
                toCleanupList.add(comps.get(i));
            if (toCleanupList.size() > 0)
                subcomponents = toCleanupList.toArray();
        }
    //subcomponents = componentInfo.getComponents().toArray();
    }
    if (subcomponents != null && subcomponents.length > 0)
        new ReleaseComponentTask(componentInfo.getHandle(), subcomponents).run();
    // make unavailable (deactivation was forced)
    if (owners > 0)
        makeUnavailable(componentInfo);
}
Also used : AcsJException(alma.acs.exceptions.AcsJException) Manager(com.cosylab.acs.maci.Manager) URI(java.net.URI) Container(com.cosylab.acs.maci.Container) CoreException(com.cosylab.acs.maci.CoreException) IntArray(com.cosylab.acs.maci.IntArray) ContainerInfoCommandComponentRemove(com.cosylab.acs.maci.manager.recovery.ContainerInfoCommandComponentRemove) ComponentCommandDeallocate(com.cosylab.acs.maci.manager.recovery.ComponentCommandDeallocate) ContainerInfo(com.cosylab.acs.maci.ContainerInfo) RemoteException(com.cosylab.acs.maci.RemoteException) TimeoutRemoteException(com.cosylab.acs.maci.TimeoutRemoteException)

Example 5 with Manager

use of com.cosylab.acs.maci.Manager 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

Manager (com.cosylab.acs.maci.Manager)5 ComponentInfo (com.cosylab.acs.maci.ComponentInfo)3 TimeoutRemoteException (com.cosylab.acs.maci.TimeoutRemoteException)3 URI (java.net.URI)3 AcsJException (alma.acs.exceptions.AcsJException)2 Container (com.cosylab.acs.maci.Container)2 ContainerInfo (com.cosylab.acs.maci.ContainerInfo)2 CoreException (com.cosylab.acs.maci.CoreException)2 RemoteException (com.cosylab.acs.maci.RemoteException)2 DAOProxy (com.cosylab.cdb.client.DAOProxy)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 AlarmSourceImpl (alma.acs.alarmsystem.source.AlarmSourceImpl)1 DaemonThreadFactory (alma.acs.concurrent.DaemonThreadFactory)1 AcsJCannotGetComponentEx (alma.maciErrType.wrappers.AcsJCannotGetComponentEx)1 AcsJComponentSpecIncompatibleWithActiveComponentEx (alma.maciErrType.wrappers.AcsJComponentSpecIncompatibleWithActiveComponentEx)1 BadParametersException (com.cosylab.acs.maci.BadParametersException)1 Client (com.cosylab.acs.maci.Client)1 ComponentSpec (com.cosylab.acs.maci.ComponentSpec)1 ImplLang (com.cosylab.acs.maci.ImplLang)1 IntArray (com.cosylab.acs.maci.IntArray)1