Search in sources :

Example 76 with Service

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

the class EventProcessor method createTaskFromEvent.

/**
 * Creates Task from Event data. Tries to resolve Service and Facility pairs from Event.
 * Events for non existing entities are discarded.
 *
 * @param event Event to parse
 * @throws ServiceNotExistsException When Service from Event doesn't exists anymore
 * @throws InvalidEventMessageException  When Message has invalid format.
 * @throws InternalErrorException  When implementation fails
 * @throws PrivilegeException  When dispatcher lack privileges to call core methods
 */
private void createTaskFromEvent(Event event) throws ServiceNotExistsException, InvalidEventMessageException, PrivilegeException {
    Map<Facility, Set<Service>> resolvedServices = eventServiceResolver.resolveEvent(event.getData());
    for (Entry<Facility, Set<Service>> map : resolvedServices.entrySet()) {
        Facility facility = map.getKey();
        for (Service service : map.getValue()) {
            if (!service.isEnabled()) {
                log.debug("Service not enabled: {}.", service);
                continue;
            }
            if (((PerunBl) perun).getServicesManagerBl().isServiceBlockedOnFacility(service, facility)) {
                log.debug("Service blocked on Facility: {} , {}.", service, facility);
                continue;
            }
            // Check if all destinations are not blocked
            try {
                // init session
                try {
                    if (sess == null) {
                        sess = perun.getPerunSession(new PerunPrincipal(dispatcherProperties.getProperty("perun.principal.name"), dispatcherProperties.getProperty("perun.principal.extSourceName"), dispatcherProperties.getProperty("perun.principal.extSourceType")), new PerunClient());
                    }
                } catch (InternalErrorException e1) {
                    log.error("Error establishing perun session to create Task from Event: ", e1);
                    continue;
                }
                List<Destination> destinations = perun.getServicesManager().getDestinations(sess, service, facility);
                if (destinations != null && !destinations.isEmpty()) {
                    Iterator<Destination> iter = destinations.iterator();
                    while (iter.hasNext()) {
                        Destination dest = iter.next();
                        if (((PerunBl) perun).getServicesManagerBl().isServiceBlockedOnDestination(service, dest.getId())) {
                            iter.remove();
                        }
                    }
                    if (destinations.isEmpty()) {
                        // All service destinations were blocked -> Task is denied to be sent to engine just like
                        // when service is blocked globally in Perun or on facility as a whole.
                        log.debug("{} blocked on all destinations on {}.", service, facility);
                        continue;
                    }
                }
            } catch (ServiceNotExistsException e) {
                log.error("Service not exist: {}.", service);
            } catch (FacilityNotExistsException e) {
                log.error("Facility not exist: {}.", facility);
            } catch (InternalErrorException | PrivilegeException e) {
                log.error("{}", e);
            }
            // check for presence of task for this <Service, Facility> pair
            // NOTE: this must be atomic enough to not create duplicate
            // tasks in schedulingPool (are we running in parallel
            // here?)
            boolean isForced = determineForcedPropagation(event);
            Task task = schedulingPool.getTask(facility, service);
            if (task != null) {
                // there already is a task in schedulingPool
                // signal that task needs to regenerate data and be forced next time
                task.setDestinations(null);
                task.setSourceUpdated(true);
                if (isForced)
                    task.setPropagationForced(true);
                task.setRecurrence(0);
                log.debug("[{}] Task is already in pool. Re-setting source updated and forced flags, {}.", task.getId(), task);
            } else {
                // no such task yet, create one
                task = new Task();
                task.setFacility(facility);
                task.setService(service);
                task.setStatus(TaskStatus.WAITING);
                task.setRecurrence(0);
                task.setDelay(service.getDelay());
                task.setSchedule(LocalDateTime.now());
                task.setSourceUpdated(false);
                task.setPropagationForced(isForced);
                try {
                    schedulingPool.addToPool(task);
                    log.debug("[{}] New Task added to pool. {}.", task.getId(), task);
                } catch (TaskStoreException e) {
                    log.error("[{}] Could not add Task to pool. Task {} will be lost: {}", task.getId(), task, e);
                }
                schedulingPool.scheduleTask(task, -1);
            }
        }
    }
}
Also used : Destination(cz.metacentrum.perun.core.api.Destination) Task(cz.metacentrum.perun.taskslib.model.Task) Set(java.util.Set) Service(cz.metacentrum.perun.core.api.Service) FacilityNotExistsException(cz.metacentrum.perun.core.api.exceptions.FacilityNotExistsException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) TaskStoreException(cz.metacentrum.perun.taskslib.exceptions.TaskStoreException) ServiceNotExistsException(cz.metacentrum.perun.core.api.exceptions.ServiceNotExistsException) PerunClient(cz.metacentrum.perun.core.api.PerunClient) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) PerunPrincipal(cz.metacentrum.perun.core.api.PerunPrincipal) Facility(cz.metacentrum.perun.core.api.Facility)

Example 77 with Service

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

the class EventParserImpl method parseEvent.

@Override
public Task parseEvent(String event) throws InvalidEventMessageException {
    log.info("Going to process event: {}", event);
    /*
		 * Expected string format:
		 * "task|[task_id][is_forced]|[service]|[facility]|[destination_list]|[dependency_list]"
		 *
		 *  String eventParsingPattern =
		 * "^event\\|([0-9]{1,6})\\|\\[([a-zA-Z0-9: ]+)\\]\\[([^\\]]+)\\]\\[(.*)\\]$";
		 */
    String eventParsingPattern = "^task\\|\\[([0-9]+)\\]\\[([^\\]]+)\\]\\|\\[([^\\|]+)\\]\\|\\[([^\\|]+)\\]\\|\\[([^\\|]+)\\]$";
    Pattern pattern = Pattern.compile(eventParsingPattern);
    Matcher matcher = pattern.matcher(event);
    boolean matchFound = matcher.find();
    if (matchFound) {
        log.debug("Message format matched ok...");
        // Data should provide information regarding the target Service (Processing rule).
        String eventTaskId = matcher.group(1);
        String eventIsForced = matcher.group(2);
        String eventService = matcher.group(3);
        String eventFacility = matcher.group(4);
        String eventDestinationList = matcher.group(5);
        // check possible enconding
        if (!eventService.startsWith("Service")) {
            eventService = new String(Base64.decodeBase64(eventService));
        }
        if (!eventService.startsWith("Service")) {
            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 {}, forced {}, facility {}, service {}, destination list {}", eventTaskId, eventIsForced, eventFacility, eventService, eventDestinationList);
        // Prepare variables
        Facility facility;
        Service service;
        List<Destination> destinationList = new ArrayList<Destination>();
        // resolve facility and 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 and deserialize event data
        listOfBeans = AuditParser.parseLog(eventService);
        try {
            service = (Service) listOfBeans.get(0);
        } catch (Exception e) {
            throw new InvalidEventMessageException("Could not resolve service from event [" + eventService + "]", e);
        }
        // resolve list of destinations
        listOfBeans = AuditParser.parseLog(eventDestinationList);
        log.debug("Found list of destination beans: {}", listOfBeans);
        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.setService(service);
        task.setDestinations(destinationList);
        task.setDelay(service.getDelay());
        task.setRecurrence(service.getRecurrence());
        task.setPropagationForced(Boolean.parseBoolean(eventIsForced));
        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) ArrayList(java.util.ArrayList) Service(cz.metacentrum.perun.core.api.Service) 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 78 with Service

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

the class ServicesManagerEntry method addDestination.

@Override
public Destination addDestination(PerunSession perunSession, List<Service> services, Facility facility, Destination destination) throws PrivilegeException, ServiceNotExistsException, FacilityNotExistsException, WrongPatternException {
    Utils.checkPerunSession(perunSession);
    Utils.notNull(services, "services");
    Utils.checkDestinationType(destination);
    getPerunBl().getFacilitiesManagerBl().checkFacilityExists(perunSession, facility);
    // Authorization
    if (!AuthzResolver.authorizedInternal(perunSession, "addDestination_List<Service>_Facility_Destination_policy", facility)) {
        throw new PrivilegeException(perunSession, "addDestination");
    }
    // prepare lists of facilities
    List<Facility> facilitiesByHostname;
    List<Facility> facilitiesByDestination = new ArrayList<>();
    if (destination.getType().equals(Destination.DESTINATIONHOSTTYPE) || destination.getType().equals(Destination.DESTINATIONUSERHOSTTYPE) || destination.getType().equals(Destination.DESTINATIONUSERHOSTPORTTYPE) || destination.getType().equals(Destination.DESTINATIONWINDOWS) || destination.getType().equals(Destination.DESTINATIONWINDOWSPROXY)) {
        facilitiesByHostname = getPerunBl().getFacilitiesManagerBl().getFacilitiesByHostName(perunSession, destination.getHostNameFromDestination());
        if (facilitiesByHostname.isEmpty())
            facilitiesByDestination = getPerunBl().getFacilitiesManagerBl().getFacilitiesByDestination(perunSession, destination.getHostNameFromDestination());
        if (!facilitiesByHostname.isEmpty()) {
            boolean hasRight = false;
            for (Facility facilityByHostname : facilitiesByHostname) {
                if (AuthzResolver.authorizedInternal(perunSession, "addDestination_List<Service>_Facility_Destination_policy", facilityByHostname)) {
                    hasRight = true;
                    break;
                }
            }
            if (!hasRight)
                throw new PrivilegeException("addDestination");
        }
        if (!facilitiesByDestination.isEmpty()) {
            boolean hasRight = false;
            for (Facility facilityByDestination : facilitiesByDestination) {
                if (AuthzResolver.authorizedInternal(perunSession, "addDestination_List<Service>_Facility_Destination_policy", facilityByDestination)) {
                    hasRight = true;
                    break;
                }
            }
            if (!hasRight)
                throw new PrivilegeException("addDestination");
        }
    }
    for (Service s : services) {
        getServicesManagerBl().checkServiceExists(perunSession, s);
    }
    Utils.notNull(destination, "destination");
    Utils.notNull(destination.getDestination(), "destination.destination");
    Utils.notNull(destination.getType(), "destination.type");
    return getServicesManagerBl().addDestination(perunSession, services, facility, destination);
}
Also used : PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) ArrayList(java.util.ArrayList) Service(cz.metacentrum.perun.core.api.Service) Facility(cz.metacentrum.perun.core.api.Facility)

Example 79 with Service

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

the class UsersManagerEntry method createListOfBeans.

/**
 * Create a list of PerunBeans from UserPageQuery.
 * If beanIds are not null it also checks if they exist. It will skip them otherwise.
 *
 * @param sess
 * @param query
 * @return list of PerunBeans created from the given parameters
 * @throws FacilityNotExistsException
 * @throws VoNotExistsException
 * @throws ServiceNotExistsException
 */
private List<PerunBean> createListOfBeans(PerunSession sess, UsersPageQuery query) throws FacilityNotExistsException, VoNotExistsException, ServiceNotExistsException {
    List<PerunBean> beans = new ArrayList<>();
    if (query.getFacilityId() != null) {
        Facility facility = perunBl.getFacilitiesManagerBl().getFacilityById(sess, query.getFacilityId());
        perunBl.getFacilitiesManagerBl().checkFacilityExists(sess, facility);
        beans.add(facility);
        if (query.getVoId() != null) {
            Vo vo = perunBl.getVosManagerBl().getVoById(sess, query.getVoId());
            getPerunBl().getVosManagerBl().checkVoExists(sess, vo);
            beans.add(vo);
        }
        if (query.getServiceId() != null) {
            Service service = perunBl.getServicesManagerBl().getServiceById(sess, query.getServiceId());
            getPerunBl().getServicesManagerBl().checkServiceExists(sess, service);
            beans.add(service);
        }
    }
    return beans;
}
Also used : PerunBean(cz.metacentrum.perun.core.api.PerunBean) ArrayList(java.util.ArrayList) Vo(cz.metacentrum.perun.core.api.Vo) Service(cz.metacentrum.perun.core.api.Service) Facility(cz.metacentrum.perun.core.api.Facility)

Example 80 with Service

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

the class AttributesManagerImpl method getRequiredAttributes.

@Override
public List<Attribute> getRequiredAttributes(PerunSession sess, List<Service> services, Resource resource, Group group) {
    try {
        MapSqlParameterSource parameters = new MapSqlParameterSource();
        List<String> namespace = new ArrayList<>();
        namespace.add(AttributesManager.NS_GROUP_RESOURCE_ATTR_DEF);
        namespace.add(AttributesManager.NS_GROUP_RESOURCE_ATTR_OPT);
        namespace.add(AttributesManager.NS_GROUP_RESOURCE_ATTR_VIRT);
        parameters.addValue("serviceIds", services.stream().map(Service::getId).collect(Collectors.toList()));
        parameters.addValue("groupId", group.getId());
        parameters.addValue("resourceId", resource.getId());
        parameters.addValue("namespaces", namespace);
        return namedParameterJdbcTemplate.query("select " + getAttributeMappingSelectQuery("grp_res") + " from attr_names " + "join service_required_attrs on id=service_required_attrs.attr_id and service_required_attrs.service_id in (:serviceIds) " + "left join    group_resource_attr_values     grp_res     on id=grp_res.attr_id     and   group_id=:groupId and resource_id=:resourceId " + "where namespace in (:namespaces)", parameters, new GroupResourceAttributeRowMapper(sess, this, group, resource));
    } catch (EmptyResultDataAccessException ex) {
        return new ArrayList<>();
    } catch (RuntimeException ex) {
        throw new InternalErrorException(ex);
    }
}
Also used : MapSqlParameterSource(org.springframework.jdbc.core.namedparam.MapSqlParameterSource) ArrayList(java.util.ArrayList) Service(cz.metacentrum.perun.core.api.Service) EmptyResultDataAccessException(org.springframework.dao.EmptyResultDataAccessException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException)

Aggregations

Service (cz.metacentrum.perun.core.api.Service)115 Test (org.junit.Test)64 AbstractPerunIntegrationTest (cz.metacentrum.perun.core.AbstractPerunIntegrationTest)55 Facility (cz.metacentrum.perun.core.api.Facility)31 ArrayList (java.util.ArrayList)26 Resource (cz.metacentrum.perun.core.api.Resource)22 Destination (cz.metacentrum.perun.core.api.Destination)20 Member (cz.metacentrum.perun.core.api.Member)17 User (cz.metacentrum.perun.core.api.User)17 Group (cz.metacentrum.perun.core.api.Group)15 Vo (cz.metacentrum.perun.core.api.Vo)13 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)13 Attribute (cz.metacentrum.perun.core.api.Attribute)11 RichUser (cz.metacentrum.perun.core.api.RichUser)11 PrivilegeException (cz.metacentrum.perun.core.api.exceptions.PrivilegeException)11 Task (cz.metacentrum.perun.taskslib.model.Task)10 AttributeDefinition (cz.metacentrum.perun.core.api.AttributeDefinition)8 PerunClient (cz.metacentrum.perun.core.api.PerunClient)8 PerunPrincipal (cz.metacentrum.perun.core.api.PerunPrincipal)8 ExecService (cz.metacentrum.perun.taskslib.model.ExecService)8