Search in sources :

Example 1 with PerunRuntimeException

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

the class Api method serve.

@SuppressWarnings("ConstantConditions")
private void serve(HttpServletRequest req, HttpServletResponse resp, boolean isGet, boolean isPut) throws IOException {
    Serializer ser = null;
    String manager = "N/A";
    String method = "N/A";
    boolean isJsonp = false;
    PerunRequest perunRequest = null;
    ApiCaller caller;
    String callbackName = req.getParameter("callback");
    long timeStart = System.currentTimeMillis();
    caller = (ApiCaller) req.getSession(true).getAttribute(APICALLER);
    OutputStream out = resp.getOutputStream();
    // init pending request in HTTP session
    if (req.getSession().getAttribute(PERUNREQUESTS) == null) {
        req.getSession().setAttribute(PERUNREQUESTS, new ConcurrentSkipListMap<String, PerunRequest>());
    }
    // store pending requests locally, because accessing it from session object after response is written would cause IllegalStateException
    @SuppressWarnings("unchecked") ConcurrentSkipListMap<String, PerunRequest> pendingRequests = ((ConcurrentSkipListMap<String, PerunRequest>) req.getSession().getAttribute(PERUNREQUESTS));
    // Check if it is request for list of pending operations.
    if (req.getPathInfo().equals("/jsonp/" + PERUNREQUESTSURL)) {
        // name used to identify pending request
        String callbackId = req.getParameter("callbackId");
        JsonSerializerJSONP serializer = new JsonSerializerJSONP(out, req, resp);
        resp.setContentType(serializer.getContentType());
        try {
            // Create a copy of the PERUNREQUESTS and then pass it to the serializer
            if (callbackId != null) {
                // return single entry
                serializer.write(pendingRequests.get(callbackId));
            } else {
                // return all pending requests
                serializer.write(Arrays.asList(pendingRequests.values().toArray()));
            }
        } catch (RpcException e) {
            serializer.writePerunRuntimeException(e);
        }
        out.close();
        return;
    }
    // prepare result object
    Object result = null;
    PrintWriter printWriter = null;
    try {
        // [0] format, [1] class, [2] method
        String[] fcm;
        try {
            if (req.getPathInfo() == null) {
                throw new RpcException(RpcException.Type.NO_PATHINFO);
            }
            fcm = req.getPathInfo().substring(1).split("/");
            if (fcm.length < 3 || fcm[0].isEmpty() || fcm[1].isEmpty() || fcm[2].isEmpty()) {
                throw new RpcException(RpcException.Type.INVALID_URL, req.getPathInfo());
            }
            manager = fcm[1];
            method = fcm[2];
            ser = selectSerializer(fcm[0], manager, method, out, req, resp);
            // what is the output format?
            if ("jsonp".equalsIgnoreCase(fcm[0])) {
                isJsonp = true;
            }
            if (ser instanceof PdfSerializer) {
                resp.addHeader("Content-Disposition", "attachment; filename=\"output.pdf\"");
            }
            resp.setContentType(ser.getContentType());
        } catch (RpcException rex) {
            // selects the default serializer (json) before throwing the exception
            ser = new JsonSerializer(out);
            resp.setContentType(ser.getContentType());
            throw rex;
        }
        // Initialize deserializer
        Deserializer des;
        if (isGet) {
            des = new UrlDeserializer(req);
        } else {
            des = selectDeserializer(fcm[0], req);
        }
        // We have new request, so do the whole auth/authz stuff
        if (caller == null) {
            caller = new ApiCaller(getServletContext(), setupPerunPrincipal(req, des), setupPerunClient(req));
            // Store the current session
            req.getSession(true).setAttribute(APICALLER, caller);
        } else if (!Objects.equals(caller.getSession().getPerunPrincipal().getExtSourceName(), getExtSourceName(req, des))) {
            // If the user is coming from the URL protected by different authN mechanism, destroy and create session again
            caller = new ApiCaller(getServletContext(), setupPerunPrincipal(req, des), setupPerunClient(req));
            req.getSession(true).setAttribute(APICALLER, caller);
        } else if (!Objects.equals(caller.getSession().getPerunPrincipal().getActor(), getActor(req, des)) && !caller.getSession().getPerunPrincipal().getExtSourceName().equals(ExtSourcesManager.EXTSOURCE_NAME_LOCAL)) {
            // prevent cookie stealing (if remote user changed, rebuild session)
            caller = new ApiCaller(getServletContext(), setupPerunPrincipal(req, des), setupPerunClient(req));
            req.getSession(true).setAttribute(APICALLER, caller);
        }
        // Does user want to logout from perun?
        if ("utils".equals(manager) && "logout".equals(method)) {
            if (req.getSession(false) != null) {
                req.getSession().removeAttribute(APICALLER);
                // deletes the cookies
                Cookie[] cookies = req.getCookies();
                if (cookies != null) {
                    final String SHIBBOLETH_COOKIE_FORMAT = "^_shib.+$";
                    for (Cookie c : cookies) {
                        // if shibboleth cookie
                        if (c.getName().matches(SHIBBOLETH_COOKIE_FORMAT)) {
                            // remove it
                            c.setValue("0");
                            c.setMaxAge(0);
                            // add updated cookie to the response
                            resp.addCookie(c);
                        }
                    }
                }
                // Invalidate session
                req.getSession().invalidate();
            }
            ser.write("Logout");
            // closes the request
            out.close();
            return;
        } else if ("utils".equals(manager) && "getGuiConfiguration".equals(method)) {
            ser.write(BeansUtils.getAllPropertiesFromCustomConfiguration("perun-web-gui.properties"));
            // closes the request
            out.close();
            return;
        } else if ("utils".equals(manager) && "getAppsConfig".equals(method)) {
            ser.write(PerunAppsConfig.getInstance());
            // closes the request
            out.close();
            return;
        } else if ("utils".equals(manager) && PERUNSTATUS.equals(method)) {
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            Map<String, Integer> auditerConsumers;
            // noinspection unchecked
            auditerConsumers = (Map<String, Integer>) caller.call("auditMessagesManager", "getAllAuditerConsumers", des);
            List<String> perunStatus = new ArrayList<>();
            perunStatus.add("Version of Perun: " + getPerunRpcVersion());
            perunStatus.add("Version of PerunDB: " + caller.call("databaseManager", "getCurrentDatabaseVersion", des));
            perunStatus.add("Version of Servlet: " + getServletContext().getServerInfo());
            perunStatus.add("Version of DB-driver: " + caller.call("databaseManager", "getDatabaseDriverInformation", des));
            perunStatus.add("Version of DB: " + caller.call("databaseManager", "getDatabaseInformation", des));
            perunStatus.add("Version of Java platform: " + System.getProperty("java.version"));
            for (String consumerName : auditerConsumers.keySet()) {
                Integer lastProcessedId = auditerConsumers.get(consumerName);
                perunStatus.add("AuditerConsumer: '" + consumerName + "' with last processed id='" + lastProcessedId + "'");
            }
            perunStatus.add("LastMessageId: " + caller.call("auditMessagesManager", "getLastMessageId", des));
            perunStatus.add("Timestamp: " + timestamp);
            ser.write(perunStatus);
            out.close();
            return;
        } else if ("utils".equals(manager) && PERUNSTATISTICS.equals(method)) {
            Date date = new Date();
            Timestamp timestamp = new Timestamp(date.getTime());
            List<String> perunStatistics = new ArrayList<>();
            perunStatistics.add("Timestamp: '" + timestamp + "'");
            perunStatistics.add("USERS: '" + caller.call("usersManager", "getUsersCount", des) + "'");
            perunStatistics.add("FACILITIES: '" + caller.call("facilitiesManager", "getFacilitiesCount", des) + "'");
            perunStatistics.add("DESTINATIONS: '" + caller.call("servicesManager", "getDestinationsCount", des) + "'");
            perunStatistics.add("VOS: '" + caller.call("vosManager", "getVosCount", des) + "'");
            perunStatistics.add("RESOURCES: '" + caller.call("resourcesManager", "getResourcesCount", des) + "'");
            perunStatistics.add("GROUPS: '" + caller.call("groupsManager", "getGroupsCount", des) + "'");
            perunStatistics.add("AUDITMESSAGES: '" + caller.call("auditMessagesManager", "getAuditerMessagesCount", des) + "'");
            ser.write(perunStatistics);
            out.close();
            return;
        } else if ("utils".equals(manager) && PERUNSYSTEMTIME.equals(method)) {
            long systemTimeInMillis = System.currentTimeMillis();
            ser.write(systemTimeInMillis);
            out.close();
        }
        // Store identification of the request only if supported by app (it passed unique callbackName)
        if (callbackName != null) {
            perunRequest = new PerunRequest(caller.getSession().getPerunPrincipal(), callbackName, manager, method, des.readAll());
            // Add perunRequest into the queue of the requests for POST only
            if (!isGet && !isPut) {
                pendingRequests.put(callbackName, perunRequest);
            }
        }
        PerunClient perunClient = caller.getSession().getPerunClient();
        if (perunClient.getType() == PerunClient.Type.OAUTH) {
            if (!perunClient.getScopes().contains(PerunClient.PERUN_API_SCOPE)) {
                // user has not consented to scope perun_api for the client on the OAuth Authorization Server
                throw new PrivilegeException("Scope " + PerunClient.PERUN_API_SCOPE + " is missing, either the client app " + perunClient.getId() + " has not asked for it, or the user has not granted it.");
            }
        }
        // Process request and sent the response back
        if (SCIMMANAGER.equals(manager)) {
            // Process SCIM protocol
            result = caller.getSCIMManager().process(caller.getSession(), method, des.readAll());
            if (perunRequest != null)
                perunRequest.setResult(result);
            if (!(result instanceof Response))
                throw new InternalErrorException("SCIM manager returned unexpected result: " + result);
            resp.setStatus(((Response) result).getStatus());
            String response = (String) ((Response) result).getEntity();
            printWriter = new PrintWriter(resp.getOutputStream());
            printWriter.println(response);
            printWriter.flush();
        } else {
            // Save only exceptions from caller to result
            try {
                result = caller.call(manager, method, des);
                if (perunRequest != null)
                    perunRequest.setResult(result);
            } catch (Exception ex) {
                result = ex;
                throw ex;
            }
            ser.write(result);
        }
    } catch (PerunException pex) {
        // If the output is JSONP, it cannot send the HTTP 400 code, because the web browser wouldn't accept this
        if (!isJsonp) {
            resp.setStatus(400);
        }
        log.warn("Perun exception {}: {}.", pex.getErrorId(), pex);
        ser.writePerunException(pex);
    } catch (PerunRuntimeException prex) {
        // If the output is JSONP, it cannot send the HTTP 400 code, because the web browser wouldn't accept this
        if (!isJsonp) {
            resp.setStatus(400);
        }
        log.warn("PerunRuntime exception {}: {}.", prex.getErrorId(), prex);
        ser.writePerunRuntimeException(prex);
    } catch (IOException ioex) {
        // IOException gets logged and is rethrown
        // noinspection ThrowableNotThrown
        log.warn("IO exception {}: {}.", Long.toHexString(System.currentTimeMillis()), ioex);
        new RpcException(RpcException.Type.UNCATCHED_EXCEPTION, ioex);
        throw ioex;
    } catch (Exception ex) {
        // If the output is JSONP, it cannot send the HTTP 400 code, because the web browser wouldn't accept this
        if (!isJsonp) {
            resp.setStatus(500);
        }
        log.warn("Perun exception {}: {}.", Long.toHexString(System.currentTimeMillis()), ex);
        ser.writePerunRuntimeException(new RpcException(RpcException.Type.UNCATCHED_EXCEPTION, ex));
    } finally {
        if (!isGet && !isPut && perunRequest != null) {
            // save result of this perunRequest
            perunRequest.setEndTime(System.currentTimeMillis());
            if (result instanceof Exception)
                perunRequest.setResult(result);
            perunRequest.setEndTime(System.currentTimeMillis());
        }
        // Check all resolved requests and remove them if they are old than timeToLiveWhenDone
        Iterator<String> iterator = pendingRequests.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            PerunRequest value = pendingRequests.get(key);
            if (value != null) {
                if (value.getEndTime() < 0)
                    continue;
                if (System.currentTimeMillis() - value.getEndTime() > timeToLiveWhenDone) {
                    iterator.remove();
                }
            }
        }
        if (printWriter != null)
            printWriter.close();
    }
    out.close();
    if (Objects.equals(manager, "authzResolver") && Objects.equals(method, "keepAlive")) {
        log.trace("Method {}.{} called by {} from {}, duration {} ms.", manager, method, caller.getSession().getPerunPrincipal().getActor(), caller.getSession().getPerunPrincipal().getExtSourceName(), (System.currentTimeMillis() - timeStart));
    } else {
        log.debug("Method {}.{} called by {} from {}, duration {} ms.", manager, method, caller.getSession().getPerunPrincipal().getActor(), caller.getSession().getPerunPrincipal().getExtSourceName(), (System.currentTimeMillis() - timeStart));
    }
}
Also used : OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) JsonSerializer(cz.metacentrum.perun.rpc.serializer.JsonSerializer) Timestamp(java.sql.Timestamp) RpcException(cz.metacentrum.perun.core.api.exceptions.RpcException) PerunRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.PerunRuntimeException) List(java.util.List) ArrayList(java.util.ArrayList) PerunRequest(cz.metacentrum.perun.core.api.PerunRequest) JsonSerializer(cz.metacentrum.perun.rpc.serializer.JsonSerializer) Serializer(cz.metacentrum.perun.rpc.serializer.Serializer) PdfSerializer(cz.metacentrum.perun.rpc.serializer.PdfSerializer) PrintWriter(java.io.PrintWriter) Cookie(javax.servlet.http.Cookie) PdfSerializer(cz.metacentrum.perun.rpc.serializer.PdfSerializer) UrlDeserializer(cz.metacentrum.perun.rpc.deserializer.UrlDeserializer) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) PerunException(cz.metacentrum.perun.core.api.exceptions.PerunException) IOException(java.io.IOException) Date(java.util.Date) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) ServletException(javax.servlet.ServletException) RpcException(cz.metacentrum.perun.core.api.exceptions.RpcException) CertificateParsingException(java.security.cert.CertificateParsingException) PerunRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.PerunRuntimeException) IOException(java.io.IOException) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) PerunException(cz.metacentrum.perun.core.api.exceptions.PerunException) Response(javax.ws.rs.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) JsonDeserializer(cz.metacentrum.perun.rpc.deserializer.JsonDeserializer) UrlDeserializer(cz.metacentrum.perun.rpc.deserializer.UrlDeserializer) Deserializer(cz.metacentrum.perun.rpc.deserializer.Deserializer) PerunClient(cz.metacentrum.perun.core.api.PerunClient) PrivilegeException(cz.metacentrum.perun.core.api.exceptions.PrivilegeException) JsonSerializerJSONP(cz.metacentrum.perun.rpc.serializer.JsonSerializerJSONP) Map(java.util.Map) HashMap(java.util.HashMap) ConcurrentSkipListMap(java.util.concurrent.ConcurrentSkipListMap)

Example 2 with PerunRuntimeException

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

the class UserSynchronizer method synchronizeUsers.

public void synchronizeUsers() {
    PerunBl perun = (PerunBl) ldapcManager.getPerunBl();
    ThreadPoolTaskExecutor syncExecutor = new ThreadPoolTaskExecutor();
    int poolIndex;
    boolean shouldWriteExceptionLog = true;
    for (poolIndex = 0; poolIndex < perunUser.length; poolIndex++) {
        perunUser[poolIndex] = context.getBean("perunUser", PerunUser.class);
    }
    try {
        log.debug("Getting list of users");
        List<User> users = perun.getUsersManagerBl().getUsers(ldapcManager.getPerunSession());
        Set<Name> presentUsers = new HashSet<Name>(users.size());
        syncExecutor.setCorePoolSize(5);
        syncExecutor.setMaxPoolSize(8);
        // syncExecutor.setQueueCapacity(30);
        syncExecutor.initialize();
        poolIndex = 0;
        taskCount = new AtomicInteger(0);
        for (User user : users) {
            presentUsers.add(perunUser[0].getEntryDN(String.valueOf(user.getId())));
            log.debug("Getting list of attributes for user {}", user.getId());
            List<Attribute> attrs = new ArrayList<Attribute>();
            List<String> attrNames = fillPerunAttributeNames(perunUser[poolIndex].getPerunAttributeNames());
            try {
                // log.debug("Getting attribute {} for user {}", attrName, user.getId());
                attrs.addAll(perun.getAttributesManagerBl().getAttributes(ldapcManager.getPerunSession(), user, attrNames));
            /* very chatty
						if(attr == null) {
							log.debug("Got null for attribute {}", attrName);
						} else if (attr.getValue() == null) {
							log.debug("Got attribute {} with null value", attrName);
						} else {
							log.debug("Got attribute {} with value {}", attrName, attr.getValue().toString());
						}
						*/
            } catch (PerunRuntimeException e) {
                log.warn("Couldn't get attributes {} for user {}: {}", attrNames, user.getId(), e.getMessage());
                shouldWriteExceptionLog = false;
                throw new InternalErrorException(e);
            }
            log.debug("Got attributes {}", attrNames.toString());
            try {
                // log.debug("Synchronizing user {} with {} attrs", user, attrs.size());
                // perunUser.synchronizeEntry(user, attrs);
                log.debug("Getting list of member groups for user {}", user.getId());
                Set<Integer> voIds = new HashSet<>();
                List<Member> members = perun.getMembersManagerBl().getMembersByUser(ldapcManager.getPerunSession(), user);
                List<Group> groups = new ArrayList<Group>();
                for (Member member : members) {
                    if (member.getStatus().equals(Status.VALID)) {
                        voIds.add(member.getVoId());
                        groups.addAll(perun.getGroupsManagerBl().getAllGroupsWhereMemberIsActive(ldapcManager.getPerunSession(), member));
                    }
                }
                // log.debug("Synchronizing user {} with {} VOs and {} groups", user.getId(), voIds.size(), groups.size());
                // perunUser.synchronizeMembership(user, voIds, groups);
                log.debug("Getting list of extSources for user {}", user.getId());
                List<UserExtSource> userExtSources = perun.getUsersManagerBl().getUserExtSources(ldapcManager.getPerunSession(), user);
                List<Group> admin_groups = perun.getUsersManagerBl().getGroupsWhereUserIsAdmin(ldapcManager.getPerunSession(), user);
                List<Vo> admin_vos = perun.getUsersManagerBl().getVosWhereUserIsAdmin(ldapcManager.getPerunSession(), user);
                List<Facility> admin_facilities = perun.getFacilitiesManagerBl().getFacilitiesWhereUserIsAdmin(ldapcManager.getPerunSession(), user);
                // log.debug("Synchronizing user {} with {} extSources", user.getId(), userExtSources.size());
                // perunUser.synchronizePrincipals(user, userExtSources);
                syncExecutor.execute(new SyncUsersWorker(poolIndex, user, attrs, voIds, groups, userExtSources, admin_groups, admin_vos, admin_facilities));
                taskCount.incrementAndGet();
            } catch (PerunRuntimeException e) {
                log.error("Error synchronizing user", e);
                shouldWriteExceptionLog = false;
                throw new InternalErrorException(e);
            }
            poolIndex = (poolIndex + 1) % perunUser.length;
        }
        try {
            removeOldEntries(perunUser[0], presentUsers, log);
        } catch (InternalErrorException e) {
            log.error("Error removing old user entries", e);
            shouldWriteExceptionLog = false;
            throw new InternalErrorException(e);
        }
    } catch (PerunRuntimeException e) {
        if (shouldWriteExceptionLog) {
            log.error("Error synchronizing users", e);
        }
        throw new InternalErrorException(e);
    } finally {
        // wait for all the tasks to get executed
        while (!syncExecutor.getThreadPoolExecutor().getQueue().isEmpty()) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                break;
            }
        }
        // wait for all the tasks to complete (for at most 10 seconds)
        for (int i = 0; i < 10 && taskCount.get() > 0; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                break;
            }
        }
        syncExecutor.shutdown();
        for (poolIndex = 0; poolIndex < perunUser.length; poolIndex++) {
            perunUser[poolIndex] = null;
        }
    }
    if (wasThreadException) {
        throw new InternalErrorException("Error synchronizing user in executed thread");
    }
}
Also used : Group(cz.metacentrum.perun.core.api.Group) PerunUser(cz.metacentrum.perun.ldapc.model.PerunUser) 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) Name(javax.naming.Name) PerunRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.PerunRuntimeException) Vo(cz.metacentrum.perun.core.api.Vo) PerunUser(cz.metacentrum.perun.ldapc.model.PerunUser) Member(cz.metacentrum.perun.core.api.Member) HashSet(java.util.HashSet) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) UserExtSource(cz.metacentrum.perun.core.api.UserExtSource) ThreadPoolTaskExecutor(org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor) Facility(cz.metacentrum.perun.core.api.Facility)

Example 3 with PerunRuntimeException

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

the class VOSynchronizer method synchronizeVOs.

public void synchronizeVOs() {
    PerunBl perun = (PerunBl) ldapcManager.getPerunBl();
    boolean shouldWriteExceptionLog = true;
    try {
        log.debug("Getting list of VOs");
        // List<Vo> vos = Rpc.VosManager.getVos(ldapcManager.getRpcCaller());
        List<Vo> vos = perun.getVosManagerBl().getVos(ldapcManager.getPerunSession());
        Set<Name> presentVos = new HashSet<Name>(vos.size());
        for (Vo vo : vos) {
            // Map<String, Object> params = new HashMap<String, Object>();
            // params.put("vo", new Integer(vo.getId()));
            presentVos.add(perunVO.getEntryDN(String.valueOf(vo.getId())));
            log.debug("Synchronizing VO entry {}", vo);
            log.debug("Getting list of attributes for vo {}", vo.getId());
            List<Attribute> attrs = new ArrayList<Attribute>();
            List<String> attrNames = fillPerunAttributeNames(perunVO.getPerunAttributeNames());
            try {
                attrs.addAll(perun.getAttributesManagerBl().getAttributes(ldapcManager.getPerunSession(), vo, attrNames));
            } catch (PerunRuntimeException e) {
                log.warn("Couldn't get attributes {} for vo {}: {}", attrNames, vo.getId(), e.getMessage());
                shouldWriteExceptionLog = false;
                throw new InternalErrorException(e);
            }
            log.debug("Got attributes {}", attrNames.toString());
            try {
                log.debug("Getting list of VO {} members", vo.getId());
                // List<Member> members = ldapcManager.getRpcCaller().call("membersManager", "getMembers", params).readList(Member.class);
                List<Member> members = perun.getMembersManager().getMembers(ldapcManager.getPerunSession(), vo, Status.VALID);
                log.debug("Synchronizing {} members of VO {}", members.size(), vo.getId());
                perunVO.synchronizeVo(vo, attrs, members);
            } catch (PerunException e) {
                log.error("Error synchronizing VO " + vo.getId(), e);
                shouldWriteExceptionLog = false;
                throw new InternalErrorException(e);
            }
        }
        // search VO entries in LDAP and remove the ones not present in Perun
        try {
            removeOldEntries(perunVO, presentVos, log);
        } catch (InternalErrorException e) {
            log.error("Error removing old VO entries", e);
            shouldWriteExceptionLog = false;
            throw new InternalErrorException(e);
        }
    } catch (InternalErrorException e) {
        if (shouldWriteExceptionLog) {
            log.error("Error getting list of VOs", 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) PerunException(cz.metacentrum.perun.core.api.exceptions.PerunException) Name(javax.naming.Name) Vo(cz.metacentrum.perun.core.api.Vo) PerunRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.PerunRuntimeException) Member(cz.metacentrum.perun.core.api.Member) HashSet(java.util.HashSet)

Example 4 with PerunRuntimeException

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

the class GroupSynchronizer method synchronizeGroups.

public void synchronizeGroups() {
    PerunBl perun = (PerunBl) ldapcManager.getPerunBl();
    boolean shouldWriteExceptionLog = true;
    try {
        log.debug("Group synchronization - getting list of VOs");
        List<Vo> vos = perun.getVosManagerBl().getVos(ldapcManager.getPerunSession());
        Set<Name> presentGroups = new HashSet<Name>();
        for (Vo vo : vos) {
            try {
                log.debug("Getting list of groups for VO {}", vo);
                List<Group> groups = perun.getGroupsManagerBl().getAllGroups(ldapcManager.getPerunSession(), vo);
                for (Group group : groups) {
                    presentGroups.add(perunGroup.getEntryDN(String.valueOf(vo.getId()), String.valueOf(group.getId())));
                    log.debug("Synchronizing group {}", group);
                    log.debug("Getting list of attributes for group {}", group.getId());
                    List<Attribute> attrs = new ArrayList<Attribute>();
                    List<String> attrNames = fillPerunAttributeNames(perunGroup.getPerunAttributeNames());
                    try {
                        attrs.addAll(perun.getAttributesManagerBl().getAttributes(ldapcManager.getPerunSession(), group, attrNames));
                    } catch (PerunRuntimeException e) {
                        log.warn("Couldn't get attributes {} for group {}: {}", attrNames, group.getId(), e.getMessage());
                        shouldWriteExceptionLog = false;
                        throw new InternalErrorException(e);
                    }
                    log.debug("Got attributes {}", attrNames.toString());
                    try {
                        log.debug("Getting list of members for group {}", group.getId());
                        // List<Member> members = ldapcManager.getRpcCaller().call("groupsManager",  "getGroupMembers", params).readList(Member.class);
                        List<Member> members = perun.getGroupsManagerBl().getActiveGroupMembers(ldapcManager.getPerunSession(), group, Status.VALID);
                        log.debug("Synchronizing {} members of group {}", members.size(), group.getId());
                        // perunGroup.synchronizeMembers(group, members);
                        log.debug("Getting list of resources assigned to group {}", group.getId());
                        // List<Resource> resources = Rpc.ResourcesManager.getAssignedResources(ldapcManager.getRpcCaller(), group);
                        List<Resource> resources = perun.getResourcesManagerBl().getAssignedResources(ldapcManager.getPerunSession(), group);
                        log.debug("Synchronizing {} resources assigned to group {}", resources.size(), group.getId());
                        // perunGroup.synchronizeResources(group, resources);
                        GroupsManagerBl groupsManager = perun.getGroupsManagerBl();
                        List<Group> admin_groups = groupsManager.getGroupsWhereGroupIsAdmin(ldapcManager.getPerunSession(), group);
                        List<Vo> admin_vos = groupsManager.getVosWhereGroupIsAdmin(ldapcManager.getPerunSession(), group);
                        List<Facility> admin_facilities = groupsManager.getFacilitiesWhereGroupIsAdmin(ldapcManager.getPerunSession(), group);
                        log.debug("Synchronizing group {} as admin of {} groups, {} VOs and {} facilities", group.getId(), admin_groups.size(), admin_vos.size(), admin_facilities.size());
                        perunGroup.synchronizeGroup(group, attrs, members, resources, admin_groups, admin_vos, admin_facilities);
                    } catch (PerunRuntimeException e) {
                        log.error("Error synchronizing group", e);
                        shouldWriteExceptionLog = false;
                        throw new InternalErrorException(e);
                    }
                }
            } catch (PerunRuntimeException e) {
                if (shouldWriteExceptionLog) {
                    log.error("Error synchronizing groups", e);
                }
                shouldWriteExceptionLog = false;
                throw new InternalErrorException(e);
            }
        }
        try {
            removeOldEntries(perunGroup, presentGroups, log);
        } catch (InternalErrorException e) {
            log.error("Error removing old group entries", e);
            shouldWriteExceptionLog = false;
            throw new InternalErrorException(e);
        }
    } catch (InternalErrorException e) {
        if (shouldWriteExceptionLog) {
            log.error("Error reading list of VOs", e);
        }
        throw new InternalErrorException(e);
    }
}
Also used : Group(cz.metacentrum.perun.core.api.Group) PerunGroup(cz.metacentrum.perun.ldapc.model.PerunGroup) GroupsManagerBl(cz.metacentrum.perun.core.bl.GroupsManagerBl) Attribute(cz.metacentrum.perun.core.api.Attribute) ArrayList(java.util.ArrayList) Resource(cz.metacentrum.perun.core.api.Resource) PerunBl(cz.metacentrum.perun.core.bl.PerunBl) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Name(javax.naming.Name) Vo(cz.metacentrum.perun.core.api.Vo) PerunRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.PerunRuntimeException) Facility(cz.metacentrum.perun.core.api.Facility) Member(cz.metacentrum.perun.core.api.Member) HashSet(java.util.HashSet)

Example 5 with PerunRuntimeException

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

the class ResourceSynchronizer method synchronizeResources.

public void synchronizeResources() {
    PerunBl perun = (PerunBl) ldapcManager.getPerunBl();
    boolean shouldWriteExceptionLog = true;
    try {
        log.debug("Resource synchronization - getting list of VOs");
        // List<Vo> vos = Rpc.VosManager.getVos(ldapcManager.getRpcCaller());
        List<Vo> vos = perun.getVosManagerBl().getVos(ldapcManager.getPerunSession());
        Set<Name> presentResources = new HashSet<Name>();
        for (Vo vo : vos) {
            try {
                log.debug("Getting list of resources for VO {}", vo);
                // List<Resource> resources = ldapcManager.getRpcCaller().call("resourceManager", "getResources", params).readList(Resource.class);
                List<Resource> resources = perun.getResourcesManagerBl().getResources(ldapcManager.getPerunSession(), vo);
                for (Resource resource : resources) {
                    presentResources.add(perunResource.getEntryDN(String.valueOf(vo.getId()), String.valueOf(resource.getId())));
                    try {
                        log.debug("Getting list of attributes for resource {}", resource.getId());
                        List<Attribute> attrs = new ArrayList<Attribute>();
                        /*
							 *  replaced with single call
							 *
							for(String attrName: fillPerunAttributeNames(perunResource.getPerunAttributeNames())) {
								try {
									//log.debug("Getting attribute {} for resource {}", attrName, resource.getId());
									attrs.add(perun.getAttributesManager().getAttribute(ldapcManager.getPerunSession(), facility, attrName));
								} catch (PerunException e) {
									log.warn("No attribute {} found for resource {}: {}", attrName, resource.getId(), e.getMessage());
								}
							}
							*/
                        List<String> attrNames = fillPerunAttributeNames(perunResource.getPerunAttributeNames());
                        try {
                            // log.debug("Getting attribute {} for resource {}", attrName, resource.getId());
                            attrs.addAll(perun.getAttributesManagerBl().getAttributes(ldapcManager.getPerunSession(), resource, attrNames));
                        } catch (PerunRuntimeException e) {
                            log.warn("No attributes {} found for resource {}: {}", attrNames, resource.getId(), e.getMessage());
                            shouldWriteExceptionLog = false;
                            throw new InternalErrorException(e);
                        }
                        log.debug("Got attributes {}", attrs.toString());
                        log.debug("Synchronizing resource {} with {} attrs", resource, attrs.size());
                        // perunResource.synchronizeEntry(resource, attrs);
                        log.debug("Getting list of assigned group for resource {}", resource.getId());
                        List<Group> assignedGroups = perun.getResourcesManagerBl().getAssignedGroups(ldapcManager.getPerunSession(), resource);
                        log.debug("Synchronizing {} groups for resource {}", assignedGroups.size(), resource.getId());
                        // perunResource.synchronizeGroups(resource, assignedGroups);
                        perunResource.synchronizeResource(resource, attrs, assignedGroups);
                    } catch (PerunRuntimeException e) {
                        if (shouldWriteExceptionLog) {
                            log.error("Error synchronizing resource", e);
                        }
                        shouldWriteExceptionLog = false;
                        throw new InternalErrorException(e);
                    }
                }
            } catch (PerunRuntimeException e) {
                if (shouldWriteExceptionLog) {
                    log.error("Error synchronizing resources", e);
                }
                shouldWriteExceptionLog = false;
                throw new InternalErrorException(e);
            }
        }
        try {
            removeOldEntries(perunResource, presentResources, log);
        } catch (InternalErrorException e) {
            log.error("Error removing old resource entries", e);
            shouldWriteExceptionLog = false;
            throw new InternalErrorException(e);
        }
    } catch (InternalErrorException e) {
        if (shouldWriteExceptionLog) {
            log.error("Error getting VO list", e);
        }
        throw new InternalErrorException(e);
    }
}
Also used : Group(cz.metacentrum.perun.core.api.Group) Attribute(cz.metacentrum.perun.core.api.Attribute) Resource(cz.metacentrum.perun.core.api.Resource) PerunResource(cz.metacentrum.perun.ldapc.model.PerunResource) ArrayList(java.util.ArrayList) PerunBl(cz.metacentrum.perun.core.bl.PerunBl) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Name(javax.naming.Name) Vo(cz.metacentrum.perun.core.api.Vo) PerunRuntimeException(cz.metacentrum.perun.core.api.exceptions.rt.PerunRuntimeException) HashSet(java.util.HashSet)

Aggregations

InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)6 PerunRuntimeException (cz.metacentrum.perun.core.api.exceptions.rt.PerunRuntimeException)6 ArrayList (java.util.ArrayList)6 Attribute (cz.metacentrum.perun.core.api.Attribute)5 PerunBl (cz.metacentrum.perun.core.bl.PerunBl)5 HashSet (java.util.HashSet)5 Name (javax.naming.Name)5 Vo (cz.metacentrum.perun.core.api.Vo)4 Facility (cz.metacentrum.perun.core.api.Facility)3 Group (cz.metacentrum.perun.core.api.Group)3 Member (cz.metacentrum.perun.core.api.Member)3 Resource (cz.metacentrum.perun.core.api.Resource)2 PerunException (cz.metacentrum.perun.core.api.exceptions.PerunException)2 PerunClient (cz.metacentrum.perun.core.api.PerunClient)1 PerunRequest (cz.metacentrum.perun.core.api.PerunRequest)1 User (cz.metacentrum.perun.core.api.User)1 UserExtSource (cz.metacentrum.perun.core.api.UserExtSource)1 PrivilegeException (cz.metacentrum.perun.core.api.exceptions.PrivilegeException)1 RpcException (cz.metacentrum.perun.core.api.exceptions.RpcException)1 UserNotExistsException (cz.metacentrum.perun.core.api.exceptions.UserNotExistsException)1