Search in sources :

Example 76 with PerunBl

use of cz.metacentrum.perun.core.bl.PerunBl in project perun by CESNET.

the class FacilitySynchronizer method synchronizeFacilities.

public void synchronizeFacilities() {
    PerunBl perun = (PerunBl) ldapcManager.getPerunBl();
    Set<Name> presentFacilities = new HashSet<Name>();
    boolean shouldWriteExceptionLog = true;
    try {
        log.debug("Getting list of facilities");
        List<Facility> facilities = perun.getFacilitiesManagerBl().getFacilities(ldapcManager.getPerunSession());
        for (Facility facility : facilities) {
            presentFacilities.add(perunFacility.getEntryDN(String.valueOf(facility.getId())));
            try {
                log.debug("Synchronizing facility {}", facility);
                log.debug("Getting list of attributes for facility {}", facility.getId());
                List<Attribute> attrs = new ArrayList<Attribute>();
                List<String> attrNames = fillPerunAttributeNames(perunFacility.getPerunAttributeNames());
                try {
                    // log.debug("Getting attribute {} for resource {}", attrName, resource.getId());
                    attrs.addAll(perun.getAttributesManagerBl().getAttributes(ldapcManager.getPerunSession(), facility, attrNames));
                } catch (PerunRuntimeException e) {
                    log.warn("No attributes {} found for facility {}: {}", attrNames, facility.getId(), e.getMessage());
                    shouldWriteExceptionLog = false;
                    throw new InternalErrorException(e);
                }
                log.debug("Got attributes {}", attrs.toString());
                perunFacility.synchronizeFacility(facility, attrs);
            } catch (PerunRuntimeException e) {
                if (shouldWriteExceptionLog) {
                    log.error("Error synchronizing facility", e);
                }
                shouldWriteExceptionLog = false;
                throw new InternalErrorException(e);
            }
        }
        try {
            removeOldEntries(perunFacility, presentFacilities, log);
        } catch (InternalErrorException e) {
            log.error("Error removing old facility entries", e);
            shouldWriteExceptionLog = false;
            throw new InternalErrorException(e);
        }
    } catch (PerunRuntimeException e) {
        if (shouldWriteExceptionLog) {
            log.error("Error reading list of facilities", e);
        }
        throw new InternalErrorException(e);
    }
}
Also used : Attribute(cz.metacentrum.perun.core.api.Attribute) ArrayList(java.util.ArrayList) PerunBl(cz.metacentrum.perun.core.bl.PerunBl) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Name(javax.naming.Name) PerunRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.PerunRuntimeException) Facility(cz.metacentrum.perun.core.api.Facility) PerunFacility(cz.metacentrum.perun.ldapc.model.PerunFacility) HashSet(java.util.HashSet)

Example 77 with PerunBl

use of cz.metacentrum.perun.core.bl.PerunBl in project perun by CESNET.

the class EventLoggerImpl method run.

@Override
public void run() {
    running = true;
    AuditMessage message = null;
    List<AuditMessage> messages;
    try {
        perunSession = auditLoggerManager.getPerunSession();
        perun = auditLoggerManager.getPerunBl();
        if (lastProcessedIdNumber == 0) {
            loadLastProcessedId();
        }
        messages = null;
        // If running is true, then this process will be continuously
        while (running) {
            int sleepTime = 1000;
            // Waiting for new messages. If consumer failed in some internal case, waiting until it will be repaired (waiting time is increases by each attempt)
            while (messages == null || messages.isEmpty()) {
                try {
                    // IMPORTANT STEP1: Get new bulk of messages
                    log.debug("Waiting for audit messages.");
                    messages = ((PerunBl) perun).getAuditMessagesManagerBl().pollConsumerMessages(perunSession, auditLoggerManager.getConsumerName(), lastProcessedIdNumber);
                    if (messages.size() > 0)
                        log.debug("Read {} new audit messages starting from {}", messages.size(), lastProcessedIdNumber);
                } catch (InternalErrorException ex) {
                    log.error("Consumer failed due to {}. Sleeping for {} ms.", ex, sleepTime);
                    Thread.sleep(sleepTime);
                    sleepTime += sleepTime;
                }
                // If there are no messages, sleep for 5 sec and then try it again
                if (messages == null || messages.isEmpty())
                    Thread.sleep(5000);
            }
            // If new messages exist, resolve them all
            Iterator<AuditMessage> messagesIterator = messages.iterator();
            log.debug("Trying to send {} messages", messages.size());
            while (messagesIterator.hasNext()) {
                message = messagesIterator.next();
                // Warning when two consecutive messages are separated by more than 15 ids
                if (lastProcessedIdNumber > 0 && lastProcessedIdNumber < message.getId()) {
                    if ((message.getId() - lastProcessedIdNumber) > 15)
                        log.debug("SKIP FLAG WARNING: lastProcessedIdNumber: {} - newMessageNumber: {} = {}", lastProcessedIdNumber, message.getId(), (lastProcessedIdNumber - message.getId()));
                }
                // IMPORTANT STEP2: send all messages to syslog
                if (this.logMessage(message) == 0) {
                    messagesIterator.remove();
                    lastProcessedIdNumber = message.getId();
                } else {
                    break;
                }
            }
            if (messages.isEmpty()) {
                log.debug("All messages sent.");
                messages = null;
            }
            // After all messages has been resolved, test interrupting of thread and if its ok, wait and go for another bulk of messages
            if (Thread.interrupted()) {
                running = false;
            } else {
                saveLastProcessedId();
                Thread.sleep(5000);
            }
        }
    // If auditlogger is interrupted
    } catch (InterruptedException e) {
        Date date = new Date();
        log.error("Last message has ID='{}' and was INTERRUPTED at {} due to interrupting.", ((message != null) ? message.getId() : 0), DATE_FORMAT.format(date));
        running = false;
        Thread.currentThread().interrupt();
    // If some other exception is thrown
    } catch (Exception e) {
        Date date = new Date();
        log.error("Last message has ID='{}' and was bad PARSED or EXECUTE at {} due to exception {}", ((message != null) ? message.getId() : 0), DATE_FORMAT.format(date), e.toString());
        throw new RuntimeException(e);
    } finally {
        saveLastProcessedId();
    }
}
Also used : AuditMessage(cz.metacentrum.perun.core.api.AuditMessage) PerunBl(cz.metacentrum.perun.core.bl.PerunBl) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Date(java.util.Date) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException)

Example 78 with PerunBl

use of cz.metacentrum.perun.core.bl.PerunBl in project perun by CESNET.

the class Utils method generateAllVosToWriter.

/**
	 * Method generate all Vos to the text for using in LDIF.
	 * Write all these information to writer in perunInitializer object.
	 *
	 * @param perunInitializer need to be loaded to get all needed dependencies
	 *
	 * @throws InternalErrorException if some problem with initializer or objects in perun-core
	 * @throws IOException if some problem with writer
	 */
public static void generateAllVosToWriter(PerunInitializer perunInitializer) throws InternalErrorException, IOException {
    //Load basic variables
    if (perunInitializer == null)
        throw new InternalErrorException("PerunInitializer must be loaded before using in generating methods!");
    PerunSession perunSession = perunInitializer.getPerunSession();
    PerunBl perun = perunInitializer.getPerunBl();
    BufferedWriter writer = perunInitializer.getOutputWriter();
    //Get list of all vos
    List<Vo> vos = perun.getVosManagerBl().getVos(perunSession);
    //For every vos get needed information and write them to the writer
    for (Vo vo : vos) {
        String dn = "dn: ";
        String desc = "description: ";
        String oc1 = "objectclass: top";
        String oc2 = "objectclass: organization";
        String oc3 = "objectclass: perunVO";
        String o = "o: ";
        String perunVoId = "perunVoId: ";
        perunVoId += String.valueOf(vo.getId());
        o += vo.getShortName();
        desc += vo.getName();
        dn += "perunVoId=" + vo.getId() + ",dc=perun,dc=cesnet,dc=cz";
        writer.write(dn + '\n');
        writer.write(oc1 + '\n');
        writer.write(oc2 + '\n');
        writer.write(oc3 + '\n');
        writer.write(o + '\n');
        writer.write(perunVoId + '\n');
        writer.write(desc + '\n');
        //Generate all members in member groups of this vo and add them here (only members with status Valid)
        List<Member> validMembers = perun.getMembersManagerBl().getMembers(perunSession, vo, Status.VALID);
        for (Member m : validMembers) {
            writer.write("uniqueMember: perunUserId=" + m.getUserId() + ",ou=People,dc=perun,dc=cesnet,dc=cz" + '\n');
        }
        writer.write('\n');
    }
}
Also used : PerunSession(cz.metacentrum.perun.core.api.PerunSession) PerunBl(cz.metacentrum.perun.core.bl.PerunBl) Vo(cz.metacentrum.perun.core.api.Vo) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Member(cz.metacentrum.perun.core.api.Member) BufferedWriter(java.io.BufferedWriter)

Example 79 with PerunBl

use of cz.metacentrum.perun.core.bl.PerunBl in project perun by CESNET.

the class Utils method generateAllUsersToWriter.

/**
	 * Method generate all Users to the text for using in LDIF.
	 * Write all these information to writer in perunInitializer object.
	 *
	 * @param perunInitializer need to be loaded to get all needed dependencies
	 *
	 * @throws InternalErrorException if some problem with initializer or objects in perun-core
	 * @throws IOException if some problem with writer
	 * @throws AttributeNotExistsException
	 * @throws WrongAttributeAssignmentException
	 */
public static void generateAllUsersToWriter(PerunInitializer perunInitializer) throws IOException, InternalErrorException, AttributeNotExistsException, WrongAttributeAssignmentException {
    //Load basic variables
    if (perunInitializer == null)
        throw new InternalErrorException("PerunInitializer must be loaded before using in generating methods!");
    PerunSession perunSession = perunInitializer.getPerunSession();
    PerunBl perun = perunInitializer.getPerunBl();
    BufferedWriter writer = perunInitializer.getOutputWriter();
    List<User> users = perun.getUsersManagerBl().getUsers(perunSession);
    for (User user : users) {
        String dn = "dn: ";
        String entryStatus = "entryStatus: active";
        String oc1 = "objectclass: top";
        String oc2 = "objectclass: person";
        String oc3 = "objectclass: organizationalPerson";
        String oc4 = "objectclass: inetOrgPerson";
        String oc5 = "objectclass: perunUser";
        String oc6 = "objectclass: tenOperEntry";
        String oc7 = "objectclass: inetUser";
        String sn = "sn: ";
        String cn = "cn: ";
        String givenName = "givenName: ";
        String perunUserId = "perunUserId: ";
        String mail = "mail: ";
        String preferredMail = "preferredMail: ";
        String o = "o: ";
        String isServiceUser = "isServiceUser: ";
        String isSponsoredUser = "isSponsoredUser: ";
        String userPassword = "userPassword: ";
        List<String> membersOf = new ArrayList<>();
        List<Member> members;
        Set<String> membersOfPerunVo = new HashSet<>();
        members = perun.getMembersManagerBl().getMembersByUser(perunSession, user);
        for (Member member : members) {
            if (member.getStatus().equals(Status.VALID)) {
                membersOfPerunVo.add("memberOfPerunVo: " + member.getVoId());
                List<Group> groups;
                groups = perun.getGroupsManagerBl().getAllMemberGroups(perunSession, member);
                for (Group group : groups) {
                    membersOf.add("memberOf: " + "perunGroupId=" + group.getId() + ",perunVoId=" + group.getVoId() + ",dc=perun,dc=cesnet,dc=cz");
                }
            }
        }
        //Attribute attrMail = perun.getAttributesManagerBl().getAttribute(perunSession, u, AttributesManager.NS_USER_ATTR_DEF + ":mail");
        Attribute attrPreferredMail = perun.getAttributesManagerBl().getAttribute(perunSession, user, AttributesManager.NS_USER_ATTR_DEF + ":preferredMail");
        Attribute attrOrganization = perun.getAttributesManagerBl().getAttribute(perunSession, user, AttributesManager.NS_USER_ATTR_DEF + ":organization");
        Attribute attrVirtCertDNs = perun.getAttributesManagerBl().getAttribute(perunSession, user, AttributesManager.NS_USER_ATTR_VIRT + ":userCertDNs");
        Attribute attrLibraryIDs = perun.getAttributesManagerBl().getAttribute(perunSession, user, AttributesManager.NS_USER_ATTR_DEF + ":libraryIDs");
        perunUserId += String.valueOf(user.getId());
        dn += "perunUserId=" + user.getId() + ",ou=People,dc=perun,dc=cesnet,dc=cz";
        String firstName = user.getFirstName();
        String lastName = user.getLastName();
        if (firstName == null)
            firstName = "";
        if (lastName == null || lastName.isEmpty())
            lastName = "N/A";
        sn += lastName;
        cn += firstName + " " + lastName;
        if (user.isServiceUser())
            isServiceUser += "1";
        else
            isServiceUser += "0";
        if (user.isSponsoredUser())
            isSponsoredUser += "1";
        else
            isSponsoredUser += "0";
        if (firstName.isEmpty())
            givenName = null;
        else
            givenName += firstName;
        if (attrPreferredMail == null || attrPreferredMail.getValue() == null)
            mail = null;
        else
            mail += (String) attrPreferredMail.getValue();
        if (attrPreferredMail == null || attrPreferredMail.getValue() == null)
            preferredMail = null;
        else
            preferredMail += (String) attrPreferredMail.getValue();
        if (attrOrganization == null || attrOrganization.getValue() == null)
            o = null;
        else
            o += (String) attrOrganization.getValue();
        Map<String, String> certDNs = null;
        Set<String> certSubjectsWithPrefix = null;
        Set<String> certSubjectsWithoutPrefix = new HashSet<>();
        if (attrVirtCertDNs != null && attrVirtCertDNs.getValue() != null) {
            certDNs = (Map) attrVirtCertDNs.getValue();
            certSubjectsWithPrefix = certDNs.keySet();
            for (String certSubject : certSubjectsWithPrefix) {
                certSubjectsWithoutPrefix.add(certSubject.replaceFirst("^[0-9]+[:]", ""));
            }
        }
        writer.write(dn + '\n');
        writer.write(oc1 + '\n');
        writer.write(oc2 + '\n');
        writer.write(oc3 + '\n');
        writer.write(oc4 + '\n');
        writer.write(oc5 + '\n');
        writer.write(oc6 + '\n');
        writer.write(oc7 + '\n');
        writer.write(entryStatus + '\n');
        writer.write(sn + '\n');
        writer.write(cn + '\n');
        if (givenName != null)
            writer.write(givenName + '\n');
        writer.write(perunUserId + '\n');
        writer.write(isServiceUser + '\n');
        writer.write(isSponsoredUser + '\n');
        if (mail != null)
            writer.write(mail + '\n');
        if (preferredMail != null)
            writer.write(preferredMail + '\n');
        if (o != null)
            writer.write(o + '\n');
        if (certSubjectsWithoutPrefix != null && !certSubjectsWithoutPrefix.isEmpty()) {
            for (String s : certSubjectsWithoutPrefix) {
                writer.write("userCertificateSubject: " + s + '\n');
            }
        }
        List<String> libraryIDs = new ArrayList<>();
        if (attrLibraryIDs.getValue() != null) {
            libraryIDs = (ArrayList) attrLibraryIDs.getValue();
        }
        if (libraryIDs != null && !libraryIDs.isEmpty()) {
            for (String id : libraryIDs) {
                writer.write("libraryIDs: " + id + '\n');
            }
        }
        //GET ALL USERS UIDs
        List<String> similarUids = perun.getAttributesManagerBl().getAllSimilarAttributeNames(perunSession, AttributesManager.NS_USER_ATTR_DEF + ":uid-namespace:");
        if (similarUids != null && !similarUids.isEmpty()) {
            for (String s : similarUids) {
                Attribute uidNamespace = perun.getAttributesManagerBl().getAttribute(perunSession, user, s);
                if (uidNamespace != null && uidNamespace.getValue() != null) {
                    writer.write("uidNumber;x-ns-" + uidNamespace.getFriendlyNameParameter() + ": " + uidNamespace.getValue().toString() + '\n');
                }
            }
        }
        //GET ALL USERS LOGINs
        List<String> similarLogins = perun.getAttributesManagerBl().getAllSimilarAttributeNames(perunSession, AttributesManager.NS_USER_ATTR_DEF + ":login-namespace:");
        if (similarLogins != null && !similarLogins.isEmpty()) {
            for (String s : similarLogins) {
                Attribute loginNamespace = perun.getAttributesManagerBl().getAttribute(perunSession, user, s);
                if (loginNamespace != null && loginNamespace.getValue() != null) {
                    writer.write("login;x-ns-" + loginNamespace.getFriendlyNameParameter() + ": " + loginNamespace.getValue().toString() + '\n');
                    if (loginNamespace.getFriendlyNameParameter().equals("einfra")) {
                        writer.write(userPassword + "{SASL}" + loginNamespace.getValue().toString() + '@' + loginNamespace.getFriendlyNameParameter().toUpperCase() + '\n');
                    }
                }
            }
        }
        //GET ALL USERS EXTlogins FOR EVERY EXTSOURCE WITH TYPE EQUALS IDP
        List<UserExtSource> userExtSources = perun.getUsersManagerBl().getUserExtSources(perunSession, user);
        List<String> extLogins = new ArrayList<>();
        for (UserExtSource ues : userExtSources) {
            if (ues != null && ues.getExtSource() != null) {
                String type = ues.getExtSource().getType();
                if (type != null) {
                    if (type.equals(ExtSourcesManager.EXTSOURCE_IDP)) {
                        String extLogin;
                        extLogin = ues.getLogin();
                        if (extLogin == null)
                            extLogin = "";
                        writer.write("eduPersonPrincipalNames: " + extLogin + '\n');
                    }
                }
            }
        }
        //ADD MEMBEROF ATTRIBUTE TO WRITER
        for (String s : membersOf) {
            writer.write(s + '\n');
        }
        //ADD MEMBEROFPERUNVO ATTRIBUTE TO WRITER
        for (String s : membersOfPerunVo) {
            writer.write(s + '\n');
        }
        writer.write('\n');
    }
}
Also used : Group(cz.metacentrum.perun.core.api.Group) PerunSession(cz.metacentrum.perun.core.api.PerunSession) User(cz.metacentrum.perun.core.api.User) Attribute(cz.metacentrum.perun.core.api.Attribute) ArrayList(java.util.ArrayList) PerunBl(cz.metacentrum.perun.core.bl.PerunBl) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) BufferedWriter(java.io.BufferedWriter) UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) Member(cz.metacentrum.perun.core.api.Member) HashSet(java.util.HashSet)

Example 80 with PerunBl

use of cz.metacentrum.perun.core.bl.PerunBl in project perun by CESNET.

the class GroupsManagerBlImpl method prepareGroupStructureSynchronizationAttribute.

/**
 * Creates new attribute, set it value and add attribute to list of attributes
 *
 * Method used by group structure synchronization
 *
 * @param sess perun session
 * @param attributeName name of the attribute
 * @param attributeValue string value which will be set to the attribute
 * @throws InternalErrorException
 * @throws AttributeNotExistsException
 */
private Attribute prepareGroupStructureSynchronizationAttribute(PerunSession sess, String attributeName, String attributeValue) throws AttributeNotExistsException {
    Attribute attributeToProcess = new Attribute(((PerunBl) sess.getPerun()).getAttributesManagerBl().getAttributeDefinition(sess, attributeName));
    attributeToProcess.setValue(attributeValue);
    return attributeToProcess;
}
Also used : Attribute(cz.metacentrum.perun.core.api.Attribute) PerunBl(cz.metacentrum.perun.core.bl.PerunBl)

Aggregations

PerunBl (cz.metacentrum.perun.core.bl.PerunBl)130 Attribute (cz.metacentrum.perun.core.api.Attribute)93 Before (org.junit.Before)65 PerunSessionImpl (cz.metacentrum.perun.core.impl.PerunSessionImpl)64 AttributesManagerBl (cz.metacentrum.perun.core.bl.AttributesManagerBl)48 User (cz.metacentrum.perun.core.api.User)41 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)37 ArrayList (java.util.ArrayList)22 Vo (cz.metacentrum.perun.core.api.Vo)21 Facility (cz.metacentrum.perun.core.api.Facility)19 UserExtSource (cz.metacentrum.perun.core.api.UserExtSource)19 ModulesUtilsBl (cz.metacentrum.perun.core.bl.ModulesUtilsBl)19 ExtSource (cz.metacentrum.perun.core.api.ExtSource)16 Member (cz.metacentrum.perun.core.api.Member)16 AttributeNotExistsException (cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException)16 UserExtSourceExistsException (cz.metacentrum.perun.core.api.exceptions.UserExtSourceExistsException)16 UsersManagerBl (cz.metacentrum.perun.core.bl.UsersManagerBl)15 WrongAttributeAssignmentException (cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException)14 GroupsManagerBl (cz.metacentrum.perun.core.bl.GroupsManagerBl)13 Group (cz.metacentrum.perun.core.api.Group)12