use of cz.metacentrum.perun.core.api.exceptions.PrivilegeException in project perun by CESNET.
the class TaskSchedulerImpl method sendToEngine.
private void sendToEngine(Task task) {
DispatcherQueue dispatcherQueue;
try {
dispatcherQueue = schedulingPool.getQueueForTask(task);
} catch (InternalErrorException e1) {
log.error("No engine set for task " + task.toString() + ", could not send it!");
return;
}
if (dispatcherQueue == null) {
// where should we send the task?
if (dispatcherQueuePool.poolSize() > 0) {
dispatcherQueue = dispatcherQueuePool.getPool().iterator().next();
try {
schedulingPool.setQueueForTask(task, dispatcherQueue);
} catch (InternalErrorException e) {
log.error("Could not assign new queue for task {}: {}", task.getId(), e);
return;
}
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;
}
}
// task|[engine_id]|[task_id][is_forced][exec_service_id][facility]|[destination_list]|[dependency_list]
// - the task|[engine_id] part is added by dispatcherQueue
List<Destination> destinations = task.getDestinations();
if (destinations == null || destinations.isEmpty()) {
log.debug("No destinations for task " + task.toString() + ", trying to query the database...");
try {
initPerunSession();
destinations = perun.getServicesManager().getDestinations(perunSession, task.getExecService().getService(), task.getFacility());
} catch (ServiceNotExistsException e) {
log.error("No destinations found for task " + task.getId());
task.setEndTime(new Date(System.currentTimeMillis()));
schedulingPool.setTaskStatus(task, TaskStatus.ERROR);
return;
} catch (FacilityNotExistsException e) {
log.error("Facility for task {} does not exist...", task.getId());
task.setEndTime(new Date(System.currentTimeMillis()));
schedulingPool.setTaskStatus(task, TaskStatus.ERROR);
return;
} catch (PrivilegeException e) {
log.error("Privilege error accessing the database: " + e.getMessage());
task.setEndTime(new Date(System.currentTimeMillis()));
schedulingPool.setTaskStatus(task, TaskStatus.ERROR);
return;
} catch (InternalErrorException e) {
log.error("Internal error: " + e.getMessage());
task.setEndTime(new Date(System.currentTimeMillis()));
schedulingPool.setTaskStatus(task, TaskStatus.ERROR);
return;
}
}
log.debug("Fetched destinations: " + ((destinations == null) ? "[]" : destinations.toString()));
task.setDestinations(destinations);
StringBuilder destinations_s = new StringBuilder("Destinations [");
if (destinations != null) {
for (Destination destination : destinations) {
destinations_s.append(destination.serializeToString() + ", ");
}
}
destinations_s.append("]");
String dependencies = "";
dispatcherQueue.sendMessage("[" + task.getId() + "][" + task.isPropagationForced() + "]|[" + fixStringSeparators(task.getExecService().serializeToString()) + "]|[" + fixStringSeparators(task.getFacility().serializeToString()) + "]|[" + fixStringSeparators(destinations_s.toString()) + "]|[" + dependencies + "]");
task.setStartTime(new Date(System.currentTimeMillis()));
task.setEndTime(null);
schedulingPool.setTaskStatus(task, TaskStatus.PROCESSING);
}
use of cz.metacentrum.perun.core.api.exceptions.PrivilegeException in project perun by CESNET.
the class Api method serve.
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
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.writePerunException(e);
}
out.close();
return;
}
//prepare result object
Object result = 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("/", 3);
if (fcm.length != 3 || fcm[2].isEmpty()) {
throw new RpcException(RpcException.Type.INVALID_URL, req.getPathInfo());
}
manager = fcm[1];
method = fcm[2];
ser = selectSerializer(fcm[0], out, req, resp);
// is the output JSONP?
if ("jsonp".equalsIgnoreCase(fcm[0])) {
isJsonp = true;
}
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(), this.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(), this.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 (int i = 0; i < cookies.length; i++) {
Cookie c = cookies[i];
// 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(new String("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) && PERUNSTATUS.equals(method)) {
Date date = new Date();
Timestamp timestamp = new Timestamp(date.getTime());
Map<String, Integer> auditerConsumers;
auditerConsumers = (Map<String, Integer>) caller.call("auditMessagesManager", "getAllAuditerConsumers", des);
List<String> perunStatus = new ArrayList<>();
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;
}
// In case of GET requests (read ones) set changing state to false
caller.setStateChanging(!isGet);
// 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);
}
}
/* Security check. Currently only OIDC manager can handle scopes from untrustful (OAuth2) clients
or client has to have allowed scope ALL. */
if (!caller.getSession().getPerunClient().getType().equals(PerunClient.Type.INTERNAL)) {
if (!OIDCMANAGER.equals(manager) && !caller.getSession().getPerunClient().getScopes().contains(PerunClient.SCOPE_ALL)) {
throw new PrivilegeException("Your client " + caller.getSession().getPerunClient().getId() + " is not allowed to call manager " + manager + ". Try " + OIDCMANAGER + " instead.");
}
}
// Process request and sent the response back
if (VOOTMANAGER.equals(manager)) {
// Process VOOT protocol
result = caller.getVOOTManager().process(caller.getSession(), method, des.readAll());
if (perunRequest != null)
perunRequest.setResult(result);
ser.write(result);
} else if (OIDCMANAGER.equals(manager)) {
// OIDC
result = caller.getOIDCManager().process(caller.getSession(), method, des);
if (perunRequest != null)
perunRequest.setResult(result);
ser.write(result);
} 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);
}
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);
}
ser.writePerunRuntimeException(prex);
} catch (IOException ioex) {
//IOException gets logged and is rethrown
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);
}
ser.writePerunException(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) {
pendingRequests.remove(key);
}
}
}
}
out.close();
log.debug("Method {}.{} called by {} from {}, duration {} ms.", new Object[] { manager, method, caller.getSession().getPerunPrincipal().getActor(), caller.getSession().getPerunPrincipal().getExtSourceName(), (System.currentTimeMillis() - timeStart) });
}
use of cz.metacentrum.perun.core.api.exceptions.PrivilegeException in project perun by CESNET.
the class AuthzResolver method unsetRole.
/**
* Unset role for group and <b>one</b> complementary object
*
* If some complementary object is wrong for the role, throw an exception.
* For role "perunadmin" ignore complementary object.
*
* @param sess perun session
* @param authorizedGroup the group for unsetting role
* @param role role of user in a session
* @param complementaryObject object for which role will be unset
*
* @throws InternalErrorException
* @throws PrivilegeException
* @throws GroupNotExistsException
* @throws GroupNotAdminException
*/
public static void unsetRole(PerunSession sess, Group authorizedGroup, PerunBean complementaryObject, Role role) throws InternalErrorException, PrivilegeException, GroupNotExistsException, GroupNotAdminException {
Utils.notNull(role, "role");
((PerunBl) sess.getPerun()).getGroupsManagerBl().checkGroupExists(sess, authorizedGroup);
if (!isAuthorized(sess, Role.PERUNADMIN))
throw new PrivilegeException("You are not privileged to use this method setRole.");
cz.metacentrum.perun.core.blImpl.AuthzResolverBlImpl.unsetRole(sess, authorizedGroup, complementaryObject, role);
}
use of cz.metacentrum.perun.core.api.exceptions.PrivilegeException in project perun by CESNET.
the class AuthzResolver method setRole.
/**
* Set role for user and <b>all</b> complementary objects.
*
* If some complementary object is wrong for the role, throw an exception.
* For role "perunadmin" ignore complementary objects.
*
* @param sess perun session
* @param user the user for setting role
* @param role role of user in a session
* @param complementaryObjects objects for which role will be set
*
* @throws InternalErrorException
* @throws PrivilegeException
* @throws UserNotExistsException
* @throws AlreadyAdminException
* @throws GroupNotAdminException
* @throws UserNotAdminException
*/
public static void setRole(PerunSession sess, User user, Role role, List<PerunBean> complementaryObjects) throws InternalErrorException, PrivilegeException, UserNotExistsException, AlreadyAdminException, GroupNotAdminException, UserNotAdminException {
Utils.notNull(role, "role");
((PerunBl) sess.getPerun()).getUsersManagerBl().checkUserExists(sess, user);
if (!isAuthorized(sess, Role.PERUNADMIN))
throw new PrivilegeException("You are not privileged to use this method setRole.");
cz.metacentrum.perun.core.blImpl.AuthzResolverBlImpl.setRole(sess, user, role, complementaryObjects);
}
use of cz.metacentrum.perun.core.api.exceptions.PrivilegeException in project perun by CESNET.
the class AuthzResolver method unsetRole.
/**
* Unset role for user and <b>all</b> complementary objects
*
* If some complementary object is wrong for the role, throw an exception.
* For role "perunadmin" ignore complementary objects.
*
* @param sess perun session
* @param user the user for unsetting role
* @param role role of user in a session
* @param complementaryObjects objects for which role will be unset
*
* @throws InternalErrorException
* @throws PrivilegeException
* @throws UserNotExistsException
* @throws UserNotAdminException
*/
public static void unsetRole(PerunSession sess, User user, Role role, List<PerunBean> complementaryObjects) throws InternalErrorException, PrivilegeException, UserNotExistsException, UserNotAdminException {
Utils.notNull(role, "role");
((PerunBl) sess.getPerun()).getUsersManagerBl().checkUserExists(sess, user);
if (!isAuthorized(sess, Role.PERUNADMIN))
throw new PrivilegeException("You are not privileged to use this method unsetRole.");
cz.metacentrum.perun.core.blImpl.AuthzResolverBlImpl.unsetRole(sess, user, role, complementaryObjects);
}
Aggregations