Search in sources :

Example 6 with FacilityNotExistsException

use of cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException in project perun by CESNET.

the class urn_perun_member_resource_attribute_def_virt_isBanned method getAttributeValue.

@Override
public Attribute getAttributeValue(PerunSessionImpl sess, Resource resource, Member member, AttributeDefinition attributeDefinition) throws InternalErrorException {
    Attribute attribute = new Attribute(attributeDefinition);
    //Default value is false
    attribute.setValue(false);
    Facility facility;
    try {
        facility = sess.getPerunBl().getFacilitiesManagerBl().getFacilityById(sess, resource.getFacilityId());
    } catch (FacilityNotExistsException ex) {
        throw new InternalErrorException("Facility for Resource " + resource + " not exists!");
    }
    User user;
    try {
        user = sess.getPerunBl().getUsersManagerBl().getUserById(sess, member.getUserId());
    } catch (UserNotExistsException ex) {
        throw new InternalErrorException("User for Member " + member + " not exists!");
    }
    //Ban on resource exists?
    if (sess.getPerunBl().getResourcesManagerBl().banExists(sess, member.getId(), resource.getId()))
        attribute.setValue(true);
    //Ban on facility exists?
    if (sess.getPerunBl().getFacilitiesManagerBl().banExists(sess, user.getId(), facility.getId()))
        attribute.setValue(true);
    return attribute;
}
Also used : User(cz.metacentrum.perun.core.api.User) Attribute(cz.metacentrum.perun.core.api.Attribute) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) BanOnFacility(cz.metacentrum.perun.core.api.BanOnFacility) Facility(cz.metacentrum.perun.core.api.Facility) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException)

Example 7 with FacilityNotExistsException

use of cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException in project perun by CESNET.

the class EventExecServiceResolverImpl method parseEvent.

@Override
public Map<Facility, Set<ExecService>> parseEvent(String event) throws InvalidEventMessageException, ServiceNotExistsException, InternalErrorException, PrivilegeException {
    log.info("I am going to process event:" + event);
    /**
		 * Expected string format as on:
		 * https://projekty.ics.muni.cz/perunv3/trac
		 * /wiki/PerunEngineDispatcherController event|x|[timestamp][Event
		 * header][Event data]
		 */
    String eventParsingPattern = "^\\[([a-zA-Z0-9+: ]+)\\]\\[([^\\]]+)\\]\\[(.*)\\]$";
    Pattern pattern = Pattern.compile(eventParsingPattern);
    Matcher matcher = pattern.matcher(event);
    boolean matchFound = matcher.find();
    if (matchFound) {
        log.debug("Message format matched ok...");
        // NOT USED ANYMORE: not applicable in dispatcher
        // String thisEngineID = matcher.group(1);
        // // This should indeed match the current Engine instance ID, so
        // let's compare it...
        // if (Integer.parseInt(thisEngineID) != Integer.parseInt((String)
        // propertiesBean.get("engine.unique.id"))) {
        // throw new InvalidEventMessageException("Wrong Engine ID. Was:" +
        // thisEngineID + ", Expected:" +
        // propertiesBean.get("engine.unique.id"));
        // }
        // // Not being used at the moment.
        // String timeStamp = matcher.group(2);
        // Header should provide information regarding the target facility.
        String eventHeader = matcher.group(2);
        // We expect the string to contain something like this:
        // facility.id=2 ???
        // String headerParsingPattern = ".*facility.id\\=([0-9]+).*";
        // Pattern headerPattern = Pattern.compile(headerParsingPattern);
        // Matcher headerMatcher = headerPattern.matcher(eventHeader);
        /*
			 * boolean headerMatchFound = headerMatcher.find();
			 * if(!headerMatchFound) { throw new InvalidEventMessageException(
			 * "Invalid event header. It does not contain the expected facility.id=value..."
			 * ); } int facilityId = Integer.parseInt(matcher.group(1));
			 * PerunSession perunSession =
			 * engineManager.getPerunSession(propertiesBean
			 * .getProperty("perun.principal")); Facility facility = null; try {
			 * facility = facilitiesManager.getFacilityById(perunSession,
			 * facilityId); } catch (FacilityNotExistsException e) { throw new
			 * InvalidEventMessageException
			 * ("Facility with ID "+facilityId+"does not exist.", e); } catch
			 * (InternalErrorException e) { throw new
			 * InvalidEventMessageException("Unknown error...", e); } catch
			 * (PrivilegeException e) { throw new
			 * InvalidEventMessageException("Principal "
			 * +propertiesBean.getProperty
			 * ("perun.principal")+" is not allowed to access that facility. ",
			 * e); }
			 */
        // Data should provide information regarding the target ExecService
        // (Processing rule).
        String eventData = matcher.group(3);
        log.debug("Event data to be parsed:" + eventData);
        // GET All Beans (only PerunBeans) from message
        List<PerunBean> listOfBeans = new ArrayList<PerunBean>();
        listOfBeans = AuditParser.parseLog(eventData);
        // Prepare variables
        AttributeDefinition attributeDefinition = null;
        Attribute attribute = null;
        Facility facility = null;
        Resource resource = null;
        Group group = null;
        User user = null;
        Member member = null;
        Service service = null;
        Host host = null;
        // etc. ?
        for (PerunBean pb : listOfBeans) {
            if (pb instanceof AttributeDefinition && pb instanceof Attribute) {
                attribute = (Attribute) pb;
            } else if (pb instanceof Facility) {
                facility = (Facility) pb;
            } else if (pb instanceof Resource) {
                resource = (Resource) pb;
            } else if (pb instanceof Group) {
                group = (Group) pb;
            } else if (pb instanceof User) {
                user = (User) pb;
            } else if (pb instanceof Member) {
                member = (Member) pb;
            } else if (pb instanceof Service) {
                service = (Service) pb;
            } else if (pb instanceof Host) {
                host = (Host) pb;
            }
        }
        // If there is any attribute, so create AttributeDefinition
        if (attribute != null) {
            attributeDefinition = new AttributeDefinition(attribute);
            log.debug("Attribute found in event. {}.", attributeDefinition);
        }
        List<Facility> facilitiesResolvedFromEvent = new ArrayList<Facility>();
        List<Resource> resourcesResolvedFromEvent = new ArrayList<Resource>();
        List<Service> servicesResolvedFromEvent = new ArrayList<Service>();
        // =============== Resolve facilities from event======================
        PerunSession perunSession = perun.getPerunSession(new PerunPrincipal(dispatcherPropertiesBean.getProperty("perun.principal.name"), dispatcherPropertiesBean.getProperty("perun.principal.extSourceName"), dispatcherPropertiesBean.getProperty("perun.principal.extSourceType")), new PerunClient());
        // Try to find FACILITY in event
        if (facility != null) {
            try {
                log.debug("Facility found in event. {}.", facility);
                facilitiesResolvedFromEvent.add(facility);
                resourcesResolvedFromEvent.addAll(perun.getFacilitiesManager().getAssignedResources(perunSession, facility));
            } catch (FacilityNotExistsException ex) {
                log.debug("Non-existing facility found while resolving event. id={}", facility.getId());
            }
        } else {
            // Try to find RESOURCE in event
            if (resource != null) {
                resourcesResolvedFromEvent.add(resource);
            } else {
                // Try to find GROUP in event
                if (group != null) {
                    try {
                        resourcesResolvedFromEvent = perun.getResourcesManager().getAssignedResources(perunSession, group);
                    } catch (GroupNotExistsException ex) {
                        log.debug("Non-existing group found while resolving event. id={}", group.getId());
                    }
                } else {
                    // try to find USER in event
                    if (user != null) {
                        try {
                            resourcesResolvedFromEvent = perun.getUsersManager().getAllowedResources(perunSession, user);
                        } catch (UserNotExistsException ex) {
                            log.debug("Non-existing user found while resolving event. id={}", user.getId());
                        }
                    } else {
                        // try to find MEMBER in event
                        if (member != null) {
                            try {
                                resourcesResolvedFromEvent = perun.getResourcesManager().getAllowedResources(perunSession, member);
                            } catch (MemberNotExistsException ex) {
                                log.debug("Non-existing member found while resolving event. id={}", member.getId());
                            }
                        } else {
                            // try to find HOST in event
                            if (host != null) {
                                try {
                                    log.debug("Host found in event.id= {}.", host.getId());
                                    facility = perun.getFacilitiesManager().getFacilityForHost(perunSession, host);
                                    facilitiesResolvedFromEvent.add(facility);
                                    resourcesResolvedFromEvent.addAll(perun.getFacilitiesManager().getAssignedResources(perunSession, facility));
                                } catch (FacilityNotExistsException ex) {
                                    log.debug("Host on non-existing facility found while resolving event. Host id={}", host.getId());
                                } catch (HostNotExistsException ex) {
                                    log.debug("Non-existing host found while resolving event. id={}", host.getId());
                                }
                            } else {
                                log.warn("No match found for this event. Event={}", event);
                            }
                        }
                    }
                }
            }
        }
        // TODO resolve more than one service
        if (service != null) {
            servicesResolvedFromEvent.add(service);
        }
        //List<Pair<List<ExecService>, Facility>> pairs = new ArrayList<Pair<List<ExecService>, Facility>>();
        Map<Facility, Set<ExecService>> result = new HashMap<Facility, Set<ExecService>>();
        for (Resource r : resourcesResolvedFromEvent) {
            Facility facilityResolvedFromEvent;
            List<Service> servicesResolvedFromResource;
            try {
                facilityResolvedFromEvent = perun.getResourcesManager().getFacility(perunSession, r);
                servicesResolvedFromResource = perun.getResourcesManager().getAssignedServices(perunSession, r);
                // process only services resolved from event if any
                if (!servicesResolvedFromEvent.isEmpty())
                    servicesResolvedFromResource.retainAll(servicesResolvedFromEvent);
            } catch (ResourceNotExistsException ex) {
                log.debug("Non-existing resource found while resolving event. Resource={}", r);
                // skip to next resource
                continue;
            }
            for (Service s : servicesResolvedFromResource) {
                // TODO: Optimize with an SQL query...
                List<ExecService> execServicesGenAndSend = generalServiceManager.listExecServices(perunSession, s.getId());
                List<ExecService> execServices = new ArrayList<ExecService>();
                for (ExecService execService : execServicesGenAndSend) {
                    if (execService.getExecServiceType().equals(ExecServiceType.SEND)) {
                        execServices.add(execService);
                    }
                }
                if (attributeDefinition != null) {
                    // remove from future processing services
                    // which don't require the found attribute
                    // TODO (CHECKME) This method can raise
                    // ServiceNotExistsException. Is it ok? Or it must be
                    // catch?
                    List<AttributeDefinition> serviceRequiredAttributes = perun.getAttributesManager().getRequiredAttributesDefinition(perunSession, s);
                    if (!serviceRequiredAttributes.contains(attributeDefinition))
                        continue;
                }
                if (!result.containsKey(facilityResolvedFromEvent)) {
                    result.put(facilityResolvedFromEvent, new HashSet<ExecService>(execServices));
                } else {
                    result.get(facilityResolvedFromEvent).addAll(execServices);
                }
            }
        }
        log.info("I am going to return " + result.size() + " facilities.");
        return result;
    } else {
        throw new InvalidEventMessageException("Message[" + event + "]");
    }
}
Also used : Group(cz.metacentrum.perun.core.api.Group) User(cz.metacentrum.perun.core.api.User) HashSet(java.util.HashSet) Set(java.util.Set) Matcher(java.util.regex.Matcher) Attribute(cz.metacentrum.perun.core.api.Attribute) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AttributeDefinition(cz.metacentrum.perun.core.api.AttributeDefinition) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) Member(cz.metacentrum.perun.core.api.Member) Pattern(java.util.regex.Pattern) PerunSession(cz.metacentrum.perun.core.api.PerunSession) MemberNotExistsException(cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException) GroupNotExistsException(cz.metacentrum.perun.core.api.exceptions.GroupNotExistsException) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) HostNotExistsException(cz.metacentrum.perun.core.api.exceptions.HostNotExistsException) Resource(cz.metacentrum.perun.core.api.Resource) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) Service(cz.metacentrum.perun.core.api.Service) Host(cz.metacentrum.perun.core.api.Host) ResourceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ResourceNotExistsException) PerunBean(cz.metacentrum.perun.core.api.PerunBean) PerunClient(cz.metacentrum.perun.core.api.PerunClient) Facility(cz.metacentrum.perun.core.api.Facility) InvalidEventMessageException(cz.metacentrum.perun.dispatcher.exceptions.InvalidEventMessageException)

Example 8 with FacilityNotExistsException

use of cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException in project perun by CESNET.

the class TaskSchedulerImpl method refetchTaskInformation.

private void refetchTaskInformation(Task task) throws FacilityNotExistsException, InternalErrorException, PrivilegeException, ServiceNotExistsException {
    // reread facility
    log.debug("Rereading facility and  exec service for task {}", task.getId());
    Facility dbFacility = perun.getFacilitiesManagerBl().getFacilityById(perunSession, task.getFacilityId());
    if (dbFacility == null) {
        throw new FacilityNotExistsException("No facility with id " + task.getFacilityId());
    }
    Boolean taskModified = false;
    if (!dbFacility.equals(task.getFacility())) {
        task.setFacility(dbFacility);
        taskModified = true;
    }
    // reread exec service (and service)
    ExecService dbExecService = generalServiceManager.getExecService(perunSession, task.getExecServiceId());
    if (dbExecService == null) {
        throw new ServiceNotExistsException("No exec service with id " + task.getExecServiceId());
    }
    if (!dbExecService.equals(task.getExecService())) {
        task.setExecService(dbExecService);
        taskModified = true;
    }
    if (taskModified) {
        log.debug("Task components have changed, updating task {}", task.getId());
        schedulingPool.setTaskStatus(task, task.getStatus());
    }
}
Also used : ServiceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ServiceNotExistsException) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) Facility(cz.metacentrum.perun.core.api.Facility)

Example 9 with FacilityNotExistsException

use of cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException in project perun by CESNET.

the class TaskSchedulerImpl method scheduleTask.

// TODO ensure dependant tasks with scope DESTINATION go to the same engine
@Override
public Boolean scheduleTask(Task task) {
    ExecService execService = task.getExecService();
    Facility facility = task.getFacility();
    Date time = new Date(System.currentTimeMillis());
    DispatcherQueue dispatcherQueue = null;
    if (task.getStatus().equals(TaskStatus.PROCESSING) && !task.isPropagationForced()) {
        log.debug("Task {} already processing, will not schedule again.", task.toString());
        return true;
    }
    log.debug("Scheduling TASK " + task.toString());
    try {
        dispatcherQueue = schedulingPool.getQueueForTask(task);
        log.debug("Task {} is assigned to queue {}", task.getId(), (dispatcherQueue == null) ? "null" : dispatcherQueue.getClientID());
    } catch (InternalErrorException e) {
        log.warn("Task {} is not assigned to any queue", task.getId());
    }
    // check if the engine is still registered
    if (dispatcherQueue != null && !dispatcherQueuePool.isThereDispatcherQueueForClient(dispatcherQueue.getClientID())) {
        dispatcherQueue = null;
    }
    if (dispatcherQueue == null) {
        // where should we send the task?
        dispatcherQueue = dispatcherQueuePool.getAvailableQueue();
        if (dispatcherQueue != null) {
            try {
                schedulingPool.setQueueForTask(task, dispatcherQueue);
            } catch (InternalErrorException e) {
                log.error("Could not set client queue for task {}: {}", task.getId(), e.getMessage());
                return true;
            }
            log.debug("Assigned new queue " + dispatcherQueue.getQueueName() + " to task " + task.getId());
        } else {
            // bad luck...
            log.error("Task " + task.toString() + " has no engine assigned and there are no engines registered...");
            return true;
        }
    }
    log.debug("Facility to be processed: " + facility.getId() + ", ExecService to be processed: " + execService.getId());
    Boolean abortTask = false;
    try {
        refetchTaskInformation(task);
        List<Service> assignedServices = perun.getServicesManagerBl().getAssignedServices(perunSession, task.getFacility());
        if (!assignedServices.contains(execService.getService())) {
            log.debug("Task {} has no longer service {} assigned, aborting.", task.getId(), execService.getId());
            abortTask = true;
        }
    } catch (FacilityNotExistsException e1) {
        log.debug("Facility {} for task {} no longer exists, aborting", facility.getId(), task.getId());
        abortTask = true;
    } catch (ServiceNotExistsException e1) {
        log.debug("Service {} for task {} no longer exists, aborting", execService.getId(), task.getId());
        abortTask = true;
    } catch (InternalErrorException e1) {
        log.error("Error checking facility or exec service for updates, task will not run now: {}", e1.getMessage());
        return true;
    } catch (PrivilegeException e1) {
        log.error("Error checking facility or exec service for updates, task will not run now: {}", e1.getMessage());
        return true;
    }
    // GEN tasks that we depend on...
    if (abortTask && execService.getExecServiceType() == ExecServiceType.GENERATE) {
        // GEN tasks may be aborted immediately
        abortTask(task);
        return false;
    }
    // do not perform further checks for task that is going to be aborted
    if (!abortTask) {
        log.debug("Is the execService ID:" + execService.getId() + " enabled globally?");
        if (execService.isEnabled()) {
            log.debug("   Yes, it is globally enabled.");
        } else {
            log.debug("   No, execService ID: " + execService.getId() + " is not enabled globally. Task will not run.");
            return true;
        }
        log.debug("   Is the execService ID: " + execService.getId() + " denied on facility ID:" + facility.getId() + "?");
        try {
            if (!denialsResolver.isExecServiceDeniedOnFacility(execService, facility)) {
                log.debug("   No, it is not.");
            } else {
                log.debug("   Yes, the execService ID: " + execService.getId() + " is denied on facility ID: " + facility.getId() + ". Task will not run.");
                return true;
            }
        } catch (InternalErrorException e) {
            log.error("Error getting disabled status for execService, task will not run now.");
            return true;
        }
    }
    List<ExecService> dependantServices = null;
    List<Pair<ExecService, DependencyScope>> dependencies = null;
    // If any of the ExecServices that depends on this one is running
    // PROCESSING
    // we will put the ExecService,Facility pair back to the pool.
    // #################################################################################
    log.debug("   Is there any execService that depends on [" + execService.getId() + "] in \"PROCESSING\" state?");
    dependantServices = dependenciesResolver.listDependantServices(execService);
    boolean proceed = true;
    for (ExecService dependantService : dependantServices) {
        Task dependantServiceTask = schedulingPool.getTask(dependantService, facility);
        if (dependantServiceTask != null) {
            if (dependantServiceTask.getStatus().equals(TaskStatus.PROCESSING)) {
                log.debug("   There is a service [" + dependantServiceTask.getId() + "] running that depends on this one [" + execService + "], so we put this to sleep...");
                // schedulingPool.addToPool(new Pair<ExecService,
                // Facility>(execService, facility));
                proceed = false;
                break;
            }
        // This is probably wrong, so commenting out:
        //   1) if there is some dispatcher queue active at the moment, dispatcherQueue is not null
        //   2) if there is no dispatcher queue available, no point in setting the same queue another task has
        //   3) the dependency should be handled the other way round, from dependant to dependent
        /*
				 * try {
				 *	if (dispatcherQueue == null &&
				 *			schedulingPool.getQueueForTask(dependantServiceTask) != null) {
				 *		schedulingPool.setQueueForTask(task, schedulingPool.getQueueForTask(dependantServiceTask));
				 *	}
				 * } catch (InternalErrorException e) {
				 *	log.debug("    Failed to set destination queue for task. This is weird, aborting.");
				 *	proceed = false;
				 *}
				 */
        }
    }
    if (proceed) {
        log.debug("   No, it is not. No dependent service is running, we can proceed.");
        // If it is an ExecService of type SEND, we have to check its
        // dependencies.
        // We can skip this for GENERATE type (it has no dependencies by
        // design).
        // ########################################################################
        log.debug("   Check whether the execService [" + execService.getId() + "] is of type SEND");
        if (execService.getExecServiceType().equals(ExecServiceType.SEND)) {
            log.debug("   Well, it is, so we have to check it's dependencies.");
            // We check the status of all the ExecServices this ExecService
            // depends on.
            //
            //
            // Current approach disregards any SEND/GENERATE differences.
            // Dependency on a GENERATE service is being treated as same as
            // any other SEND dependency
            // but for a small exception regarding ERROR and DONE states,
            // see below:
            //
            // If the dependency is in one of the following states, we do:
            // NONE Schedule it and wait (put this [ExecService,Facility]
            // pair back to the SchedulingPool for a while).
            // PROCESSING Wait
            // ERROR IF dependency is GENERATE THEN DO
            // Schedule it and wait (put this [ExecService,Facility] pair
            // back to the SchedulingPool for a while).
            // ELSE IF dependency is SEND THEN DO
            // End with ERROR. (no point in trying, something is probably
            // amiss on destination nodes...)
            // ELSE
            // throw new IllegalArgumentException
            // FI
            // DONE IF dependency is GENERATE THEN DO
            // Schedule it and wait (put this [ExecService,Facility] pair
            // back to the SchedulingPool for a while).
            //
            // It might look like we get an infinite loop where GENERATE
            // will be in DONE and then rescheduled again and again.
            // It is not so because PropagationMaintainer sets its state to
            // NONE as soon as the SEND, that depends on it,
            // enters either DONE or ERROR states (one of its finite
            // states).
            // ELSE IF dependency is SEND THEN DO
            // Proceed (Yes, no need to schedule this dependency, it is done
            // already and we don't care for how long it has been so at this
            // point.)
            // ELSE
            // throw new IllegalArgumentException
            // FI
            // :-)
            // #######################################################################################################
            proceed = true;
            dependencies = dependenciesResolver.listDependenciesAndScope(execService);
            log.debug("   We are about to loop over execService [" + execService.getId() + "] dependencies.");
            log.debug("   Number of dependencies:" + dependencies);
            DispatcherQueue dependencyQueue = null;
            for (Pair<ExecService, DependencyScope> dependencyPair : dependencies) {
                ExecService dependency = dependencyPair.getLeft();
                DependencyScope dependencyScope = dependencyPair.getRight();
                Task dependencyServiceTask = schedulingPool.getTask(dependency, facility);
                if (dependencyServiceTask == null) {
                    if (abortTask) {
                        log.info("   Task {} is going to be aborted, the dependency exec service {} will not be scheduled now.", task.getId(), dependency.getId());
                    } else {
                        // Dependency being NULL is equivalent to being in NONE
                        // state.
                        log.info("   Last Task [dependency:" + dependency.getId() + ", facility:" + facility.getId() + "] was NULL, we are gonna propagate.");
                        if (scheduleItAndWait(dependency, facility, execService, dispatcherQueue, time)) {
                        // task sucessfully scheduled, nothing to do
                        } else {
                        // TODO: task aborted - maybe set this one to error?
                        }
                    }
                    proceed = false;
                } else {
                    boolean wasDependencyServiceTaskForced = dependencyServiceTask.isPropagationForced();
                    dependencyServiceTask.setPropagationForced(task.isPropagationForced());
                    switch(dependencyServiceTask.getStatus()) {
                        case DONE:
                            switch(dependency.getExecServiceType()) {
                                case GENERATE:
                                    if (task.isSourceUpdated()) {
                                        // we need to reschedule the GEN task as the source data has changed
                                        log.debug("   Dependency ID " + dependency.getId() + " is in DONE and is going to be rescheduled as we need fresh data.");
                                        rescheduleTask(dependencyServiceTask, execService, dispatcherQueue);
                                        proceed = false;
                                    } else {
                                        log.debug("   Dependency ID " + dependency.getId() + " is in DONE and it is of type GENERATE, we can proceed.");
                                        // Nothing, we can proceed...
                                        try {
                                            dependencyQueue = schedulingPool.getQueueForTask(dependencyServiceTask);
                                        } catch (InternalErrorException e) {
                                            log.error("Could not get queue for task {}", dependencyServiceTask.getId());
                                        }
                                    }
                                    break;
                                case SEND:
                                    log.debug("   Dependency ID " + dependencyServiceTask.getId() + " is in DONE and it is of type SEND, we can proceed.");
                                    // Nothing, we can proceed...
                                    break;
                                default:
                                    throw new IllegalArgumentException("Unknown ExecService type. Expected GENERATE or SEND.");
                            }
                            break;
                        case ERROR:
                            switch(dependency.getExecServiceType()) {
                                case GENERATE:
                                    log.info("   Dependency ID " + dependencyServiceTask.getId() + " is in ERROR and it is of type GENERATE, we are gonna propagate.");
                                    // scheduleItAndWait(dependency, facility,
                                    // execService, dispatcherQueue);
                                    // try to run the generate task again
                                    rescheduleTask(dependencyServiceTask, execService, dispatcherQueue);
                                    proceed = false;
                                    break;
                                case SEND:
                                    log.info("   Dependency ID " + dependencyServiceTask.getId() + " is in ERROR and it is of type SEND, we are gonna end with ERROR.");
                                    proceed = false;
                                    // We end Task with error immediately.
                                    schedulingPool.setTaskStatus(task, TaskStatus.ERROR);
                                    // facility);
                                    break;
                                default:
                                    throw new IllegalArgumentException("Unknown ExecService type. Expected GENERATE or SEND.");
                            }
                            break;
                        case NONE:
                            log.info("   Last Task {} [dependency:" + dependency.getId() + ", facility:" + facility.getId() + "] was NONE, we are gonna propagate.", dependencyServiceTask.getId());
                            rescheduleTask(dependencyServiceTask, execService, dispatcherQueue);
                            proceed = false;
                            break;
                        case PLANNED:
                            log.info("   Dependency ID " + dependencyServiceTask.getId() + " is in PLANNED so we are gonna wait.");
                            // justWait(facility, execService);
                            if (dependencyScope.equals(DependencyScope.SERVICE)) {
                                proceed = false;
                            } else {
                                try {
                                    dependencyQueue = schedulingPool.getQueueForTask(dependencyServiceTask);
                                } catch (InternalErrorException e) {
                                    log.error("Could not get queue for task {}", dependencyServiceTask.getId());
                                }
                            }
                            break;
                        case PROCESSING:
                            log.info("   Dependency ID " + dependencyServiceTask.getId() + " is in PROCESSING so we are gonna wait.");
                            // justWait(facility, execService);
                            if (dependencyScope.equals(DependencyScope.SERVICE)) {
                                proceed = false;
                            } else {
                                try {
                                    dependencyQueue = schedulingPool.getQueueForTask(dependencyServiceTask);
                                } catch (InternalErrorException e) {
                                    log.error("Could not get queue for task {}", dependencyServiceTask.getId());
                                }
                            }
                            if (dependencyServiceTask.isPropagationForced() && !wasDependencyServiceTaskForced) {
                                // reschedule dependant only if originally was not forced !!!
                                rescheduleTask(dependencyServiceTask, execService, dispatcherQueue);
                            // XXX - should we proceed here?
                            }
                            break;
                        default:
                            throw new IllegalArgumentException("Unknown Task status. Expected DONE, ERROR, NONE, PLANNED or PROCESSING.");
                    }
                }
            }
            // #########################################
            if (proceed) {
                if (abortTask) {
                    // the SEND task is going to be aborted now
                    abortTask(task);
                    return false;
                } else {
                    if (dependencyQueue != null && dependencyQueue != dispatcherQueue) {
                        log.debug("Changing task {} destination queue to {} to match dependency task", task.getId(), dependencyQueue.getClientID());
                        try {
                            schedulingPool.setQueueForTask(task, dependencyQueue);
                        } catch (InternalErrorException e) {
                            log.error("Could not change task {} destination queue: {}", task.getId(), e.getMessage());
                        }
                    }
                    log.info("   SCHEDULING task [" + task.getId() + "], execService [" + execService.getId() + "] facility [" + facility.getId() + "] as PLANNED.");
                    task.setSchedule(time);
                    schedulingPool.setTaskStatus(task, TaskStatus.PLANNED);
                    sendToEngine(task);
                }
            // manipulateTasks(execService, facility, task);
            } else {
                if (abortTask) {
                    // the SEND task is going to be aborted now
                    abortTask(task);
                    return false;
                } else {
                    // If we can not proceed, we just end here.
                    // ########################################
                    // The current ExecService,Facility pair should be sleeping
                    // in SchedulingPool at the moment...
                    log.info("   Task {} state set to NONE, will be scheduled again at the next cycle.", task.getId());
                    schedulingPool.setTaskStatus(task, TaskStatus.NONE);
                }
            }
        } else if (execService.getExecServiceType().equals(ExecServiceType.GENERATE)) {
            log.debug("   Well, it is not. ExecService of type GENERATE does not have any dependencies by design, so we schedule it immediately.");
            log.info("   SCHEDULING task [" + task.getId() + "], execService [" + execService.getId() + "] facility [" + facility.getId() + "] as PLANNED.");
            task.setSchedule(time);
            schedulingPool.setTaskStatus(task, TaskStatus.PLANNED);
            sendToEngine(task);
        // manipulateTasks(execService, facility, task);
        } else {
            throw new IllegalArgumentException("Unknown ExecService type. Expected GENERATE or SEND.");
        }
    } else {
        log.debug("   We do not proceed, we put the task [" + task.getId() + "], [" + execService.getId() + "] execService to sleep.");
    }
    return true;
}
Also used : Task(cz.metacentrum.perun.taskslib.model.Task) DependencyScope(cz.metacentrum.perun.taskslib.dao.ExecServiceDependencyDao.DependencyScope) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) Service(cz.metacentrum.perun.core.api.Service) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Date(java.util.Date) ServiceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ServiceNotExistsException) DispatcherQueue(cz.metacentrum.perun.dispatcher.jms.DispatcherQueue) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) Facility(cz.metacentrum.perun.core.api.Facility) Pair(cz.metacentrum.perun.core.api.Pair)

Example 10 with FacilityNotExistsException

use of cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException in project perun by CESNET.

the class EventProcessorImpl method resolveMessage.

/**
	 * Get a message and id of this message.
	 * Parse the message and decide which way will be further processed.
	 * Using patterns and objects to choose the way.
	 *
	 * Additional Information:
	 * -> For user and serviceUser there is the same behavior.
	 * -> If there is only serviceUser (not serviceUser and user) the behavior for serviceUser is the same like for user (in LDAP)
	 * -> If there are 2 groups in one message, expecting the first is subGroup and second is parentGroup
	 *
	 * Possible ways (first and only 1 possible way with the lowest number is choose):
	 * -> 1) GROUP and MEMBER exist
	 *   -> 1.1) if member status is valid => add member to group in LDAP
	 *   -> 1.2) if member was totally removed from group (totally means there is no direct or indirect existence of member in this group yet)
	 *           => remove member from this group in LDAP
	 * -> 2) GROUP and PARENT_GROUP exist
	 *   -> 2.1) if there is message with adding subgroup => add group like subgroup of parentGroup in LDAP
	 * -> 3) GROUP AND RESOURCE exist
	 *   -> 3.1) if there is message with adding group to resource => add resource to group (like attribute) in LDAP
	 *   -> 3.2) if there is message with removing group from resource => remove resource from group (like attribute) in LDAP
	 * -> 4) only RESOURCE exists (resource must be before group because of
	 *   -> 4.1) if there is message with deleting resource => delete this resource from LDAP
	 *   -> 4.2) if there is message with createing resource => create this resource in LDAP
	 *   -> 4.3) if there is message with updating resource => update this resource in LDAP
	 * -> 5) only GROUP exists
	 *   -> 5.1) if there is message with deleting group => delete this group from LDAP
	 *   -> 5.2) if there is message with creating group => create this group in LDAP
	 *   -> 5.3) if there is message with updating group => update this group in LDAP
	 * -> 6) only MEMBER exists (RPC CALLING used)
	 *   -> 6.1) if there is message with changing of member state to valid => add member to all groups in LDAP where he needs to be
	 *   -> 6.2) if there is message with changing of member state to other than valid => remove member from all groups in LDAP where is needed
	 * -> 7) only VO exists
	 *   -> 7.1) if there is message with deleting vo => delete this vo from LDAP
	 *   -> 7.2) if there is message with creating vo => create this vo in LDAP
	 *   -> 7.3) if there is message with updating vo => update this vo in LDAP
	 * -> 8) USER and USER_EXT_SOURCE exist
	 *   -> 8.1) if there is message with adding userExtSource (IDP) to user => create or update attribute of user in LDAP
	 *   -> 8.2) if there is message with removing userExtSource (IDP) from user => remove or update attribute of user in LDAP
	 * -> 9) USER and ATTRIBUTE exist
	 *   -> 9.1) if there is message with setting attribute to user => set Attribute to user in LDAP
	 * -> 10) USER and ATTRIBUTE_DEFINITION exist
	 *   -> 10.1) if there is message with removing attribute from user => remove Attribute from user in LDAP
	 * -> 11) only USER exists
	 *   -> 11.1) if there is message with deleting user => delete user from LDAP
	 *   -> 11.2) if there is message with creating user => create user in LDAP
	 *   -> 11.3) if there is message with updating user => update user in LDAP
	 *   -> 11.4) if there is message with removing all attribute from user => remove all attributes from user in LDAP (only removeable attributes)
	 * -> 12) FACILITY and ATTRIBUTE exist
	 *   -> 12.1) if there is message with setting attribute to facility => set Attribute to resources (assigned to facility) in LDAP
	 * -> 13) FACILITY and ATTRIBUTE_DEF exist
	 *   -> 13.1) if there is message with removing attribute from facility => remove Attribute from resources (assigned to facility) in LDAP
	 * -> 14) in all other cases
	 *   -> 14.1) always => only log some information
	 *
	 * @param msg message which need to be parse and resolve
	 * @param idOfMessage id of paring/resolving message
	 *
	 * @throws InternalErrorException when some internal error in core occurs
	 */
protected void resolveMessage(String msg, Integer idOfMessage) throws InternalErrorException {
    List<PerunBean> listOfBeans = new ArrayList<PerunBean>();
    listOfBeans = AuditParser.parseLog(msg);
    //TemporaryDebug information for controling parsing of message.
    if (!listOfBeans.isEmpty()) {
        int i = 0;
        for (PerunBean p : listOfBeans) {
            i++;
            if (p != null)
                log.debug("There is object number " + i + ") " + p.serializeToString());
            else
                log.debug("There is unknow object which is null");
        }
    }
    //Fill perunBeans
    emptyAndFillPerunBeans(listOfBeans);
    //Log debug data for looking in messages
    log.debug("MessageNumber=" + idOfMessage + " -- OBJECTS: " + this.member + '/' + this.group + '/' + this.facility + "/" + this.parentGroup + '/' + this.vo + '/' + this.resource + '/' + this.user + '/' + this.attribute + '/' + this.attributeDef + '/' + this.userExtSource);
    //If specific user is the only one user in message, so behavior will be same for him like for any other user!
    if (this.specificUser != null && this.user == null)
        this.user = this.specificUser;
    // 1) IF GROUP AND MEMBER WERE FOUND, TRY TO WORK WITH GROUP-MEMBER SPECIFIC OPERATIONS
    if (this.group != null && this.member != null) {
        // 1.1) ONLY FOR VALID MEMBER WE ADD HIM TO THE GROUP IN LDAP
        if (this.member.getStatus().equals(Status.VALID)) {
            Matcher addedTo = addedToPattern.matcher(msg);
            if (addedTo.find()) {
                if (!ldapConnector.isAlreadyMember(this.member, this.group))
                    ldapConnector.addMemberToGroup(this.member, this.group);
            }
        }
        // 1.2) MEMBER WILL BE REMOVED FROM GROUP
        //Matcher removedFrom = removedFromPattern.matcher(msg);
        Matcher totallyRemovedFrom = totallyRemovedFromPatter.matcher(msg);
        if (totallyRemovedFrom.find()) {
            if (ldapConnector.isAlreadyMember(this.member, this.group))
                ldapConnector.removeMemberFromGroup(this.member, this.group);
        }
    // 2) IF 2 GROUPS WERE FOUND, TRY TO WORK WITH PARENTGROUP-SUBGROUP SPECIFIC OPERATIONS
    } else if (this.group != null && this.parentGroup != null) {
        Matcher newSubGroup = subGroupPattern.matcher(msg);
        // 2.1) ADD GROUP AS SUBGROUP TO PARENTGROUP
        if (newSubGroup.find()) {
            ldapConnector.addGroupAsSubGroup(this.group, this.parentGroup);
        }
    // 3) IF GROUP AND RESOURCE WERE FOUND, TRY TO WORK WITH GROUP-RESOURCE SPECIFIC OPERATIONS
    } else if (this.group != null && this.resource != null) {
        Matcher assigned = assignGroupToResource.matcher(msg);
        Matcher removed = removeGroupFromResource.matcher(msg);
        // 3.1) ADD NEW RESOURCE FOR GROUP IN LDAP
        if (assigned.find()) {
            updateGroupAttribute("assignedToResourceId", String.valueOf(this.resource.getId()), LdapOperation.ADD_ATTRIBUTE, this.group);
            updateResourceAttribute("assignedGroupId", String.valueOf(this.group.getId()), LdapOperation.ADD_ATTRIBUTE, this.resource);
        // 3.2) REMOVE RESOURCE FROM GROUP IN LDAP
        } else if (removed.find()) {
            updateGroupAttribute("assignedToResourceId", String.valueOf(this.resource.getId()), LdapOperation.REMOVE_ATTRIBUTE, this.group);
            updateResourceAttribute("assignedGroupId", String.valueOf(this.group.getId()), LdapOperation.REMOVE_ATTRIBUTE, this.resource);
        }
    // 4) IF ONLY RESOURCE WERE FOUND, TRY TO WORK WITH RESOURCE SPECIFIC OPERATIONS
    } else if (this.resource != null) {
        Matcher deleted = deletedResourcePattern.matcher(msg);
        Matcher created = createdPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        // 4.1) RESOURCE WILL BE DELETED
        if (deleted.find()) {
            ldapConnector.deleteResource(resource);
        // 4.2) RESOURCE WILL BE CREATED
        } else if (created.find()) {
            ldapConnector.createResource(resource, getFacilityEntityIdValue(resource.getFacilityId()));
        // 4.3) RESOURCE WILL BE UPDATED
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            replaceList.add(new Pair("cn", this.resource.getName()));
            if (this.resource.getDescription() != null && !this.resource.getDescription().isEmpty())
                replaceList.add(new Pair("description", this.resource.getDescription()));
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateResourceAttributes(attributes, this.resource);
        }
    // 5) IF ONLY GROUP WERE FOUND, TRY TO WORK WITH GROUP SPECIFIC OPERATIONS
    } else if (this.group != null) {
        Matcher deleted = deletedPattern.matcher(msg);
        Matcher newGroup = newGroupPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        // 5.1) GROUP WILL BE DELETED
        if (deleted.find()) {
            ldapConnector.removeGroup(this.group);
        // 5.2) GROUP WILL BE CREATED
        } else if (newGroup.find()) {
            ldapConnector.addGroup(this.group);
        // 5.3) GROUP WILL BE UPDATED
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            replaceList.add(new Pair("cn", this.group.getName()));
            replaceList.add(new Pair("perunUniqueGroupName", ldapConnector.getVoShortName(this.group.getVoId()) + ":" + this.group.getName()));
            if (this.group.getDescription() != null && !this.group.getDescription().isEmpty())
                replaceList.add(new Pair("description", this.group.getDescription()));
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateGroupAttributes(attributes, this.group);
        }
    // 6) IF MEMBER WAS FOUND, TRY TO WORK WITH MEMBER SPECIFIC OPERATIONS (! RPC CALLING used there !)
    } else if (this.member != null) {
        Matcher validated = validatedPattern.matcher(msg);
        Matcher otherStateOfMember = otherStateOfMemberPattern.matcher(msg);
        // 6.1) MEMBER WAS VALIDATED, NEED TO ADD HIM TO ALL GROUPS
        if (validated.find()) {
            List<Group> memberGroups = new ArrayList<Group>();
            try {
                memberGroups = Rpc.GroupsManager.getAllMemberGroups(ldapcManager.getRpcCaller(), this.member);
            } catch (MemberNotExistsException e) {
            //IMPORTATNT this is not problem, if member not exist, we expected that will be deleted in some message after that, in DB is deleted
            } catch (PrivilegeException e) {
                throw new InternalErrorException("There are no privilegies for getting member's groups", e);
            } catch (InternalErrorException e) {
                throw e;
            }
            for (Group g : memberGroups) {
                if (!ldapConnector.isAlreadyMember(this.member, g))
                    ldapConnector.addMemberToGroup(this.member, g);
            }
        // 6.2) MEMBER STATE WAS CHANGED TO OTHER STATE THAN VALIDATE
        } else if (otherStateOfMember.find()) {
            List<Group> memberGroups = new ArrayList<Group>();
            try {
                memberGroups = Rpc.GroupsManager.getAllMemberGroups(ldapcManager.getRpcCaller(), this.member);
            } catch (MemberNotExistsException e) {
            //IMPORTATNT this is not problem, if member not exist, we expected that will be deleted in some message after that, in DB is deleted
            } catch (PrivilegeException e) {
                throw new InternalErrorException("There are no privilegies for getting member's groups", e);
            } catch (InternalErrorException e) {
                throw e;
            }
            for (Group g : memberGroups) {
                if (ldapConnector.isAlreadyMember(this.member, g))
                    ldapConnector.removeMemberFromGroup(this.member, g);
            }
        }
    // 7) IF VO WAS FOUND, TRY TO WORK WITH VO SPECIFIC OPERATIONS
    } else if (this.vo != null) {
        Matcher deleted = deletedPattern.matcher(msg);
        Matcher created = createdPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        // 7.1) VO WILL BE DELETED
        if (deleted.find()) {
            ldapConnector.deleteVo(this.vo);
        // 7.2) VO WILL BE CREATED
        } else if (created.find()) {
            ldapConnector.createVo(this.vo);
        // 7.3) VO WILL BE UPDATED
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            replaceList.add(new Pair("description", this.vo.getName()));
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateVoAttributes(attributes, this.vo);
        }
    // 8) IF USER AND USEREXTSOURCE WERE FOUND, TRY TO WORK WITH USER-USEREXTSOURCE SPECIFIC OPERATIONS (LIKE SET EXT LOGINS FOR IDP EXTSOURCES)
    } else if (this.user != null && this.userExtSource != null) {
        Matcher addExtSource = addUserExtSource.matcher(msg);
        Matcher removeExtSource = removeUserExtSource.matcher(msg);
        // 8.1) ADD ATTRIBUTE WITH IDP EXTSOURCE
        if (addExtSource.find()) {
            if (this.userExtSource.getExtSource() != null && this.userExtSource.getExtSource().getType() != null) {
                String extLogin;
                if (this.userExtSource.getExtSource().getType().equals(ExtSourcesManager.EXTSOURCE_IDP)) {
                    extLogin = this.userExtSource.getLogin();
                    if (extLogin == null)
                        extLogin = "";
                    updateUserAttribute("eduPersonPrincipalNames", extLogin, LdapOperation.ADD_ATTRIBUTE, user);
                }
            }
        // 8.2) REMOVE ATTRIBUTE WITH IDP EXTSOURCE
        } else if (removeExtSource.find()) {
            if (this.userExtSource.getExtSource() != null && this.userExtSource.getExtSource().getType() != null) {
                String extLogin;
                if (this.userExtSource.getExtSource().getType().equals(ExtSourcesManager.EXTSOURCE_IDP)) {
                    extLogin = this.userExtSource.getLogin();
                    if (extLogin == null)
                        extLogin = "";
                    updateUserAttribute("eduPersonPrincipalNames", extLogin, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            }
        }
    // 9) IF USER AND ATTRIBUTE WERE FOUND, TRY TO WORK WITH USER-ATTR SPECIFIC OPERATIONS (LIKE SET USER ATTRIBUTES)
    } else if (this.user != null && this.attribute != null) {
        Matcher set = userSetPattern.matcher(msg);
        // 9.1) SOME USER ATTRIBUTE WILL BE PROBABLY SET (IF IT IS ONE OF SPECIFIC ATTRIBUTES)
        if (set.find()) {
            Matcher uidMatcher = userUidNamespace.matcher(this.attribute.getName());
            Matcher loginMatcher = userLoginNamespace.matcher(this.attribute.getName());
            //USER PREFERREDMAIL WILL BE SET
            if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":preferredMail")) {
                //this mean change of attribute preferredMail in User
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("preferredMail", (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, user);
                    updateUserAttribute("mail", (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, user);
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "preferredMail")) {
                        updateUserAttribute("preferredMail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                    if (ldapConnector.userAttributeExist(this.user, "mail")) {
                        updateUserAttribute("mail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            //USER ORGANIZATION WILL BE SET
            } else if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":organization")) {
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("o", (String) attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "o")) {
                        updateUserAttribute("o", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            //USER CERT DNS WILL BE SET (special method for updating)
            } else if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_VIRT + ":userCertDNs")) {
                Map<String, String> certDNsMap = new HashMap<String, String>();
                if (this.attribute.getValue() != null)
                    certDNsMap = (Map) this.attribute.getValue();
                else
                    certDNsMap = null;
                if (certDNsMap == null || certDNsMap.isEmpty()) {
                    if (ldapConnector.userAttributeExist(this.user, "userCertificateSubject")) {
                        updateUserAttribute("userCertificateSubject", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                } else {
                    Set<String> certSubjectsWithPrefixes = ((Map) this.attribute.getValue()).keySet();
                    Set<String> certSubjectsWithoutPrefixes = new HashSet<>();
                    //remove prefixes from certificates
                    for (String key : certSubjectsWithPrefixes) {
                        certSubjectsWithoutPrefixes.add(key.replaceFirst("^[0-9]+[:]", ""));
                    }
                    String[] subjectsArray = Arrays.copyOf(certSubjectsWithoutPrefixes.toArray(), certSubjectsWithoutPrefixes.toArray().length, String[].class);
                    ldapConnector.updateUsersCertSubjects(String.valueOf(this.user.getId()), subjectsArray);
                }
            //USER LIBRARY IDs WILL BE SET (special method for updating)
            } else if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":libraryIDs")) {
                List<String> libraryIDsList = new ArrayList<>();
                if (this.attribute.getValue() != null)
                    libraryIDsList = (ArrayList) this.attribute.getValue();
                else
                    libraryIDsList = null;
                if (libraryIDsList == null || libraryIDsList.isEmpty()) {
                    if (ldapConnector.userAttributeExist(this.user, "libraryIDs")) {
                        updateUserAttribute("libraryIDs", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                } else {
                    String[] subjectsArray = Arrays.copyOf(libraryIDsList.toArray(), libraryIDsList.toArray().length, String[].class);
                    ldapConnector.updateUsersLibraryIds(String.valueOf(this.user.getId()), subjectsArray);
                }
            //USER UID NUMBER WILL BE SET
            } else if (uidMatcher.find()) {
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("uidNumber;x-ns-" + this.attribute.getFriendlyNameParameter(), String.valueOf((Integer) this.attribute.getValue()), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "uidNumber;x-ns-" + this.attribute.getFriendlyNameParameter())) {
                        updateUserAttribute("uidNumber;x-ns-" + this.attribute.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            //USER LOGIN WILL BE SET
            } else if (loginMatcher.find()) {
                if (this.attribute.getValue() != null) {
                    updateUserAttribute("login;x-ns-" + this.attribute.getFriendlyNameParameter(), (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                    //if login is from loginNamespace (eg. EINFRA) (new value), then userPassword must be set or modified
                    if (ldapProperties.getLdapLoginNamespace().toLowerCase().equals(this.attribute.getFriendlyNameParameter())) {
                        updateUserAttribute("userPassword", "{SASL}" + this.attribute.getValue() + "@" + ldapProperties.getLdapLoginNamespace(), LdapOperation.REPLACE_ATTRIBUTE, this.user);
                    }
                } else {
                    if (ldapConnector.userAttributeExist(this.user, "login;x-ns-" + this.attribute.getFriendlyNameParameter())) {
                        updateUserAttribute("login;x-ns-" + this.attribute.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                    if (ldapProperties.getLdapLoginNamespace().toLowerCase().equals(this.attribute.getFriendlyNameParameter())) {
                        if (ldapConnector.userAttributeExist(this.user, "userPassword")) {
                            updateUserAttribute("userPassword", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                        }
                    }
                }
            }
        }
    // 10) IF USER AND ATTRIBTUE DEFINITION WERE FOUND, TRY TO WORK WITH USER-ATTRDEF SPECIFIC OPERATIONS
    } else if (this.user != null && attributeDef != null) {
        Matcher remove = userRemovePattern.matcher(msg);
        // 10.1) REMOVE SPECIFIC USER ATTRIBUTE
        if (remove.find() && ldapConnector.userExist(this.user)) {
            Matcher uidMatcher = userUidNamespace.matcher(this.attributeDef.getName());
            Matcher loginMatcher = userLoginNamespace.matcher(this.attributeDef.getName());
            if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":preferredMail")) {
                if (ldapConnector.userAttributeExist(this.user, "preferredMail")) {
                    updateUserAttribute("preferredMail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
                if (ldapConnector.userAttributeExist(this.user, "mail")) {
                    updateUserAttribute("mail", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            //TODO: organization (user) will not exists
            } else if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":organization")) {
                if (ldapConnector.userAttributeExist(this.user, "o")) {
                    updateUserAttribute("o", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_VIRT + ":userCertDNs")) {
                if (ldapConnector.userAttributeExist(this.user, "userCertificateSubject")) {
                    updateUserAttribute("userCertificateSubject", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_USER_ATTR_DEF + ":libraryIDs")) {
                if (ldapConnector.userAttributeExist(this.user, "libraryIDs")) {
                    updateUserAttribute("libraryIDs", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (uidMatcher.find()) {
                if (ldapConnector.userAttributeExist(this.user, "uidNumber;x-ns-" + this.attributeDef.getFriendlyNameParameter())) {
                    updateUserAttribute("uidNumber;x-ns-" + this.attributeDef.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else if (loginMatcher.find()) {
                if (ldapConnector.userAttributeExist(this.user, "login;x-ns-" + this.attributeDef.getFriendlyNameParameter())) {
                    updateUserAttribute("login;x-ns-" + this.attributeDef.getFriendlyNameParameter(), null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
                if (ldapProperties.getLdapLoginNamespace().toLowerCase().equals(this.attributeDef.getFriendlyNameParameter())) {
                    if (ldapConnector.userPasswordExists(this.user)) {
                        updateUserAttribute("userPassword", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                    }
                }
            }
        }
    // 11) IF ONLY USER WAS FOUND, TRY TO WORK WITH USER SPECIFIC OPERATIONS
    } else if (this.user != null) {
        Matcher deleted = deletedPattern.matcher(msg);
        Matcher created = createdPattern.matcher(msg);
        Matcher updated = updatedPattern.matcher(msg);
        Matcher removedAllAttrs = userAllAttrsRemovedPattern.matcher(msg);
        // 11.1) DELETE USER
        if (deleted.find()) {
            ldapConnector.deleteUser(this.user);
        // 11.2) CREATE USER
        } else if (created.find()) {
            ldapConnector.createUser(this.user);
        // 11.3) UPDATE USER
        } else if (updated.find()) {
            Map<LdapOperation, List<Pair<String, String>>> attributes = new HashMap<LdapOperation, List<Pair<String, String>>>();
            List<Pair<String, String>> replaceList = new ArrayList<Pair<String, String>>();
            String firstName = this.user.getFirstName();
            String lastName = this.user.getLastName();
            if (firstName == null)
                firstName = "";
            if (lastName == null || lastName.isEmpty())
                lastName = "N/A";
            replaceList.add(new Pair("sn", lastName));
            replaceList.add(new Pair("cn", firstName + " " + lastName));
            // IF firstName is empty, maybe need to be removed first
            if (firstName.isEmpty()) {
                //if first name exists and new one is empty, then remove it, else do nothing
                if (ldapConnector.userAttributeExist(this.user, "givenName")) {
                    updateUserAttribute("givenName", null, LdapOperation.REMOVE_ATTRIBUTE, this.user);
                }
            } else {
                //if first name is not empty, replace it by new first name
                replaceList.add(new Pair("givenName", firstName));
            }
            attributes.put(LdapOperation.REPLACE_ATTRIBUTE, replaceList);
            updateUserAttributes(attributes, this.user);
        // 11.4) REMOVE ALL USER ATTRIBUTES
        } else if (removedAllAttrs.find()) {
            if (ldapConnector.userExist(this.user)) {
                Attributes usersAttrs = ldapConnector.getAllUsersAttributes(this.user);
                List<ModificationItem> listOfItems = new ArrayList<ModificationItem>();
                if (usersAttrs != null) {
                    NamingEnumeration<? extends Attribute> attributesEnumeration;
                    attributesEnumeration = usersAttrs.getAll();
                    try {
                        while (attributesEnumeration.hasMore()) {
                            Attribute attr = attributesEnumeration.nextElement();
                            if (attr != null && attr.getID() != null) {
                                if (isRemovableUserAttribute(attr.getID())) {
                                    ModificationItem item = new ModificationItem(LdapOperation.REMOVE_ATTRIBUTE.getCode(), attr);
                                    listOfItems.add(item);
                                }
                            }
                        }
                    } catch (NamingException ex) {
                        throw new InternalErrorException("Error at Deleting All Users Attribute, throw namingException.", ex);
                    }
                }
                if (!listOfItems.isEmpty()) {
                    ModificationItem[] items = Arrays.copyOf(listOfItems.toArray(), listOfItems.toArray().length, ModificationItem[].class);
                    ldapConnector.updateUser(this.user, items);
                }
            }
        }
    //12) IF FACILITY AND ATTRIBUTE TO SET WAS FOUND
    } else if (this.facility != null && attribute != null) {
        Matcher set = facilitySetPattern.matcher(msg);
        // 12.1) SOME FACILITY ATTRIBUTE WILL BE PROBABLY SET (IF IT IS ONE OF SPECIFIC ATTRIBUTES)
        if (set.find()) {
            //EntityID WILL BE SET
            if (this.attribute.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_FACILITY_ATTR_DEF + ":entityID")) {
                try {
                    List<Resource> resources = Rpc.FacilitiesManager.getAssignedResources(ldapcManager.getRpcCaller(), this.facility);
                    //this mean change of attribute entityID in all assigned resources
                    if (this.attribute.getValue() != null) {
                        for (Resource res : resources) {
                            updateResourceAttribute("entityID", (String) this.attribute.getValue(), LdapOperation.REPLACE_ATTRIBUTE, res);
                        }
                    } else {
                        for (Resource res : resources) {
                            if (ldapConnector.resourceAttributeExist(res, "entityID")) {
                                updateResourceAttribute("entityID", null, LdapOperation.REMOVE_ATTRIBUTE, res);
                            }
                        }
                    }
                } catch (FacilityNotExistsException ex) {
                    //this probably means that facility is already removed, so also resources are removed and we just delete them in some other message
                    //so skip it just log
                    log.debug("Try to get resources from facility, but facility just not exists. Skip it!");
                } catch (PrivilegeException e) {
                    throw new InternalErrorException("There are no privilegies for getting all assigned resources of facility" + this.facility, e);
                }
            }
        }
    //13) IF FACILITY AND ATTRIBUTE DEF TO REMOVE WAS FOUND
    } else if (this.facility != null && attributeDef != null) {
        Matcher remove = facilityRemovePattern.matcher(msg);
        // 13.1) REMOVE SPECIFIC FACILITY ATTRIBUTE
        if (remove.find()) {
            if (this.attributeDef.getName().equals(cz.metacentrum.perun.core.api.AttributesManager.NS_FACILITY_ATTR_DEF + ":entityID")) {
                try {
                    List<Resource> resources = Rpc.FacilitiesManager.getAssignedResources(ldapcManager.getRpcCaller(), this.facility);
                    for (Resource res : resources) {
                        if (ldapConnector.resourceAttributeExist(res, "entityID")) {
                            updateResourceAttribute("entityID", null, LdapOperation.REMOVE_ATTRIBUTE, res);
                        }
                    }
                } catch (FacilityNotExistsException ex) {
                    //this probably means that facility is already removed, so also resources are removed and we just delete them in some other message
                    //so skip it just log
                    log.debug("Try to get resources from facility, but facility just not exists. Skip it!");
                } catch (PrivilegeException e) {
                    throw new InternalErrorException("There are no privilegies for getting all assigned resources of facility" + this.facility, e);
                }
            }
        }
    // 14) IN OTHER CASES
    } else {
        log.debug("Nothing to resolve for message with number : " + idOfMessage);
    }
}
Also used : LdapOperation(cz.metacentrum.perun.ldapc.beans.LdapOperation) Matcher(java.util.regex.Matcher) HashMap(java.util.HashMap) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) NamingEnumeration(javax.naming.NamingEnumeration) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) ArrayList(java.util.ArrayList) List(java.util.List) NamingException(javax.naming.NamingException) HashSet(java.util.HashSet) MemberNotExistsException(cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

FacilityNotExistsException (cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException)11 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)8 Facility (cz.metacentrum.perun.core.api.Facility)7 PrivilegeException (cz.metacentrum.perun.core.api.exceptions.PrivilegeException)5 Attribute (cz.metacentrum.perun.core.api.Attribute)4 ExecService (cz.metacentrum.perun.taskslib.model.ExecService)4 ArrayList (java.util.ArrayList)4 User (cz.metacentrum.perun.core.api.User)3 ServiceNotExistsException (cz.metacentrum.perun.core.api.exceptions.ServiceNotExistsException)3 UserNotExistsException (cz.metacentrum.perun.core.api.exceptions.UserNotExistsException)3 Date (java.util.Date)3 Group (cz.metacentrum.perun.core.api.Group)2 PerunSession (cz.metacentrum.perun.core.api.PerunSession)2 Resource (cz.metacentrum.perun.core.api.Resource)2 Service (cz.metacentrum.perun.core.api.Service)2 AttributeNotExistsException (cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException)2 ConsistencyErrorException (cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException)2 MemberNotExistsException (cz.metacentrum.perun.core.api.exceptions.MemberNotExistsException)2 WrongAttributeAssignmentException (cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException)2 DispatcherQueue (cz.metacentrum.perun.dispatcher.jms.DispatcherQueue)2