Search in sources :

Example 6 with Container

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

the class ManagerImplTest method testAdministratorNotifications.

public void testAdministratorNotifications() {
    try {
        TestAdministrator admin = new TestAdministrator("admin", true);
        ClientInfo adminInfo = manager.login(admin);
        assertNotNull(adminInfo);
        TestAdministrator admin2 = new TestAdministrator("admin2", true);
        ClientInfo adminInfo2 = manager.login(admin2);
        assertNotNull(adminInfo2);
        checkForNotification(admin.getClientLoggedInNotifications(), adminInfo2);
        TestAdministrator admin3 = new TestAdministrator("admin3", true);
        ClientInfo adminInfo3 = manager.login(admin3);
        assertNotNull(adminInfo3);
        checkForNotification(admin.getClientLoggedInNotifications(), adminInfo3);
        checkForNotification(admin2.getClientLoggedInNotifications(), adminInfo3);
        // test client login notification
        Client client = new TestClient("client");
        ClientInfo clientInfo = manager.login(client);
        assertNotNull(clientInfo);
        checkForNotification(admin.getClientLoggedInNotifications(), clientInfo);
        checkForNotification(admin2.getClientLoggedInNotifications(), clientInfo);
        checkForNotification(admin3.getClientLoggedInNotifications(), clientInfo);
        // test container login notification
        Container container = new TestContainer("Container");
        ClientInfo containerInfo = manager.login(container);
        assertNotNull(containerInfo);
        Integer h = new Integer(containerInfo.getHandle());
        checkForNotification(admin.getContainerLoggedInNotifications(), h);
        checkForNotification(admin2.getContainerLoggedInNotifications(), h);
        checkForNotification(admin3.getContainerLoggedInNotifications(), h);
        manager.logout(containerInfo.getHandle());
        checkForNotification(admin.getContainerLoggedOutNotifications(), h);
        checkForNotification(admin2.getContainerLoggedOutNotifications(), h);
        checkForNotification(admin3.getContainerLoggedOutNotifications(), h);
        manager.logout(clientInfo.getHandle());
        h = new Integer(clientInfo.getHandle());
        checkForNotification(admin.getClientLoggedOutNotifications(), h);
        checkForNotification(admin2.getClientLoggedOutNotifications(), h);
        checkForNotification(admin3.getClientLoggedOutNotifications(), h);
        manager.logout(adminInfo3.getHandle());
        h = new Integer(adminInfo3.getHandle());
        checkForNotification(admin.getClientLoggedOutNotifications(), h);
        checkForNotification(admin2.getClientLoggedOutNotifications(), h);
        manager.logout(adminInfo2.getHandle());
        h = new Integer(adminInfo2.getHandle());
        checkForNotification(admin.getClientLoggedOutNotifications(), h);
        manager.logout(adminInfo.getHandle());
        // test
        assertEquals(0, admin.getClientLoggedInNotifications().size());
        assertEquals(0, admin.getClientLoggedOutNotifications().size());
        assertEquals(0, admin.getContainerLoggedInNotifications().size());
        assertEquals(0, admin.getContainerLoggedOutNotifications().size());
        assertEquals(0, admin2.getClientLoggedInNotifications().size());
        assertEquals(0, admin2.getClientLoggedOutNotifications().size());
        assertEquals(0, admin2.getContainerLoggedInNotifications().size());
        assertEquals(0, admin2.getContainerLoggedOutNotifications().size());
        assertEquals(0, admin3.getClientLoggedInNotifications().size());
        assertEquals(0, admin3.getClientLoggedOutNotifications().size());
        assertEquals(0, admin3.getContainerLoggedInNotifications().size());
        assertEquals(0, admin3.getContainerLoggedOutNotifications().size());
    } catch (AcsJNoPermissionEx e) {
        fail("No permission");
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Container(com.cosylab.acs.maci.Container) AcsJNoPermissionEx(alma.maciErrType.wrappers.AcsJNoPermissionEx) ClientInfo(com.cosylab.acs.maci.ClientInfo) Client(com.cosylab.acs.maci.Client)

Example 7 with Container

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

Example 8 with Container

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

the class ManagerImpl method internalNoSyncRestartComponent.

/**
	 * Internal method for restarting components.
	 *
	 * @param	owner	owner of the component.
	 * @param	h		handle of the component to be restarting.
	 * @return			Newly restarted component, <code>null</code> if failed.
	 */
// @todo MF not supported
private Component internalNoSyncRestartComponent(int owner, int h) throws AcsJNoPermissionEx {
    int handle = h & HANDLE_MASK;
    ComponentInfo componentInfo = null;
    componentsLock.lock();
    try {
        if (components.isAllocated(handle))
            componentInfo = (ComponentInfo) components.get(handle);
        if (componentInfo == null || componentInfo.getHandle() != h) {
            // invalid component handle
            BadParametersException af = new BadParametersException("Invalid component handle.");
            throw af;
        }
        // remove ownership of the component
        if (!componentInfo.getClients().contains(owner)) {
            // not an owner
            AcsJNoPermissionEx npe = new AcsJNoPermissionEx();
            npe.setReason("Restarting component that client does not own.");
            npe.setID(HandleHelper.toString(owner));
            npe.setProtectedResource(componentInfo.getName());
            throw npe;
        }
    } finally {
        componentsLock.unlock();
    }
    /****************** restart component ******************/
    //
    // get container
    //
    // 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) {
            checkContainerShutdownState(containerInfo);
            container = containerInfo.getContainer();
        }
        // required container is not logged in
        if (container == null) {
            // then simply do not do the restart
            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.");
        }
    }
    // return value
    Component component = null;
    if (container != null) {
        // restart component
        try {
            component = container.restart_component(componentInfo.getHandle());
            if (component == null) {
                RemoteException re = new RemoteException("Failed to restart component '" + componentInfo.getName() + "', 'null' returned.");
                throw re;
            }
        // @todo what about notifying clients, marking component as available, updating reference...
        } catch (Throwable ex) {
            RemoteException re = new RemoteException("Failed to restart component '" + componentInfo.getName() + "' on container '" + containerInfo.getName() + "'.", ex);
            logger.log(Level.SEVERE, re.getMessage(), re);
        }
    }
    logger.log(Level.FINE, "Component '" + componentInfo.getName() + "' restarted.");
    return component;
}
Also used : Container(com.cosylab.acs.maci.Container) AcsJNoPermissionEx(alma.maciErrType.wrappers.AcsJNoPermissionEx) ContainerInfo(com.cosylab.acs.maci.ContainerInfo) ComponentInfo(com.cosylab.acs.maci.ComponentInfo) Component(com.cosylab.acs.maci.Component) RemoteException(com.cosylab.acs.maci.RemoteException) TimeoutRemoteException(com.cosylab.acs.maci.TimeoutRemoteException) BadParametersException(com.cosylab.acs.maci.BadParametersException)

Example 9 with Container

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

the class ManagerImpl method containerLogin.

/*****************************************************************************/
/**************************** [ Login methods ] ******************************/
/*****************************************************************************/
/**
	 * Container specific login method.
	 * @param	name	name of the container, non-<code>null</code>.
	 * @param	reply	reply to authenticate method, non-<code>null</code>.
	 * @param	container	container that is logging in, non-<code>null</code>.
	 * @return	ClientInfo	client info. of newly logged container
	 */
private ClientInfo containerLogin(String name, AuthenticationData reply, Container container, long timeStamp, long executionId) throws AcsJNoPermissionEx {
    assert (name != null);
    assert (reply != null);
    assert (container != null);
    TimerTaskContainerInfo containerInfo = null;
    ClientInfo clientInfo = null;
    boolean existingLogin = false;
    synchronized (containers) {
        // check if container is already logged in,
        // if it is, return existing info
        int h = containers.first();
        while (h != 0) {
            ContainerInfo loggedContainerInfo = (ContainerInfo) containers.get(h);
            //if (container.equals(loggedContainerInfo.getContainer()))
            if (name.equals(loggedContainerInfo.getName())) {
                Container loggedContainer = loggedContainerInfo.getContainer();
                if (loggedContainer != null) {
                    // if same instance simply recover, if not...
                    if (!loggedContainer.equals(container)) {
                        // check if logged container is alive, if it is reject him
                        boolean alive = false;
                        try {
                            int lh = loggedContainer.get_handle();
                            if (lh != 0 && lh == loggedContainerInfo.getHandle())
                                alive = true;
                        } catch (Throwable th) {
                        // noop
                        }
                        if (alive) {
                            AcsJNoPermissionEx npe = new AcsJNoPermissionEx();
                            String address = "";
                            try {
                                address = " " + loggedContainer.getRemoteLocation();
                            } catch (Throwable th) {
                            /* noop */
                            }
                            npe.setReason("Rejecting container login, container with name '" + name + "'" + address + " already logged in.");
                            npe.setID(HandleHelper.toString(loggedContainerInfo.getHandle()));
                            npe.setProtectedResource(name);
                            throw npe;
                        } else
                            logger.log(Level.FINER, "Container '" + name + "' is no longer functional, new container is taking over.");
                    }
                }
                // !!! ACID 2
                // new reference is considered as better
                executeCommand(new ContainerCommandUpdate(h, container));
                //loggedContainerInfo.setContainer(container);
                existingLogin = true;
                // generate ClientInfo
                containerInfo = (TimerTaskContainerInfo) loggedContainerInfo;
                clientInfo = containerInfo.createClientInfo();
                break;
            }
            h = containers.next(h);
        }
        // new container
        if (h == 0) {
            long pingInterval = 0;
            DAOProxy dao = getContainersDAOProxy();
            if (dao != null) {
                String impLang = readStringCharacteristics(dao, name + "/ImplLang", true);
                ImplLang configuredImplLang = ImplLang.fromString(impLang);
                if (configuredImplLang != ImplLang.not_specified && configuredImplLang != reply.getImplLang()) {
                    AcsJNoPermissionEx npe = new AcsJNoPermissionEx();
                    npe.setReason("Rejecting container login, container reported '" + reply.getImplLang() + "' implementation language, but configured '" + configuredImplLang + "'.");
                    npe.setProtectedResource(name);
                    throw npe;
                }
                pingInterval = readLongCharacteristics(dao, name + "/PingInterval", -1, true) * 1000;
            }
            // allocate new handle
            // !!! ACID 2
            Integer objHandle = (Integer) executeCommand(new ContainerCommandAllocate());
            int handle;
            if (objHandle == null || (handle = objHandle.intValue()) == 0) {
                NoResourcesException af = new NoResourcesException("Generation of new handle failed, too many containers logged in.");
                throw af;
            }
            // generate external handle
            h = handle | CONTAINER_MASK;
            // add generated key
            h |= (random.nextInt(0x100)) << 16;
            // create new container info
            containerInfo = new TimerTaskContainerInfo(h, name, container, containerPingInterval);
            containerInfo.setImplLang(reply.getImplLang());
            if (// safety limit
            pingInterval >= 1000)
                containerInfo.setPingInterval(pingInterval);
            clientInfo = containerInfo.createClientInfo();
            // register container to the heartbeat manager
            PingTimerTask task = new PingTimerTask(this, logger, clientInfo, alarmSource);
            containerInfo.setTask(task);
            heartbeatTask.schedule(task, containerInfo.getPingInterval(), containerInfo.getPingInterval());
            // !!! ACID - register AddContainerCommand
            executeCommand(new ContainerCommandSet(handle, containerInfo));
        // store info
        //containers.set(handle, containerInfo);
        }
    }
    // cancel all "old" container async request
    AcsJCannotGetComponentEx acgcex = new AcsJCannotGetComponentEx();
    acgcex.setReason("Request canceled due to container re-login.");
    cancelPendingContainerAsyncRequestWithException(containerInfo.getName(), acgcex);
    final boolean recoverContainer = reply.isRecover();
    if (existingLogin) {
        // merge container's and manager's internal state
        containerInternalStateMerge(containerInfo, recoverContainer);
    }
    // notify administrators about the login
    notifyContainerLogin(containerInfo, timeStamp, executionId);
    // do container post login activation in separate thread
    final ContainerInfo finalInfo = containerInfo;
    threadPool.execute(new Runnable() {

        public void run() {
            containerPostLoginActivation(finalInfo, recoverContainer);
        }
    });
    logger.log(Level.INFO, "Container '" + name + "' logged in.");
    return clientInfo;
}
Also used : ContainerCommandAllocate(com.cosylab.acs.maci.manager.recovery.ContainerCommandAllocate) ContainerCommandSet(com.cosylab.acs.maci.manager.recovery.ContainerCommandSet) ContainerCommandUpdate(com.cosylab.acs.maci.manager.recovery.ContainerCommandUpdate) DAOProxy(com.cosylab.cdb.client.DAOProxy) AcsJCannotGetComponentEx(alma.maciErrType.wrappers.AcsJCannotGetComponentEx) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NoResourcesException(com.cosylab.acs.maci.NoResourcesException) Container(com.cosylab.acs.maci.Container) AcsJNoPermissionEx(alma.maciErrType.wrappers.AcsJNoPermissionEx) ContainerInfo(com.cosylab.acs.maci.ContainerInfo) ClientInfo(com.cosylab.acs.maci.ClientInfo) ImplLang(com.cosylab.acs.maci.ImplLang)

Example 10 with Container

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

the class ManagerImplTest method testSequentialContainersLogin.

public void testSequentialContainersLogin() {
    int counter = 0;
    final int SEQUENTAL_LOGINS = 100;
    try {
        for (int i = 0; i < SEQUENTAL_LOGINS; i++) {
            final String containerName = "Container" + (++counter);
            Container container = new TestContainer(containerName);
            ClientInfo info = manager.login(container);
            assertTrue(containerName + " failed to login.", info != null && info.getHandle() != 0);
        }
    } catch (AcsJNoPermissionEx e) {
        fail("No permission");
    }
}
Also used : Container(com.cosylab.acs.maci.Container) AcsJNoPermissionEx(alma.maciErrType.wrappers.AcsJNoPermissionEx) ClientInfo(com.cosylab.acs.maci.ClientInfo)

Aggregations

Container (com.cosylab.acs.maci.Container)10 AcsJNoPermissionEx (alma.maciErrType.wrappers.AcsJNoPermissionEx)6 ClientInfo (com.cosylab.acs.maci.ClientInfo)5 ContainerInfo (com.cosylab.acs.maci.ContainerInfo)5 TimeoutRemoteException (com.cosylab.acs.maci.TimeoutRemoteException)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 AcsJCannotGetComponentEx (alma.maciErrType.wrappers.AcsJCannotGetComponentEx)3 BadParametersException (com.cosylab.acs.maci.BadParametersException)3 ComponentInfo (com.cosylab.acs.maci.ComponentInfo)3 NoResourcesException (com.cosylab.acs.maci.NoResourcesException)3 RemoteException (com.cosylab.acs.maci.RemoteException)3 CoreException (com.cosylab.acs.maci.CoreException)2 ImplLang (com.cosylab.acs.maci.ImplLang)2 Manager (com.cosylab.acs.maci.Manager)2 DAOProxy (com.cosylab.cdb.client.DAOProxy)2 URI (java.net.URI)2 AcsJException (alma.acs.exceptions.AcsJException)1 AcsJComponentSpecIncompatibleWithActiveComponentEx (alma.maciErrType.wrappers.AcsJComponentSpecIncompatibleWithActiveComponentEx)1 Administrator (com.cosylab.acs.maci.Administrator)1 AuthenticationData (com.cosylab.acs.maci.AuthenticationData)1