Search in sources :

Example 61 with PrivilegeException

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

the class ExecServiceDependencyDaoTest method beforeClass.

@Before
public void beforeClass() {
    try {
        perunSession = perun.getPerunSession(new PerunPrincipal("perunTests", ExtSourcesManager.EXTSOURCE_NAME_INTERNAL, ExtSourcesManager.EXTSOURCE_INTERNAL), new PerunClient());
    } catch (InternalErrorException e) {
        log.error(e.toString());
    }
    jdbcTemplate = new JdbcPerunTemplate(dataSource);
    // Test Owner
    int newOwnerId = 0;
    try {
        newOwnerId = Utils.getNewId(jdbcTemplate, "owners_id_seq");
    } catch (InternalErrorException e) {
        log.error(e.toString(), e);
    }
    testOwner = new Owner();
    testOwner.setContact("Call me babe");
    testOwner.setType(OwnerType.technical);
    testOwner.setName("Tester-" + Long.toHexString(System.currentTimeMillis()));
    testOwner.setId(newOwnerId);
    jdbcTemplate.update("insert into owners(id, name, contact, type) values (?,?,?,?)", newOwnerId, testOwner.getName(), testOwner.getContact(), testOwner.getType().toString());
    // Test Service #1
    testService1 = new Service();
    testService1.setName("Test_service_1_" + Long.toHexString(System.currentTimeMillis()));
    // Test Service #2
    testService2 = new Service();
    testService2.setName("Test_service_2_" + Long.toHexString(System.currentTimeMillis()));
    try {
        testService1.setId(servicesManager.createService(perunSession, testService1).getId());
        testService2.setId(servicesManager.createService(perunSession, testService2).getId());
    } catch (InternalErrorException e) {
        log.error(e.toString());
    } catch (PrivilegeException e) {
        log.error(e.toString());
    } catch (ServiceExistsException e) {
        log.error(e.toString());
    }
    // Test ExecService #1 (Parent:testService1)
    testExecService1 = new ExecService();
    testExecService1.setDefaultDelay(1);
    testExecService1.setDefaultRecurrence(1);
    testExecService1.setEnabled(true);
    testExecService1.setService(testService1);
    testExecService1.setScript("/hellish/test/script");
    testExecService1.setExecServiceType(ExecServiceType.GENERATE);
    try {
        testExecService1.setId(execServiceDao.insertExecService(testExecService1));
    } catch (InternalErrorException e) {
        log.error(e.toString(), e);
    }
    // Test ExecService #2 (Parent:testService1)
    testExecService2 = new ExecService();
    testExecService2.setDefaultDelay(2);
    testExecService2.setDefaultRecurrence(2);
    testExecService2.setEnabled(true);
    testExecService2.setService(testService1);
    testExecService2.setScript("/hellish/test/script2");
    testExecService2.setExecServiceType(ExecServiceType.SEND);
    try {
        testExecService2.setId(execServiceDao.insertExecService(testExecService2));
    } catch (InternalErrorException e) {
        log.error(e.toString(), e);
    }
    // Test ExecService #3 (Parent:testService2)
    testExecService3 = new ExecService();
    testExecService3.setDefaultDelay(3);
    testExecService3.setDefaultRecurrence(3);
    testExecService3.setEnabled(true);
    testExecService3.setService(testService2);
    testExecService3.setScript("/hellish/test/script3");
    testExecService3.setExecServiceType(ExecServiceType.SEND);
    try {
        testExecService3.setId(execServiceDao.insertExecService(testExecService3));
    } catch (InternalErrorException e) {
        log.error(e.toString(), e);
    }
}
Also used : JdbcPerunTemplate(org.springframework.jdbc.core.JdbcPerunTemplate) Owner(cz.metacentrum.perun.core.api.Owner) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) PerunClient(cz.metacentrum.perun.core.api.PerunClient) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) Service(cz.metacentrum.perun.core.api.Service) ServiceExistsException(cz.metacentrum.perun.core.api.exceptions.ServiceExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Before(org.junit.Before)

Example 62 with PrivilegeException

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

the class EventParserImpl method parseEvent.

@Override
public Task 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] New format:
		 * "task|[engine_id]|[task_id][is_forced]|[exec_service]|[facility]|[destination_list]|[dependency_list]"
		 * 
		 */
    // String eventParsingPattern =
    // "^event\\|([0-9]{1,6})\\|\\[([a-zA-Z0-9: ]+)\\]\\[([^\\]]+)\\]\\[(.*)\\]$";
    String eventParsingPattern = "^task\\|([0-9]{1,6})\\|\\[([0-9]+)\\]\\[([^\\]]+)\\]\\|\\[([^\\|]+)\\]\\|\\[([^\\|]+)\\]\\|\\[([^\\|]+)\\]\\|\\[(.*)\\]$";
    Pattern pattern = Pattern.compile(eventParsingPattern);
    Matcher matcher = pattern.matcher(event);
    boolean matchFound = matcher.find();
    if (matchFound) {
        log.debug("Message format matched ok...");
        String thisEngineID = matcher.group(1);
        // compare it...
        try {
            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"));
            }
        } catch (Exception e) {
            throw new InvalidEventMessageException("Wrong Engine ID: parse exception", e);
        }
        // Data should provide information regarding the target ExecService
        // (Processing rule).
        String eventTaskId = matcher.group(2);
        String eventIsForced = matcher.group(3);
        String eventExecService = matcher.group(4);
        String eventFacility = matcher.group(5);
        String eventDestinationList = matcher.group(6);
        String eventDependencyList = matcher.group(7);
        // check possible enconding
        if (!eventExecService.startsWith("ExecService")) {
            eventExecService = new String(Base64.decodeBase64(eventExecService));
        }
        if (!eventExecService.startsWith("ExecService")) {
            throw new InvalidEventMessageException("Wrong exec service: parse exception");
        }
        if (!eventFacility.startsWith("Facility")) {
            eventFacility = new String(Base64.decodeBase64(eventFacility));
        }
        if (!eventFacility.startsWith("Facility")) {
            throw new InvalidEventMessageException("Wrong facility: parse exception");
        }
        if (!eventDestinationList.startsWith("Destinations")) {
            eventDestinationList = new String(Base64.decodeBase64(eventDestinationList));
        }
        if (!eventDestinationList.startsWith("Destinations")) {
            throw new InvalidEventMessageException("Wrong destination list: parse exception");
        }
        log.debug("Event data to be parsed: task id " + eventTaskId + ", forced " + eventIsForced + ", facility " + eventFacility + ", exec service " + eventExecService + ", destination list " + eventDestinationList + ", dependency list " + eventDependencyList);
        // Prepare variables
        Facility facility;
        ExecService execService;
        List<Destination> destinationList = new ArrayList<Destination>();
        // resolve facility
        // deserialize event data
        List<PerunBean> listOfBeans = AuditParser.parseLog(eventFacility);
        try {
            facility = (Facility) listOfBeans.get(0);
        } catch (Exception e) {
            throw new InvalidEventMessageException("Could not resolve facility from event [" + eventFacility + "]", e);
        }
        // resolve exec service
        // deserialize event data
        listOfBeans = AuditParser.parseLog(eventExecService);
        try {
            execService = (ExecService) listOfBeans.get(0);
        } catch (Exception e) {
            throw new InvalidEventMessageException("Could not resolve exec service from event [" + eventExecService + "]", e);
        }
        // resolve list of destinations
        listOfBeans = AuditParser.parseLog(eventDestinationList);
        log.debug("Found list of destination beans: " + listOfBeans);
        // return new Pair<ExecService, Facility>(execService, facility);
        try {
            for (PerunBean bean : listOfBeans) {
                destinationList.add((Destination) bean);
            }
        } catch (Exception e) {
            throw new InvalidEventMessageException("Could not resolve list of destinations from event.", e);
        }
        Task task = new Task();
        task.setId(Integer.parseInt(eventTaskId));
        task.setFacility(facility);
        task.setExecService(execService);
        task.setDestinations(destinationList);
        task.setDelay(execService.getDefaultDelay());
        task.setRecurrence(execService.getDefaultRecurrence());
        task.setPropagationForced(Boolean.parseBoolean(eventIsForced));
        // resolve list of dependencies
        if (eventDependencyList != null) {
            for (String token : eventDependencyList.split("[\t ]*,[\t ]*")) {
                if (token.length() > 0) {
                    try {
                        dependenciesResolver.addDependency(task, Integer.parseInt(token));
                    } catch (Exception e) {
                        throw new InvalidEventMessageException("Invalid dependency in event: " + token);
                    }
                }
            }
        }
        return task;
    } else {
        throw new InvalidEventMessageException("Invalid message format: Message[" + event + "]");
    }
}
Also used : Pattern(java.util.regex.Pattern) Destination(cz.metacentrum.perun.core.api.Destination) Task(cz.metacentrum.perun.taskslib.model.Task) Matcher(java.util.regex.Matcher) ExecService(cz.metacentrum.perun.taskslib.model.ExecService) ArrayList(java.util.ArrayList) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) ServiceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ServiceNotExistsException) InvalidEventMessageException(cz.metacentrum.perun.engine.exceptions.InvalidEventMessageException) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) PerunBean(cz.metacentrum.perun.core.api.PerunBean) Facility(cz.metacentrum.perun.core.api.Facility) InvalidEventMessageException(cz.metacentrum.perun.engine.exceptions.InvalidEventMessageException)

Example 63 with PrivilegeException

use of cz.metacentrum.perun.core.api.exceptions.PrivilegeException 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 64 with PrivilegeException

use of cz.metacentrum.perun.core.api.exceptions.PrivilegeException 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)

Example 65 with PrivilegeException

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

the class EventProcessorImpl method getFacilityEntityIdValue.

/**
	 * Get entityID value from perun by facilityId.
	 *
	 * @param facilityId the facilityId
	 * @return value of entityID or null, if value is null or user not exists yet
	 * @throws InternalErrorException if some exception is thrown from RPC
	 */
private String getFacilityEntityIdValue(int facilityId) throws InternalErrorException {
    Facility facility = null;
    try {
        facility = Rpc.FacilitiesManager.getFacilityById(ldapcManager.getRpcCaller(), facilityId);
    } catch (PrivilegeException ex) {
        throw new InternalErrorException("There are no privilegies for getting facility by id.", ex);
    } catch (FacilityNotExistsException ex) {
        //If facility not exist in perun now, probably will be deleted in next step so its ok. The value is null anyway.
        return null;
    }
    cz.metacentrum.perun.core.api.Attribute entityID = null;
    try {
        entityID = Rpc.AttributesManager.getAttribute(ldapcManager.getRpcCaller(), facility, AttributesManager.NS_FACILITY_ATTR_DEF + ":entityID");
    } catch (PrivilegeException ex) {
        throw new InternalErrorException("There are no privilegies for getting facility attribute.", ex);
    } catch (AttributeNotExistsException ex) {
        throw new InternalErrorException("There is no such attribute.", ex);
    } catch (FacilityNotExistsException ex) {
        //If facility not exist in perun now, probably will be deleted in next step so its ok. The value is null anyway.
        return null;
    } catch (WrongAttributeAssignmentException ex) {
        throw new InternalErrorException("There is problem with wrong attribute assignment exception.", ex);
    }
    if (entityID.getValue() == null)
        return null;
    else
        return (String) entityID.getValue();
}
Also used : WrongAttributeAssignmentException(cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) cz.metacentrum.perun.core.api(cz.metacentrum.perun.core.api)

Aggregations

PrivilegeException (cz.metacentrum.perun.core.api.exceptions.PrivilegeException)66 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)22 Facility (cz.metacentrum.perun.core.api.Facility)18 BanOnFacility (cz.metacentrum.perun.core.api.BanOnFacility)13 Group (cz.metacentrum.perun.core.api.Group)13 RichFacility (cz.metacentrum.perun.core.api.RichFacility)13 Vo (cz.metacentrum.perun.core.api.Vo)8 RichGroup (cz.metacentrum.perun.core.api.RichGroup)7 ArrayList (java.util.ArrayList)7 User (cz.metacentrum.perun.core.api.User)6 Service (cz.metacentrum.perun.core.api.Service)5 FacilityNotExistsException (cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException)5 ServiceNotExistsException (cz.metacentrum.perun.core.api.exceptions.ServiceNotExistsException)5 Member (cz.metacentrum.perun.core.api.Member)4 RichMember (cz.metacentrum.perun.core.api.RichMember)4 IllegalArgumentException (cz.metacentrum.perun.core.api.exceptions.IllegalArgumentException)4 ExecService (cz.metacentrum.perun.taskslib.model.ExecService)4 Task (cz.metacentrum.perun.taskslib.model.Task)4 RichUser (cz.metacentrum.perun.core.api.RichUser)3 WrongAttributeAssignmentException (cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException)3