diff --git a/airavata-api/src/main/java/org/apache/airavata/api/server/handler/AiravataServerHandler.java b/airavata-api/src/main/java/org/apache/airavata/api/server/handler/AiravataServerHandler.java index 4da1eb7494..ee1eea4888 100644 --- a/airavata-api/src/main/java/org/apache/airavata/api/server/handler/AiravataServerHandler.java +++ b/airavata-api/src/main/java/org/apache/airavata/api/server/handler/AiravataServerHandler.java @@ -20,28 +20,13 @@ package org.apache.airavata.api.server.handler; import java.util.*; -import java.util.function.BiFunction; -import java.util.stream.Collectors; import org.apache.airavata.accountprovisioning.ConfigParam; -import org.apache.airavata.accountprovisioning.SSHAccountManager; import org.apache.airavata.accountprovisioning.SSHAccountProvisionerFactory; import org.apache.airavata.accountprovisioning.SSHAccountProvisionerProvider; -import org.apache.airavata.agents.api.AgentAdaptor; -import org.apache.airavata.agents.api.AgentException; import org.apache.airavata.api.Airavata; import org.apache.airavata.api.airavata_apiConstants; -import org.apache.airavata.common.exception.AiravataException; import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.AiravataUtils; import org.apache.airavata.common.utils.Constants; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.common.utils.ThriftClientPool; -import org.apache.airavata.credential.store.cpi.CredentialStoreService; -import org.apache.airavata.helix.core.support.adaptor.AdaptorSupportImpl; -import org.apache.airavata.messaging.core.MessageContext; -import org.apache.airavata.messaging.core.MessagingFactory; -import org.apache.airavata.messaging.core.Publisher; -import org.apache.airavata.messaging.core.Type; import org.apache.airavata.model.appcatalog.accountprovisioning.SSHAccountProvisioner; import org.apache.airavata.model.appcatalog.accountprovisioning.SSHAccountProvisionerConfigParam; import org.apache.airavata.model.appcatalog.accountprovisioning.SSHAccountProvisionerConfigParamType; @@ -67,7 +52,6 @@ import org.apache.airavata.model.appcatalog.userresourceprofile.UserStoragePreference; import org.apache.airavata.model.application.io.InputDataObjectType; import org.apache.airavata.model.application.io.OutputDataObjectType; -import org.apache.airavata.model.commons.airavata_commonsConstants; import org.apache.airavata.model.credential.store.*; import org.apache.airavata.model.data.movement.*; import org.apache.airavata.model.data.movement.DMType; @@ -76,247 +60,33 @@ import org.apache.airavata.model.error.*; import org.apache.airavata.model.experiment.*; import org.apache.airavata.model.group.ResourcePermissionType; -import org.apache.airavata.model.group.ResourceType; import org.apache.airavata.model.job.JobModel; -import org.apache.airavata.model.messaging.event.ExperimentIntermediateOutputsEvent; -import org.apache.airavata.model.messaging.event.ExperimentStatusChangeEvent; -import org.apache.airavata.model.messaging.event.ExperimentSubmitEvent; -import org.apache.airavata.model.messaging.event.MessageType; -import org.apache.airavata.model.process.ProcessModel; import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel; import org.apache.airavata.model.security.AuthzToken; -import org.apache.airavata.model.status.ExperimentState; import org.apache.airavata.model.status.ExperimentStatus; -import org.apache.airavata.model.status.JobState; import org.apache.airavata.model.status.JobStatus; -import org.apache.airavata.model.status.ProcessState; import org.apache.airavata.model.status.ProcessStatus; import org.apache.airavata.model.status.QueueStatusModel; -import org.apache.airavata.model.task.TaskTypes; import org.apache.airavata.model.workspace.Gateway; import org.apache.airavata.model.workspace.Notification; import org.apache.airavata.model.workspace.Project; -import org.apache.airavata.registry.api.RegistryService; -import org.apache.airavata.registry.api.exception.RegistryServiceException; -import org.apache.airavata.service.security.GatewayGroupsInitializer; +import org.apache.airavata.service.AiravataService; import org.apache.airavata.service.security.interceptor.SecurityCheck; -import org.apache.airavata.sharing.registry.models.*; -import org.apache.airavata.sharing.registry.service.cpi.SharingRegistryService; -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import org.apache.thrift.TApplicationException; -import org.apache.thrift.TException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class AiravataServerHandler implements Airavata.Iface { - private static final Logger logger = LoggerFactory.getLogger(AiravataServerHandler.class); - private Publisher statusPublisher; - private Publisher experimentPublisher; - private ThriftClientPool sharingClientPool; - private ThriftClientPool registryClientPool; - private ThriftClientPool csClientPool; + private AiravataService airavataService; public AiravataServerHandler() { - try { - statusPublisher = MessagingFactory.getPublisher(Type.STATUS); - experimentPublisher = MessagingFactory.getPublisher(Type.EXPERIMENT_LAUNCH); - - sharingClientPool = new ThriftClientPool<>( - tProtocol -> new SharingRegistryService.Client(tProtocol), - this.createGenericObjectPoolConfig(), - ServerSettings.getSharingRegistryHost(), - Integer.parseInt(ServerSettings.getSharingRegistryPort())); - registryClientPool = new ThriftClientPool<>( - tProtocol -> new RegistryService.Client(tProtocol), - this.createGenericObjectPoolConfig(), - ServerSettings.getRegistryServerHost(), - Integer.parseInt(ServerSettings.getRegistryServerPort())); - csClientPool = new ThriftClientPool<>( - tProtocol -> new CredentialStoreService.Client(tProtocol), - this.createGenericObjectPoolConfig(), - ServerSettings.getCredentialStoreServerHost(), - Integer.parseInt(ServerSettings.getCredentialStoreServerPort())); - - initSharingRegistry(); - postInitDefaultGateway(); - } catch (ApplicationSettingsException e) { - logger.error("Error occured while reading airavata-server properties..", e); - } catch (AiravataException e) { - logger.error("Error occured while reading airavata-server properties..", e); - } catch (TException e) { - logger.error("Error occured while reading airavata-server properties..", e); - } - } - - private GenericObjectPoolConfig createGenericObjectPoolConfig() { - - GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); - poolConfig.setMaxTotal(100); - poolConfig.setMinIdle(5); - poolConfig.setBlockWhenExhausted(true); - poolConfig.setTestOnBorrow(true); - poolConfig.setTestWhileIdle(true); - // must set timeBetweenEvictionRunsMillis since eviction doesn't run unless that is positive - poolConfig.setTimeBetweenEvictionRunsMillis(5L * 60L * 1000L); - poolConfig.setNumTestsPerEvictionRun(10); - poolConfig.setMaxWaitMillis(3000); - return poolConfig; - } - - /** - * This method creates a password token for the default gateway profile. Default gateway is originally initialized - * at the registry server but we can not add the password token at that step as the credential store is not initialized - * before registry server. - */ - private void postInitDefaultGateway() { - - RegistryService.Client registryClient = registryClientPool.getResource(); - try { - - GatewayResourceProfile gatewayResourceProfile = - registryClient.getGatewayResourceProfile(ServerSettings.getDefaultUserGateway()); - if (gatewayResourceProfile != null && gatewayResourceProfile.getIdentityServerPwdCredToken() == null) { - - logger.debug("Starting to add the password credential for default gateway : " - + ServerSettings.getDefaultUserGateway()); - - PasswordCredential passwordCredential = new PasswordCredential(); - passwordCredential.setPortalUserName(ServerSettings.getDefaultUser()); - passwordCredential.setGatewayId(ServerSettings.getDefaultUserGateway()); - passwordCredential.setLoginUserName(ServerSettings.getDefaultUser()); - passwordCredential.setPassword(ServerSettings.getDefaultUserPassword()); - passwordCredential.setDescription("Credentials for default gateway"); - - CredentialStoreService.Client csClient = csClientPool.getResource(); - String token = null; - try { - logger.info("Creating password credential for default gateway"); - token = csClient.addPasswordCredential(passwordCredential); - csClientPool.returnResource(csClient); - } catch (Exception ex) { - logger.error( - "Failed to create the password credential for the default gateway : " - + ServerSettings.getDefaultUserGateway(), - ex); - if (csClient != null) { - csClientPool.returnBrokenResource(csClient); - } - } - - if (token != null) { - logger.debug("Adding password credential token " + token + " to the default gateway : " - + ServerSettings.getDefaultUserGateway()); - gatewayResourceProfile.setIdentityServerPwdCredToken(token); - gatewayResourceProfile.setIdentityServerTenant(ServerSettings.getDefaultUserGateway()); - registryClient.updateGatewayResourceProfile( - ServerSettings.getDefaultUserGateway(), gatewayResourceProfile); - } - } - - registryClientPool.returnResource(registryClient); - } catch (Exception e) { - logger.error("Failed to add the password credentials for the default gateway", e); - - if (registryClient != null) { - registryClientPool.returnBrokenResource(registryClient); - } - } - } - - private void initSharingRegistry() throws ApplicationSettingsException, TException { - SharingRegistryService.Client client = sharingClientPool.getResource(); - try { - if (!client.isDomainExists(ServerSettings.getDefaultUserGateway())) { - Domain domain = new Domain(); - domain.setDomainId(ServerSettings.getDefaultUserGateway()); - domain.setName(ServerSettings.getDefaultUserGateway()); - domain.setDescription("Domain entry for " + domain.getName()); - client.createDomain(domain); - - User user = new User(); - user.setDomainId(domain.getDomainId()); - user.setUserId(ServerSettings.getDefaultUser() + "@" + ServerSettings.getDefaultUserGateway()); - user.setUserName(ServerSettings.getDefaultUser()); - client.createUser(user); - - // Creating Entity Types for each domain - EntityType entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":PROJECT"); - entityType.setDomainId(domain.getDomainId()); - entityType.setName("PROJECT"); - entityType.setDescription("Project entity type"); - client.createEntityType(entityType); - - entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":EXPERIMENT"); - entityType.setDomainId(domain.getDomainId()); - entityType.setName("EXPERIMENT"); - entityType.setDescription("Experiment entity type"); - client.createEntityType(entityType); - - entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":FILE"); - entityType.setDomainId(domain.getDomainId()); - entityType.setName("FILE"); - entityType.setDescription("File entity type"); - client.createEntityType(entityType); - - entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); - entityType.setDomainId(domain.getDomainId()); - entityType.setName("APPLICATION-DEPLOYMENT"); - entityType.setDescription("Application Deployment entity type"); - client.createEntityType(entityType); - - entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":" + ResourceType.GROUP_RESOURCE_PROFILE.name()); - entityType.setDomainId(domain.getDomainId()); - entityType.setName(ResourceType.GROUP_RESOURCE_PROFILE.name()); - entityType.setDescription("Group Resource Profile entity type"); - client.createEntityType(entityType); - - entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":" + ResourceType.CREDENTIAL_TOKEN.name()); - entityType.setDomainId(domain.getDomainId()); - entityType.setName(ResourceType.CREDENTIAL_TOKEN.name()); - entityType.setDescription("Credential Store Token entity type"); - client.createEntityType(entityType); - - // Creating Permission Types for each domain - PermissionType permissionType = new PermissionType(); - permissionType.setPermissionTypeId(domain.getDomainId() + ":READ"); - permissionType.setDomainId(domain.getDomainId()); - permissionType.setName("READ"); - permissionType.setDescription("Read permission type"); - client.createPermissionType(permissionType); - - permissionType = new PermissionType(); - permissionType.setPermissionTypeId(domain.getDomainId() + ":WRITE"); - permissionType.setDomainId(domain.getDomainId()); - permissionType.setName("WRITE"); - permissionType.setDescription("Write permission type"); - client.createPermissionType(permissionType); - - permissionType = new PermissionType(); - permissionType.setPermissionTypeId(domain.getDomainId() + ":MANAGE_SHARING"); - permissionType.setDomainId(domain.getDomainId()); - permissionType.setName("MANAGE_SHARING"); - permissionType.setDescription("Sharing permission type"); - client.createPermissionType(permissionType); - } - sharingClientPool.returnResource(client); - } catch (Exception ex) { - sharingClientPool.returnBrokenResource(client); - throw ex; - } + airavataService = new AiravataService(); + airavataService.init(); } /** * Query Airavata to fetch the API version */ @Override - public String getAPIVersion() throws TException { + public String getAPIVersion() throws AiravataSystemException { return airavata_apiConstants.AIRAVATA_API_VERSION; } @@ -331,111 +101,15 @@ public String getAPIVersion() throws TException { @Override @SecurityCheck public boolean isUserExists(AuthzToken authzToken, String gatewayId, String userName) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client client = registryClientPool.getResource(); - try { - boolean isExists = client.isUserExists(gatewayId, userName); - logger.debug("Checking if the user" + userName + "exists in the gateway" + gatewayId); - registryClientPool.returnResource(client); - return isExists; - } catch (Exception e) { - logger.error("Error while verifying user", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while verifying user. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(client); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.isUserExists(gatewayId, userName); } @Override @SecurityCheck public String addGateway(AuthzToken authzToken, Gateway gateway) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - RegistryService.Client registryClient = registryClientPool.getResource(); - try { - String gatewayId = registryClient.addGateway(gateway); - Domain domain = new Domain(); - domain.setDomainId(gateway.getGatewayId()); - domain.setName(gateway.getGatewayName()); - domain.setDescription("Domain entry for " + domain.getName()); - sharingClient.createDomain(domain); - - // Creating Entity Types for each domain - EntityType entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":PROJECT"); - entityType.setDomainId(domain.getDomainId()); - entityType.setName("PROJECT"); - entityType.setDescription("Project entity type"); - sharingClient.createEntityType(entityType); - - entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":EXPERIMENT"); - entityType.setDomainId(domain.getDomainId()); - entityType.setName("EXPERIMENT"); - entityType.setDescription("Experiment entity type"); - sharingClient.createEntityType(entityType); - - entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":FILE"); - entityType.setDomainId(domain.getDomainId()); - entityType.setName("FILE"); - entityType.setDescription("File entity type"); - sharingClient.createEntityType(entityType); - - entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); - entityType.setDomainId(domain.getDomainId()); - entityType.setName("APPLICATION-DEPLOYMENT"); - entityType.setDescription("Application Deployment entity type"); - sharingClient.createEntityType(entityType); - - entityType = new EntityType(); - entityType.setEntityTypeId(domain.getDomainId() + ":" + ResourceType.GROUP_RESOURCE_PROFILE.name()); - entityType.setDomainId(domain.getDomainId()); - entityType.setName(ResourceType.GROUP_RESOURCE_PROFILE.name()); - entityType.setDescription("Group Resource Profile entity type"); - sharingClient.createEntityType(entityType); - - // Creating Permission Types for each domain - PermissionType permissionType = new PermissionType(); - permissionType.setPermissionTypeId(domain.getDomainId() + ":READ"); - permissionType.setDomainId(domain.getDomainId()); - permissionType.setName("READ"); - permissionType.setDescription("Read permission type"); - sharingClient.createPermissionType(permissionType); - - permissionType = new PermissionType(); - permissionType.setPermissionTypeId(domain.getDomainId() + ":WRITE"); - permissionType.setDomainId(domain.getDomainId()); - permissionType.setName("WRITE"); - permissionType.setDescription("Write permission type"); - sharingClient.createPermissionType(permissionType); - - permissionType = new PermissionType(); - permissionType.setPermissionTypeId(domain.getDomainId() + ":MANAGE_SHARING"); - permissionType.setDomainId(domain.getDomainId()); - permissionType.setName("MANAGE_SHARING"); - permissionType.setDescription("Sharing permission type"); - sharingClient.createPermissionType(permissionType); - - registryClientPool.returnResource(registryClient); - sharingClientPool.returnResource(sharingClient); - logger.debug("Airavata successfully created the gateway with " + gatewayId); - - return gatewayId; - } catch (Exception e) { - logger.error("Error while adding gateway", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding gateway. More info : " + e.getMessage()); - sharingClientPool.returnBrokenResource(sharingClient); - registryClientPool.returnBrokenResource(registryClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addGateway(gateway); } /** @@ -449,126 +123,43 @@ public String addGateway(AuthzToken authzToken, Gateway gateway) @Override @SecurityCheck public List getAllUsersInGateway(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getAllUsersInGateway(gatewayId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving users", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving users. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllUsersInGateway(gatewayId); } @Override @SecurityCheck public boolean updateGateway(AuthzToken authzToken, String gatewayId, Gateway updatedGateway) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateGateway(gatewayId, updatedGateway); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while updating the gateway", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating the gateway. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateGateway(gatewayId, updatedGateway); } @Override @SecurityCheck public Gateway getGateway(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - - RegistryService.Client regClient = registryClientPool.getResource(); - try { - Gateway result = regClient.getGateway(gatewayId); - registryClientPool.returnResource(regClient); - logger.debug("Airavata found the gateway with " + gatewayId); - return result; - } catch (Exception e) { - logger.error("Error while getting the gateway", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while getting the gateway. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getGateway(gatewayId); } @Override @SecurityCheck public boolean deleteGateway(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteGateway(gatewayId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while deleting the gateway", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while deleting the gateway. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteGateway(gatewayId); } @Override @SecurityCheck public List getAllGateways(AuthzToken authzToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - logger.debug("Airavata searching for all gateways"); - List result = regClient.getAllGateways(); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while getting all the gateways", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while getting all the gateways. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllGateways(); } @Override @SecurityCheck public boolean isGatewayExist(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - logger.debug("Airavata verifying if the gateway with " + gatewayId + "exits"); - boolean result = regClient.isGatewayExist(gatewayId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while getting gateway", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while getting gateway. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.isGatewayExist(gatewayId); } /** @@ -581,151 +172,45 @@ public boolean isGatewayExist(AuthzToken authzToken, String gatewayId) @Override @SecurityCheck public String createNotification(AuthzToken authzToken, Notification notification) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.createNotification(notification); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while creating notification", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while creating notification. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.createNotification(notification); } @Override @SecurityCheck public boolean updateNotification(AuthzToken authzToken, Notification notification) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateNotification(notification); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while updating notification", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while getting gateway. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateNotification(notification); } @Override @SecurityCheck public boolean deleteNotification(AuthzToken authzToken, String gatewayId, String notificationId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteNotification(gatewayId, notificationId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while deleting notification", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while deleting notification. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteNotification(gatewayId, notificationId); } // No security check @Override public Notification getNotification(AuthzToken authzToken, String gatewayId, String notificationId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - Notification result = regClient.getNotification(gatewayId, notificationId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving notification", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retreiving notification. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getNotification(gatewayId, notificationId); } // No security check @Override public List getAllNotifications(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getAllNotifications(gatewayId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while getting all notifications", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while getting all notifications. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllNotifications(gatewayId); } @Override @SecurityCheck public String generateAndRegisterSSHKeys(AuthzToken authzToken, String description) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException { + throws InvalidRequestException, AiravataClientException, AiravataSystemException { String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - CredentialStoreService.Client csClient = csClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - RegistryService.Client regClient = registryClientPool.getResource(); - try { - SSHCredential sshCredential = new SSHCredential(); - sshCredential.setUsername(userName); - sshCredential.setGatewayId(gatewayId); - sshCredential.setDescription(description); - String key = csClient.addSSHCredential(sshCredential); - try { - Entity entity = new Entity(); - entity.setEntityId(key); - entity.setDomainId(gatewayId); - entity.setEntityTypeId(gatewayId + ":" + ResourceType.CREDENTIAL_TOKEN); - entity.setOwnerId(userName + "@" + gatewayId); - entity.setName(key); - entity.setDescription(description); - sharingClient.createEntity(entity); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - logger.error("Rolling back ssh key creation for user " + userName + " and description [" + description - + "]"); - csClient.deleteSSHCredential(key, gatewayId); - AiravataSystemException ase = new AiravataSystemException(); - ase.setMessage("Failed to create sharing registry record"); - throw ase; - } - logger.debug("Airavata generated SSH keys for gateway : " + gatewayId + " and for user : " + userName); - csClientPool.returnResource(csClient); - sharingClientPool.returnResource(sharingClient); - registryClientPool.returnResource(regClient); - return key; - } catch (Exception e) { - logger.error("Error occurred while registering SSH Credential", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error occurred while registering SSH Credential. More info : " + e.getMessage()); - csClientPool.returnBrokenResource(csClient); - sharingClientPool.returnBrokenResource(sharingClient); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + return airavataService.generateAndRegisterSSHKeys(gatewayId, userName, description); } /** @@ -741,195 +226,43 @@ public String generateAndRegisterSSHKeys(AuthzToken authzToken, String descripti @SecurityCheck public String registerPwdCredential( AuthzToken authzToken, String loginUserName, String password, String description) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException { + throws AiravataClientException, AiravataSystemException, AuthorizationException, InvalidRequestException { String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - CredentialStoreService.Client csClient = csClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - RegistryService.Client regClient = registryClientPool.getResource(); - try { - PasswordCredential pwdCredential = new PasswordCredential(); - pwdCredential.setPortalUserName(userName); - pwdCredential.setLoginUserName(loginUserName); - pwdCredential.setPassword(password); - pwdCredential.setDescription(description); - pwdCredential.setGatewayId(gatewayId); - String key = csClient.addPasswordCredential(pwdCredential); - try { - Entity entity = new Entity(); - entity.setEntityId(key); - entity.setDomainId(gatewayId); - entity.setEntityTypeId(gatewayId + ":" + ResourceType.CREDENTIAL_TOKEN); - entity.setOwnerId(userName + "@" + gatewayId); - entity.setName(key); - entity.setDescription(description); - sharingClient.createEntity(entity); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - logger.error("Rolling back password registration for user " + userName + " and description [" - + description + "]"); - csClient.deletePWDCredential(key, gatewayId); - AiravataSystemException ase = new AiravataSystemException(); - ase.setMessage("Failed to create sharing registry record"); - throw ase; - } - logger.debug("Airavata generated PWD credential for gateway : " + gatewayId + " and for user : " - + loginUserName); - csClientPool.returnResource(csClient); - sharingClientPool.returnResource(sharingClient); - registryClientPool.returnResource(regClient); - return key; - } catch (Exception e) { - logger.error("Error occurred while registering PWD Credential", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error occurred while registering PWD Credential. More info : " + e.getMessage()); - csClientPool.returnBrokenResource(csClient); - throw exception; - } + return airavataService.registerPwdCredential(gatewayId, userName, loginUserName, password, description); } @Override @SecurityCheck public CredentialSummary getCredentialSummary(AuthzToken authzToken, String tokenId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - CredentialStoreService.Client csClient = csClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - if (!userHasAccessInternal(sharingClient, authzToken, tokenId, ResourcePermissionType.READ)) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - CredentialSummary credentialSummary = csClient.getCredentialSummary(tokenId, gatewayId); - csClientPool.returnResource(csClient); - sharingClientPool.returnResource(sharingClient); - logger.debug("Airavata retrived the credential summary for token " + tokenId + "GatewayId: " + gatewayId); - return credentialSummary; - } catch (AuthorizationException ae) { - String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - logger.info("User " + userName + " not allowed to access credential store token " + tokenId); - csClientPool.returnResource(csClient); - sharingClientPool.returnResource(sharingClient); - throw ae; - } catch (Exception e) { - String msg = "Error retrieving credential summary for token " + tokenId + ". GatewayId: " + gatewayId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - csClientPool.returnBrokenResource(csClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + return airavataService.getCredentialSummary(authzToken, tokenId, gatewayId); } @Override @SecurityCheck public List getAllCredentialSummaries(AuthzToken authzToken, SummaryType type) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException { - CredentialStoreService.Client csClient = csClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); + throws InvalidRequestException, AiravataClientException, AiravataSystemException { String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - try { - List filters = new ArrayList<>(); - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); - searchCriteria.setSearchCondition(SearchCondition.EQUAL); - searchCriteria.setValue(gatewayId + ":" + ResourceType.CREDENTIAL_TOKEN.name()); - filters.add(searchCriteria); - List accessibleTokenIds = - sharingClient.searchEntities(gatewayId, userName + "@" + gatewayId, filters, 0, -1).stream() - .map(p -> p.getEntityId()) - .collect(Collectors.toList()); - List credentialSummaries = - csClient.getAllCredentialSummaries(type, accessibleTokenIds, gatewayId); - csClientPool.returnResource(csClient); - sharingClientPool.returnResource(sharingClient); - logger.debug( - "Airavata successfully retrived credential summaries of type " + type + " GatewayId: " + gatewayId); - return credentialSummaries; - } catch (Exception e) { - String msg = "Error retrieving credential summaries of type " + type + ". GatewayId: " + gatewayId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - csClientPool.returnBrokenResource(csClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + return airavataService.getAllCredentialSummaries(authzToken, type, gatewayId, userName); } @Override @SecurityCheck public boolean deleteSSHPubKey(AuthzToken authzToken, String airavataCredStoreToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException { - CredentialStoreService.Client csClient = csClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); + throws AiravataClientException, AiravataSystemException, AuthorizationException, InvalidRequestException { String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - if (!userHasAccessInternal( - sharingClient, authzToken, airavataCredStoreToken, ResourcePermissionType.WRITE)) { - throw new AuthorizationException("User does not have permission to delete this resource."); - } - logger.debug("Airavata deleted SSH pub key for gateway Id : " + gatewayId + " and with token id : " - + airavataCredStoreToken); - boolean result = csClient.deleteSSHCredential(airavataCredStoreToken, gatewayId); - csClientPool.returnResource(csClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (AuthorizationException ae) { - String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - logger.info("User " + userName + " not allowed to delete (no WRITE permission) credential store token " - + airavataCredStoreToken); - csClientPool.returnResource(csClient); - sharingClientPool.returnResource(sharingClient); - throw ae; - } catch (Exception e) { - logger.error("Error occurred while deleting SSH credential", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error occurred while deleting SSH credential. More info : " + e.getMessage()); - csClientPool.returnBrokenResource(csClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + return airavataService.deleteSSHPubKey(authzToken, airavataCredStoreToken, gatewayId); } @Override @SecurityCheck public boolean deletePWDCredential(AuthzToken authzToken, String airavataCredStoreToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException { - CredentialStoreService.Client csClient = csClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); + throws AiravataClientException, AiravataSystemException, AuthorizationException, InvalidRequestException { String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - if (!userHasAccessInternal( - sharingClient, authzToken, airavataCredStoreToken, ResourcePermissionType.WRITE)) { - throw new AuthorizationException("User does not have permission to delete this resource."); - } - logger.debug("Airavata deleted PWD credential for gateway Id : " + gatewayId + " and with token id : " - + airavataCredStoreToken); - boolean result = csClient.deletePWDCredential(airavataCredStoreToken, gatewayId); - csClientPool.returnResource(csClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (AuthorizationException ae) { - String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - logger.info("User " + userName + " not allowed to delete (no WRITE permission) credential store token " - + airavataCredStoreToken); - csClientPool.returnResource(csClient); - sharingClientPool.returnResource(sharingClient); - throw ae; - } catch (Exception e) { - logger.error("Error occurred while deleting PWD credential", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error occurred while deleting PWD credential. More info : " + e.getMessage()); - csClientPool.returnBrokenResource(csClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + return airavataService.deletePWDCredential(authzToken, airavataCredStoreToken, gatewayId); } /** @@ -940,148 +273,24 @@ public boolean deletePWDCredential(AuthzToken authzToken, String airavataCredSto @Override @SecurityCheck public String createProject(AuthzToken authzToken, String gatewayId, Project project) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - // TODO: verify that gatewayId and project.gatewayId match authzToken - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - String projectId = regClient.createProject(gatewayId, project); - if (ServerSettings.isEnableSharing()) { - try { - Entity entity = new Entity(); - entity.setEntityId(projectId); - final String domainId = project.getGatewayId(); - entity.setDomainId(domainId); - entity.setEntityTypeId(domainId + ":" + "PROJECT"); - entity.setOwnerId(project.getOwner() + "@" + domainId); - entity.setName(project.getName()); - entity.setDescription(project.getDescription()); - sharingClient.createEntity(entity); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - logger.error("Rolling back project creation Proj ID : " + projectId); - regClient.deleteProject(projectId); - AiravataSystemException ase = new AiravataSystemException(); - ase.setMessage("Failed to create entry for project in Sharing Registry"); - throw ase; - } - } - logger.debug("Airavata created project with project Id : " + projectId + " for gateway Id : " + gatewayId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return projectId; - } catch (Exception e) { - logger.error("Error while creating the project", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while creating the project. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.createProject(gatewayId, project); } @Override @SecurityCheck public void updateProject(AuthzToken authzToken, String projectId, Project updatedProject) throws InvalidRequestException, AiravataClientException, AiravataSystemException, ProjectNotFoundException, - AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - Project existingProject = regClient.getProject(projectId); - if (ServerSettings.isEnableSharing() - && !authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.USER_NAME) - .equals(existingProject.getOwner()) - || !authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.GATEWAY_ID) - .equals(existingProject.getGatewayId())) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, projectId, gatewayId + ":WRITE")) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } - if (!updatedProject.getOwner().equals(existingProject.getOwner())) { - throw new InvalidRequestException("Owner of a project cannot be changed"); - } - if (!updatedProject.getGatewayId().equals(existingProject.getGatewayId())) { - throw new InvalidRequestException("Gateway ID of a project cannot be changed"); - } - regClient.updateProject(projectId, updatedProject); - logger.debug("Airavata updated project with project Id : " + projectId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - } catch (Exception e) { - logger.error("Error while updating the project", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating the project. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + AuthorizationException { + airavataService.updateProject(authzToken, projectId, updatedProject); } @Override @SecurityCheck public boolean deleteProject(AuthzToken authzToken, String projectId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, ProjectNotFoundException, - AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - Project existingProject = regClient.getProject(projectId); - if (ServerSettings.isEnableSharing() - && !authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.USER_NAME) - .equals(existingProject.getOwner()) - || !authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.GATEWAY_ID) - .equals(existingProject.getGatewayId())) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, projectId, gatewayId + ":WRITE")) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } - boolean ret = regClient.deleteProject(projectId); - logger.debug("Airavata deleted project with project Id : " + projectId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return ret; - } catch (Exception e) { - logger.error("Error while removing the project", e); - ProjectNotFoundException exception = new ProjectNotFoundException(); - exception.setMessage("Error while removing the project. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } - } - - private boolean validateString(String name) { - boolean valid = true; - if (name == null || name.equals("") || name.trim().length() == 0) { - valid = false; - } - return valid; + AuthorizationException { + return airavataService.deleteProject(authzToken, projectId); } /** @@ -1093,49 +302,8 @@ private boolean validateString(String name) { @SecurityCheck public Project getProject(AuthzToken authzToken, String projectId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, ProjectNotFoundException, - AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - Project project = regClient.getProject(projectId); - if (authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.USER_NAME) - .equals(project.getOwner()) - && authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.GATEWAY_ID) - .equals(project.getGatewayId())) { - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return project; - } else if (ServerSettings.isEnableSharing()) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, projectId, gatewayId + ":READ")) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return project; - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } else { - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return null; - } - } catch (Exception e) { - logger.error("Error while retrieving the project", e); - ProjectNotFoundException exception = new ProjectNotFoundException(); - exception.setMessage("Error while retrieving the project. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + AuthorizationException { + return airavataService.getProject(authzToken, projectId); } /** @@ -1155,55 +323,8 @@ public Project getProject(AuthzToken authzToken, String projectId) @SecurityCheck public List getUserProjects( AuthzToken authzToken, String gatewayId, String userName, int limit, int offset) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - // user projects + user accessible projects - List accessibleProjectIds = new ArrayList<>(); - List filters = new ArrayList<>(); - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); - searchCriteria.setSearchCondition(SearchCondition.EQUAL); - searchCriteria.setValue(gatewayId + ":PROJECT"); - filters.add(searchCriteria); - sharingClient - .searchEntities( - authzToken.getClaimsMap().get(Constants.GATEWAY_ID), - userName + "@" + gatewayId, - filters, - 0, - -1) - .stream() - .forEach(p -> accessibleProjectIds.add(p.getEntityId())); - List result; - if (accessibleProjectIds.isEmpty()) { - result = Collections.emptyList(); - } else { - result = regClient.searchProjects( - gatewayId, userName, accessibleProjectIds, new HashMap<>(), limit, offset); - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } else { - List result = regClient.getUserProjects(gatewayId, userName, limit, offset); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } - - } catch (Exception e) { - logger.error("Error while retrieving projects", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving projects. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getUserProjects(authzToken, gatewayId, userName, limit, offset); } /** @@ -1237,50 +358,8 @@ public List searchProjects( Map filters, int limit, int offset) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - List accessibleProjIds = new ArrayList<>(); - - List result; - if (ServerSettings.isEnableSharing()) { - List sharingFilters = new ArrayList<>(); - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); - searchCriteria.setSearchCondition(SearchCondition.EQUAL); - searchCriteria.setValue(gatewayId + ":PROJECT"); - sharingFilters.add(searchCriteria); - sharingClient - .searchEntities( - authzToken.getClaimsMap().get(Constants.GATEWAY_ID), - userName + "@" + gatewayId, - sharingFilters, - 0, - Integer.MAX_VALUE) - .stream() - .forEach(e -> accessibleProjIds.add(e.getEntityId())); - if (accessibleProjIds.isEmpty()) { - result = Collections.emptyList(); - } else { - result = regClient.searchProjects(gatewayId, userName, accessibleProjIds, filters, limit, offset); - } - } else { - result = regClient.searchProjects(gatewayId, userName, accessibleProjIds, filters, limit, offset); - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving projects", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving projects. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.searchProjects(authzToken, gatewayId, userName, filters, limit, offset); } /** @@ -1307,106 +386,8 @@ public List searchExperiments( Map filters, int limit, int offset) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - List accessibleExpIds = new ArrayList<>(); - Map filtersCopy = new HashMap<>(filters); - List sharingFilters = new ArrayList<>(); - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); - searchCriteria.setSearchCondition(SearchCondition.EQUAL); - searchCriteria.setValue(gatewayId + ":EXPERIMENT"); - sharingFilters.add(searchCriteria); - - // Apply as much of the filters in the sharing API as possible, - // removing each filter that can be filtered via the sharing API - if (filtersCopy.containsKey(ExperimentSearchFields.FROM_DATE)) { - String fromTime = filtersCopy.remove(ExperimentSearchFields.FROM_DATE); - SearchCriteria fromCreatedTimeCriteria = new SearchCriteria(); - fromCreatedTimeCriteria.setSearchField(EntitySearchField.CREATED_TIME); - fromCreatedTimeCriteria.setSearchCondition(SearchCondition.GTE); - fromCreatedTimeCriteria.setValue(fromTime); - sharingFilters.add(fromCreatedTimeCriteria); - } - if (filtersCopy.containsKey(ExperimentSearchFields.TO_DATE)) { - String toTime = filtersCopy.remove(ExperimentSearchFields.TO_DATE); - SearchCriteria toCreatedTimeCriteria = new SearchCriteria(); - toCreatedTimeCriteria.setSearchField(EntitySearchField.CREATED_TIME); - toCreatedTimeCriteria.setSearchCondition(SearchCondition.LTE); - toCreatedTimeCriteria.setValue(toTime); - sharingFilters.add(toCreatedTimeCriteria); - } - if (filtersCopy.containsKey(ExperimentSearchFields.PROJECT_ID)) { - String projectId = filtersCopy.remove(ExperimentSearchFields.PROJECT_ID); - SearchCriteria projectParentEntityCriteria = new SearchCriteria(); - projectParentEntityCriteria.setSearchField(EntitySearchField.PARRENT_ENTITY_ID); - projectParentEntityCriteria.setSearchCondition(SearchCondition.EQUAL); - projectParentEntityCriteria.setValue(projectId); - sharingFilters.add(projectParentEntityCriteria); - } - if (filtersCopy.containsKey(ExperimentSearchFields.USER_NAME)) { - String username = filtersCopy.remove(ExperimentSearchFields.USER_NAME); - SearchCriteria usernameOwnerCriteria = new SearchCriteria(); - usernameOwnerCriteria.setSearchField(EntitySearchField.OWNER_ID); - usernameOwnerCriteria.setSearchCondition(SearchCondition.EQUAL); - usernameOwnerCriteria.setValue(username + "@" + gatewayId); - sharingFilters.add(usernameOwnerCriteria); - } - if (filtersCopy.containsKey(ExperimentSearchFields.EXPERIMENT_NAME)) { - String experimentName = filtersCopy.remove(ExperimentSearchFields.EXPERIMENT_NAME); - SearchCriteria experimentNameCriteria = new SearchCriteria(); - experimentNameCriteria.setSearchField(EntitySearchField.NAME); - experimentNameCriteria.setSearchCondition(SearchCondition.LIKE); - experimentNameCriteria.setValue(experimentName); - sharingFilters.add(experimentNameCriteria); - } - if (filtersCopy.containsKey(ExperimentSearchFields.EXPERIMENT_DESC)) { - String experimentDescription = filtersCopy.remove(ExperimentSearchFields.EXPERIMENT_DESC); - SearchCriteria experimentDescriptionCriteria = new SearchCriteria(); - experimentDescriptionCriteria.setSearchField(EntitySearchField.DESCRIPTION); - experimentDescriptionCriteria.setSearchCondition(SearchCondition.LIKE); - experimentDescriptionCriteria.setValue(experimentDescription); - sharingFilters.add(experimentDescriptionCriteria); - } - // Grab all of the matching experiments in the sharing registry - // unless all of the filtering can be done through the sharing API - int searchOffset = 0; - int searchLimit = Integer.MAX_VALUE; - boolean filteredInSharing = filtersCopy.isEmpty(); - if (filteredInSharing) { - searchOffset = offset; - searchLimit = limit; - } - sharingClient - .searchEntities( - authzToken.getClaimsMap().get(Constants.GATEWAY_ID), - userName + "@" + gatewayId, - sharingFilters, - searchOffset, - searchLimit) - .forEach(e -> accessibleExpIds.add(e.getEntityId())); - int finalOffset = offset; - // If no more filtering to be done (either empty or all done through sharing API), set the offset to 0 - if (filteredInSharing) { - finalOffset = 0; - } - List result = - regClient.searchExperiments(gatewayId, userName, accessibleExpIds, filtersCopy, limit, finalOffset); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving experiments", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving experiments. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.searchExperiments(authzToken, gatewayId, userName, filters, limit, offset); } /** @@ -1420,7 +401,6 @@ public List searchExperiments( * @throws InvalidRequestException * @throws AiravataClientException * @throws AiravataSystemException - * @throws TException */ @Override @SecurityCheck @@ -1434,58 +414,18 @@ public ExperimentStatistics getExperimentStatistics( String resourceHostName, int limit, int offset) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - // SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - // FIXME: re-enable experiment statistics for non-admin users - // Find accessible experiments in date range - // List accessibleExpIds = new ArrayList<>(); - // List sharingFilters = new ArrayList<>(); - // SearchCriteria entityTypeCriteria = new SearchCriteria(); - // entityTypeCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); - // entityTypeCriteria.setSearchCondition(SearchCondition.EQUAL); - // entityTypeCriteria.setValue(gatewayId + ":EXPERIMENT"); - // sharingFilters.add(entityTypeCriteria); - // SearchCriteria fromCreatedTimeCriteria = new SearchCriteria(); - // fromCreatedTimeCriteria.setSearchField(EntitySearchField.CREATED_TIME); - // fromCreatedTimeCriteria.setSearchCondition(SearchCondition.GTE); - // fromCreatedTimeCriteria.setValue(Long.toString(fromTime)); - // sharingFilters.add(fromCreatedTimeCriteria); - // SearchCriteria toCreatedTimeCriteria = new SearchCriteria(); - // toCreatedTimeCriteria.setSearchField(EntitySearchField.CREATED_TIME); - // toCreatedTimeCriteria.setSearchCondition(SearchCondition.LTE); - // toCreatedTimeCriteria.setValue(Long.toString(toTime)); - // sharingFilters.add(toCreatedTimeCriteria); - // String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - // sharingClient.searchEntities(authzToken.getClaimsMap().get(Constants.GATEWAY_ID), - // userId + "@" + gatewayId, sharingFilters, 0, Integer.MAX_VALUE).forEach(e -> - // accessibleExpIds.add(e.getEntityId())); - List accessibleExpIds = null; - - ExperimentStatistics result = regClient.getExperimentStatistics( - gatewayId, - fromTime, - toTime, - userName, - applicationName, - resourceHostName, - accessibleExpIds, - limit, - offset); - registryClientPool.returnResource(regClient); - // sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving experiments", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving experiments. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - // sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + List accessibleExpIds = null; + return airavataService.getExperimentStatistics( + gatewayId, + fromTime, + toTime, + userName, + applicationName, + resourceHostName, + accessibleExpIds, + limit, + offset); } /** @@ -1503,45 +443,8 @@ public ExperimentStatistics getExperimentStatistics( @SecurityCheck public List getExperimentsInProject(AuthzToken authzToken, String projectId, int limit, int offset) throws InvalidRequestException, AiravataClientException, AiravataSystemException, ProjectNotFoundException, - AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - Project project = regClient.getProject(projectId); - - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - if (ServerSettings.isEnableSharing() - && !authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.USER_NAME) - .equals(project.getOwner()) - || !authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.GATEWAY_ID) - .equals(project.getGatewayId())) { - try { - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, projectId, gatewayId + ":READ")) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } - List result = regClient.getExperimentsInProject(gatewayId, projectId, limit, offset); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving the experiments", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving the experiments. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + AuthorizationException { + return airavataService.getExperimentsInProject(authzToken, projectId, limit, offset); } /** @@ -1561,24 +464,8 @@ public List getExperimentsInProject(AuthzToken authzToken, Stri @SecurityCheck public List getUserExperiments( AuthzToken authzToken, String gatewayId, String userName, int limit, int offset) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - List result = regClient.getUserExperiments(gatewayId, userName, limit, offset); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving the experiments", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving the experiments. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getUserExperiments(gatewayId, userName, limit, offset); } /** @@ -1606,66 +493,8 @@ public List getUserExperiments( @Override @SecurityCheck public String createExperiment(AuthzToken authzToken, String gatewayId, ExperimentModel experiment) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - // TODO: verify that gatewayId and experiment.gatewayId match authzToken - logger.info("Api server accepted experiment creation with name {}", experiment.getExperimentName()); - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - String experimentId = regClient.createExperiment(gatewayId, experiment); - - if (ServerSettings.isEnableSharing()) { - try { - Entity entity = new Entity(); - entity.setEntityId(experimentId); - final String domainId = experiment.getGatewayId(); - entity.setDomainId(domainId); - entity.setEntityTypeId(domainId + ":" + "EXPERIMENT"); - entity.setOwnerId(experiment.getUserName() + "@" + domainId); - entity.setName(experiment.getExperimentName()); - entity.setDescription(experiment.getDescription()); - entity.setParentEntityId(experiment.getProjectId()); - - sharingClient.createEntity(entity); - shareEntityWithAdminGatewayGroups(regClient, sharingClient, entity); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - logger.error("Rolling back experiment creation Exp ID : " + experimentId); - regClient.deleteExperiment(experimentId); - AiravataSystemException ase = new AiravataSystemException(); - ase.setMessage("Failed to create sharing registry record"); - throw ase; - } - } - - ExperimentStatusChangeEvent event = - new ExperimentStatusChangeEvent(ExperimentState.CREATED, experimentId, gatewayId); - String messageId = AiravataUtils.getId("EXPERIMENT"); - MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT, messageId, gatewayId); - messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); - if (statusPublisher != null) { - statusPublisher.publish(messageContext); - } - // logger.debug(experimentId, "Created new experiment with experiment name {}", - // experiment.getExperimentName()); - logger.info( - experimentId, - "Created new experiment with experiment name {} and id ", - experiment.getExperimentName(), - experimentId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return experimentId; - } catch (Exception e) { - logger.error("Error while creating the experiment with experiment name {}", experiment.getExperimentName()); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while creating the experiment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.createExperiment(gatewayId, experiment); } /** @@ -1677,57 +506,13 @@ public String createExperiment(AuthzToken authzToken, String gatewayId, Experime * @throws AiravataClientException * @throws AiravataSystemException * @throws AuthorizationException - * @throws TException */ @Override @SecurityCheck public boolean deleteExperiment(AuthzToken authzToken, String experimentId) throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - ExperimentModel experimentModel = regClient.getExperiment(experimentId); - - if (ServerSettings.isEnableSharing() - && !authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.USER_NAME) - .equals(experimentModel.getUserName()) - || !authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.GATEWAY_ID) - .equals(experimentModel.getGatewayId())) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, experimentId, gatewayId + ":WRITE")) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } - - if (!(experimentModel.getExperimentStatus().get(0).getState() == ExperimentState.CREATED)) { - logger.error("Error while deleting the experiment"); - throw new RegistryServiceException( - "Experiment is not in CREATED state. Hence cannot deleted. ID:" + experimentId); - } - boolean result = regClient.deleteExperiment(experimentId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error("Error while deleting the experiment", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while deleting the experiment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + ExperimentNotFoundException, ProjectNotFoundException { + return airavataService.deleteExperimentWithAuth(authzToken, experimentId); } /** @@ -1756,84 +541,17 @@ public boolean deleteExperiment(AuthzToken authzToken, String experimentId) @SecurityCheck public ExperimentModel getExperiment(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - ExperimentModel experimentModel = null; - try { - experimentModel = regClient.getExperiment(airavataExperimentId); - if (authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.USER_NAME) - .equals(experimentModel.getUserName()) - && authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.GATEWAY_ID) - .equals(experimentModel.getGatewayId())) { - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return experimentModel; - } else if (ServerSettings.isEnableSharing()) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, airavataExperimentId, gatewayId + ":READ")) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return experimentModel; - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } else { - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return null; - } - } catch (ExperimentNotFoundException e) { - logger.error(e.getMessage(), e); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - throw e; - } catch (Exception e) { - logger.error("Error while getting the experiment", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while getting the experiment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + AiravataSystemException, AuthorizationException { + return airavataService.getExperiment(authzToken, airavataExperimentId); } @Override @SecurityCheck public ExperimentModel getExperimentByAdmin(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - ExperimentModel experimentModel = null; - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - experimentModel = regClient.getExperiment(airavataExperimentId); - registryClientPool.returnResource(regClient); - if (gatewayId.equals(experimentModel.getGatewayId())) { - return experimentModel; - } else { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } catch (Exception e) { - logger.error("Error while getting the experiment", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while getting the experiment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + AiravataSystemException, AuthorizationException { + return airavataService.getExperimentByAdmin(authzToken, airavataExperimentId); } - /** * Fetch the completed nested tree structue of previously created experiment metadata which includes processes -> * tasks -> jobs information. @@ -1861,23 +579,8 @@ public ExperimentModel getExperimentByAdmin(AuthzToken authzToken, String airava @SecurityCheck public ExperimentModel getDetailedExperimentTree(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - ExperimentModel result = regClient.getDetailedExperimentTree(airavataExperimentId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving the experiment", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving the experiment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + AiravataSystemException, AuthorizationException { + return airavataService.getDetailedExperimentTree(airavataExperimentId); } /** @@ -1908,103 +611,24 @@ public ExperimentModel getDetailedExperimentTree(AuthzToken authzToken, String a @SecurityCheck public void updateExperiment(AuthzToken authzToken, String airavataExperimentId, ExperimentModel experiment) throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - ExperimentModel experimentModel = regClient.getExperiment(airavataExperimentId); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - if (ServerSettings.isEnableSharing() - && !authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.USER_NAME) - .equals(experimentModel.getUserName()) - || !authzToken - .getClaimsMap() - .get(org.apache.airavata.common.utils.Constants.GATEWAY_ID) - .equals(experimentModel.getGatewayId())) { - try { - // Verify WRITE access - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, airavataExperimentId, gatewayId + ":WRITE")) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access this resource"); - } - } - - try { - // Update name, description and parent on Entity - // TODO: update the experiment via a DB event - Entity entity = sharingClient.getEntity(gatewayId, airavataExperimentId); - entity.setName(experiment.getExperimentName()); - entity.setDescription(experiment.getDescription()); - entity.setParentEntityId(experiment.getProjectId()); - sharingClient.updateEntity(entity); - } catch (Exception e) { - throw new Exception("Failed to update entity in sharing registry", e); - } - - regClient.updateExperiment(airavataExperimentId, experiment); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while updating experiment", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + AiravataSystemException, AuthorizationException { + airavataService.updateExperiment(authzToken, airavataExperimentId, experiment); } @Override @SecurityCheck public void updateExperimentConfiguration( AuthzToken authzToken, String airavataExperimentId, UserConfigurationDataModel userConfiguration) - throws AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - regClient.updateExperimentConfiguration(airavataExperimentId, userConfiguration); - registryClientPool.returnResource(regClient); - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while updating user configuration", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while updating user configuration. " + "Update experiment is only valid for experiments " - + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " - + "experiment is in one of above statuses... " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws AuthorizationException, AiravataSystemException { + airavataService.updateExperimentConfiguration(airavataExperimentId, userConfiguration); } @Override @SecurityCheck public void updateResourceScheduleing( AuthzToken authzToken, String airavataExperimentId, ComputationalResourceSchedulingModel resourceScheduling) - throws AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - regClient.updateResourceScheduleing(airavataExperimentId, resourceScheduling); - registryClientPool.returnResource(regClient); - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while updating scheduling info", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while updating scheduling info. " + "Update experiment is only valid for experiments " - + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " - + "experiment is in one of above statuses... " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws AuthorizationException, AiravataSystemException { + airavataService.updateResourceScheduleing(airavataExperimentId, resourceScheduling); } /** @@ -2020,33 +644,29 @@ public void updateResourceScheduleing( */ @Override @SecurityCheck - public boolean validateExperiment(AuthzToken authzToken, String airavataExperimentId) throws TException { + public boolean validateExperiment(AuthzToken authzToken, String airavataExperimentId) + throws AiravataClientException, AiravataSystemException, AuthorizationException, + ExperimentNotFoundException, InvalidRequestException { // TODO - call validation module and validate experiment /* try { - ExperimentModel experimentModel = regClient.getExperiment(airavataExperimentId); + ExperimentModel existingExperiment = airavataService.getExperiment(airavataExperimentId); if (experimentModel == null) { logger.error(airavataExperimentId, "Experiment validation failed , experiment {} doesn't exist.", airavataExperimentId); throw new ExperimentNotFoundException("Requested experiment id " + airavataExperimentId + " does not exist in the system.."); } } catch (RegistryServiceException | ApplicationSettingsException e1) { logger.error(airavataExperimentId, "Error while retrieving projects", e1); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving projects. More info : " + e1.getMessage()); - throw exception; + // Commented out code - not used } Client orchestratorClient = getOrchestratorClient(); try{ if (orchestratorClient.validateExperiment(airavataExperimentId)) { logger.debug(airavataExperimentId, "Experiment validation succeed."); - return true; } else { logger.debug(airavataExperimentId, "Experiment validation failed."); return false; - }}catch (TException e){ - throw e; - }finally { + }}finally { orchestratorClient.getOutputProtocol().getTransport().close(); orchestratorClient.getInputProtocol().getTransport().close(); }*/ @@ -2078,44 +698,23 @@ public boolean validateExperiment(AuthzToken authzToken, String airavataExperime */ @Override @SecurityCheck - public ExperimentStatus getExperimentStatus(AuthzToken authzToken, String airavataExperimentId) throws TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - ExperimentStatus result = regClient.getExperimentStatus(airavataExperimentId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - AiravataSystemException exception = new AiravataSystemException(); - exception.setMessage(e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + public ExperimentStatus getExperimentStatus(AuthzToken authzToken, String airavataExperimentId) + throws AiravataSystemException { + return airavataService.getExperimentStatus(airavataExperimentId); } @Override @SecurityCheck public List getExperimentOutputs(AuthzToken authzToken, String airavataExperimentId) - throws AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getExperimentOutputs(airavataExperimentId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while retrieving the experiment outputs", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving the experiment outputs. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws AuthorizationException, AiravataSystemException { + return airavataService.getExperimentOutputs(airavataExperimentId); } @Override @SecurityCheck public List getIntermediateOutputs(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, AuthorizationException, TException { + AiravataSystemException, AuthorizationException { return null; } @@ -2123,78 +722,8 @@ public List getIntermediateOutputs(AuthzToken authzToken, @SecurityCheck public void fetchIntermediateOutputs(AuthzToken authzToken, String airavataExperimentId, List outputNames) throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, AuthorizationException, TException { - - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - - // Verify that user has WRITE access to experiment - final boolean hasAccess = userHasAccessInternal( - sharingClient, authzToken, airavataExperimentId, ResourcePermissionType.WRITE); - if (!hasAccess) { - throw new AuthorizationException("User does not have WRITE access to this experiment"); - } - - // Verify that the experiment's job is currently ACTIVE - ExperimentModel existingExperiment = regClient.getExperiment(airavataExperimentId); - List jobs = regClient.getJobDetails(airavataExperimentId); - boolean anyJobIsActive = jobs.stream().anyMatch(j -> { - if (j.getJobStatusesSize() > 0) { - return j.getJobStatuses().get(j.getJobStatusesSize() - 1).getJobState() == JobState.ACTIVE; - } else { - return false; - } - }); - if (!anyJobIsActive) { - throw new InvalidRequestException("Experiment does not have currently ACTIVE job"); - } - - // Figure out if there are any currently running intermediate output fetching processes for outputNames - // First, find any existing intermediate output fetch processes for outputNames - List intermediateOutputFetchProcesses = existingExperiment.getProcesses().stream() - .filter(p -> { - // Filter out completed or failed processes - if (p.getProcessStatusesSize() > 0) { - ProcessStatus latestStatus = p.getProcessStatuses().get(p.getProcessStatusesSize() - 1); - if (latestStatus.getState() == ProcessState.COMPLETED - || latestStatus.getState() == ProcessState.FAILED) { - return false; - } - } - return true; - }) - .filter(p -> p.getTasks().stream().allMatch(t -> t.getTaskType() == TaskTypes.OUTPUT_FETCHING)) - .filter(p -> p.getProcessOutputs().stream().anyMatch(o -> outputNames.contains(o.getName()))) - .collect(Collectors.toList()); - if (!intermediateOutputFetchProcesses.isEmpty()) { - throw new InvalidRequestException( - "There are already intermediate output fetching tasks running for those outputs."); - } - - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - submitExperimentIntermediateOutputsEvent(gatewayId, airavataExperimentId, outputNames); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - } catch (InvalidRequestException | AuthorizationException e) { - logger.error(e.getMessage(), e); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - throw e; - } catch (Exception e) { - logger.error( - "Error while processing request to fetch intermediate outputs for experiment: " - + airavataExperimentId, - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while processing request to fetch intermediate outputs for experiment. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + AiravataSystemException, AuthorizationException { + airavataService.fetchIntermediateOutputs(authzToken, airavataExperimentId, outputNames); } @Override @@ -2202,109 +731,22 @@ public void fetchIntermediateOutputs(AuthzToken authzToken, String airavataExper public ProcessStatus getIntermediateOutputProcessStatus( AuthzToken authzToken, String airavataExperimentId, List outputNames) throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - - // Verify that user has READ access to experiment - final boolean hasAccess = - userHasAccessInternal(sharingClient, authzToken, airavataExperimentId, ResourcePermissionType.READ); - if (!hasAccess) { - throw new AuthorizationException("User does not have WRITE access to this experiment"); - } - - ExperimentModel existingExperiment = regClient.getExperiment(airavataExperimentId); - - // Find the most recent intermediate output fetching process for the outputNames - // Assumption: only one of these output fetching processes runs at a - // time so we only need to check the status of the most recent one - Optional mostRecentOutputFetchProcess = existingExperiment.getProcesses().stream() - .filter(p -> p.getTasks().stream().allMatch(t -> t.getTaskType() == TaskTypes.OUTPUT_FETCHING)) - .filter(p -> { - List names = p.getProcessOutputs().stream() - .map(o -> o.getName()) - .collect(Collectors.toList()); - return new HashSet<>(names).equals(new HashSet<>(outputNames)); - }) - .sorted(Comparator.comparing(ProcessModel::getLastUpdateTime) - .reversed()) - .findFirst(); - - if (!mostRecentOutputFetchProcess.isPresent()) { - throw new InvalidRequestException("No matching intermediate output fetching process found."); - } - - ProcessStatus result; - // Determine the most recent status for the most recent process - ProcessModel process = mostRecentOutputFetchProcess.get(); - if (process.getProcessStatusesSize() > 0) { - result = process.getProcessStatuses().get(process.getProcessStatusesSize() - 1); - } else { - // Process has no statuses so it must be created but not yet running - result = new ProcessStatus(ProcessState.CREATED); - } - - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (InvalidRequestException | AuthorizationException e) { - logger.debug(e.getMessage(), e); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - throw e; - } catch (Exception e) { - logger.error( - "Error while processing request to fetch intermediate outputs for experiment: " - + airavataExperimentId, - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while processing request to fetch intermediate outputs for experiment. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + AiravataSystemException, AuthorizationException { + return airavataService.getIntermediateOutputProcessStatus(authzToken, airavataExperimentId, outputNames); } @SecurityCheck public Map getJobStatuses(AuthzToken authzToken, String airavataExperimentId) - throws AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - Map result = regClient.getJobStatuses(airavataExperimentId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while retrieving the job statuses", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving the job statuses. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws AuthorizationException, AiravataSystemException { + return airavataService.getJobStatuses(airavataExperimentId); } @Override @SecurityCheck public List getJobDetails(AuthzToken authzToken, String airavataExperimentId) throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, AuthorizationException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getJobDetails(airavataExperimentId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while retrieving the job details", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving the job details. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + AiravataSystemException, AuthorizationException { + return airavataService.getJobDetails(airavataExperimentId); } /** @@ -2337,145 +779,11 @@ public List getJobDetails(AuthzToken authzToken, String airavataExperi @Override @SecurityCheck public void launchExperiment(AuthzToken authzToken, final String airavataExperimentId, String gatewayId) - throws AuthorizationException, AiravataSystemException, TException { - // TODO: verify that gatewayId matches gatewayId in authzToken - logger.info("Launching experiment {}", airavataExperimentId); - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - ExperimentModel experiment = regClient.getExperiment(airavataExperimentId); - - if (experiment == null) { - logger.error( - airavataExperimentId, - "Error while launching experiment, experiment {} doesn't exist.", - airavataExperimentId); - throw new ExperimentNotFoundException( - "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); - } - String username = authzToken.getClaimsMap().get(Constants.USER_NAME); - - // For backwards compatibility, if there is no groupResourceProfileId, look up one that is shared with the - // user - if (!experiment.getUserConfigurationData().isSetGroupResourceProfileId()) { - List groupResourceProfiles = getGroupResourceList(authzToken, gatewayId); - logger.info("Checking for groupResourceProfileId for ExpID: " + airavataExperimentId); - if (!groupResourceProfiles.isEmpty()) { - // Just pick the first one - final String groupResourceProfileId = - groupResourceProfiles.get(0).getGroupResourceProfileId(); - logger.warn( - "Experiment {} doesn't have groupResourceProfileId, picking first one user has access to: {}", - airavataExperimentId, - groupResourceProfileId); - experiment.getUserConfigurationData().setGroupResourceProfileId(groupResourceProfileId); - regClient.updateExperimentConfiguration( - airavataExperimentId, experiment.getUserConfigurationData()); - } else { - throw new AuthorizationException("User " + username + " in gateway " + gatewayId - + " doesn't have access to any group resource profiles."); - } - } - - // Verify user has READ access to groupResourceProfileId - if (!sharingClient.userHasAccess( - gatewayId, - username + "@" + gatewayId, - experiment.getUserConfigurationData().getGroupResourceProfileId(), - gatewayId + ":READ")) { - throw new AuthorizationException("User " + username + " in gateway " + gatewayId - + " doesn't have access to group resource profile " - + experiment.getUserConfigurationData().getGroupResourceProfileId()); - } - - // Verify user has READ access to Application Deployment - final String appInterfaceId = experiment.getExecutionId(); - ApplicationInterfaceDescription applicationInterfaceDescription = - regClient.getApplicationInterface(appInterfaceId); - - List appModuleIds = applicationInterfaceDescription.getApplicationModules(); - // Assume that there is only one app module for this interface (otherwise, how could we figure out the - // deployment) - String appModuleId = appModuleIds.get(0); - List applicationDeploymentDescriptions = - regClient.getApplicationDeployments(appModuleId); - - if (!experiment.getUserConfigurationData().isAiravataAutoSchedule()) { - final String resourceHostId = experiment - .getUserConfigurationData() - .getComputationalResourceScheduling() - .getResourceHostId(); - - Optional applicationDeploymentDescription = - applicationDeploymentDescriptions.stream() - .filter(dep -> dep.getComputeHostId().equals(resourceHostId)) - .findFirst(); - if (applicationDeploymentDescription.isPresent()) { - final String appDeploymentId = - applicationDeploymentDescription.get().getAppDeploymentId(); - if (!sharingClient.userHasAccess( - gatewayId, username + "@" + gatewayId, appDeploymentId, gatewayId + ":READ")) { - throw new AuthorizationException("User " + username + " in gateway " + gatewayId - + " doesn't have access to app deployment " + appDeploymentId); - } - } else { - throw new InvalidRequestException("Application deployment doesn't exist for application interface " - + appInterfaceId + " and host " + resourceHostId + " in gateway " + gatewayId); - } - } else if (experiment.getUserConfigurationData().getAutoScheduledCompResourceSchedulingList() != null - && !experiment - .getUserConfigurationData() - .getAutoScheduledCompResourceSchedulingList() - .isEmpty()) { - List compResourceSchedulingList = - experiment.getUserConfigurationData().getAutoScheduledCompResourceSchedulingList(); - for (ComputationalResourceSchedulingModel crScheduling : compResourceSchedulingList) { - Optional applicationDeploymentDescription = - applicationDeploymentDescriptions.stream() - .filter(dep -> dep.getComputeHostId().equals(crScheduling.getResourceHostId())) - .findFirst(); - if (applicationDeploymentDescription.isPresent()) { - final String appDeploymentId = - applicationDeploymentDescription.get().getAppDeploymentId(); - if (!sharingClient.userHasAccess( - gatewayId, username + "@" + gatewayId, appDeploymentId, gatewayId + ":READ")) { - throw new AuthorizationException("User " + username + " in gateway " + gatewayId - + " doesn't have access to app deployment " + appDeploymentId); - } - } - } - } - submitExperiment(gatewayId, airavataExperimentId); - logger.info("Experiment with ExpId: " + airavataExperimentId + " was submitted in gateway with gatewayID: " - + gatewayId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - } catch (InvalidRequestException | ExperimentNotFoundException | AuthorizationException e) { - logger.error(e.getMessage(), e); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - throw e; - } catch (Exception e1) { - logger.error(airavataExperimentId, "Error while instantiate the registry instance", e1); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while instantiate the registry instance. More info : " + e1.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws AiravataClientException, AiravataSystemException, AuthorizationException, + ExperimentNotFoundException, InvalidRequestException, ProjectNotFoundException { + airavataService.launchExperiment(authzToken, gatewayId, airavataExperimentId); } - // private OrchestratorService.Client getOrchestratorClient() throws TException { - // try { - // final String serverHost = ServerSettings.getOrchestratorServerHost(); - // final int serverPort = ServerSettings.getOrchestratorServerPort(); - // return OrchestratorClientFactory.createOrchestratorClient(serverHost, serverPort); - // } catch (AiravataException e) { - // throw new TException(e); - // } - // } - /** * Clone an specified experiment with a new name. A copy of the experiment configuration is made and is persisted with new metadata. * The client has to subsequently update this configuration if needed and launch the cloned experiment. @@ -2522,33 +830,11 @@ public void launchExperiment(AuthzToken authzToken, final String airavataExperim public String cloneExperiment( AuthzToken authzToken, String existingExperimentID, String newExperimentName, String newExperimentProjectId) throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, AuthorizationException, ProjectNotFoundException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - // getExperiment will apply sharing permissions - ExperimentModel existingExperiment = this.getExperiment(authzToken, existingExperimentID); - String result = cloneExperimentInternal( - regClient, - sharingClient, - authzToken, - existingExperimentID, - newExperimentName, - newExperimentProjectId, - existingExperiment); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error(existingExperimentID, "Error while cloning the experiment with existing configuration...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while cloning the experiment with existing configuration. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + AiravataSystemException, AuthorizationException, ProjectNotFoundException { + // getExperiment will apply sharing permissions + ExperimentModel existingExperiment = airavataService.getExperiment(authzToken, existingExperimentID); + return airavataService.cloneExperiment( + authzToken, existingExperimentID, newExperimentName, newExperimentProjectId, existingExperiment); } @Override @@ -2556,140 +842,18 @@ public String cloneExperiment( public String cloneExperimentByAdmin( AuthzToken authzToken, String existingExperimentID, String newExperimentName, String newExperimentProjectId) throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, AuthorizationException, ProjectNotFoundException, TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - // get existing experiment by bypassing normal sharing permissions for the admin user - ExperimentModel existingExperiment = this.getExperimentByAdmin(authzToken, existingExperimentID); - String result = cloneExperimentInternal( - regClient, - sharingClient, - authzToken, - existingExperimentID, - newExperimentName, - newExperimentProjectId, - existingExperiment); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error(existingExperimentID, "Error while cloning the experiment with existing configuration...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while cloning the experiment with existing configuration. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } - } - - private String cloneExperimentInternal( - RegistryService.Client regClient, - SharingRegistryService.Client sharingClient, - AuthzToken authzToken, - String existingExperimentID, - String newExperimentName, - String newExperimentProjectId, - ExperimentModel existingExperiment) - throws ExperimentNotFoundException, ProjectNotFoundException, TException, AuthorizationException, - ApplicationSettingsException { - if (existingExperiment == null) { - logger.error( - existingExperimentID, - "Error while cloning experiment {}, experiment doesn't exist.", - existingExperimentID); - throw new ExperimentNotFoundException( - "Requested experiment id " + existingExperimentID + " does not exist in the system.."); - } - if (newExperimentProjectId != null) { - - // getProject will apply sharing permissions - Project project = this.getProject(authzToken, newExperimentProjectId); - if (project == null) { - logger.error( - "Error while cloning experiment {}, project {} doesn't exist.", - existingExperimentID, - newExperimentProjectId); - throw new ProjectNotFoundException( - "Requested project id " + newExperimentProjectId + " does not exist in the system.."); - } - existingExperiment.setProjectId(project.getProjectID()); - } - - // make sure user has write access to the project - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, existingExperiment.getProjectId(), gatewayId + ":WRITE")) { - logger.error( - "Error while cloning experiment {}, user doesn't have write access to project {}", - existingExperimentID, - existingExperiment.getProjectId()); - throw new AuthorizationException("User does not have permission to clone an experiment in this project"); - } - - existingExperiment.setCreationTime(AiravataUtils.getCurrentTimestamp().getTime()); - if (existingExperiment.getExecutionId() != null) { - List applicationOutputs = - regClient.getApplicationOutputs(existingExperiment.getExecutionId()); - existingExperiment.setExperimentOutputs(applicationOutputs); - } - if (validateString(newExperimentName)) { - existingExperiment.setExperimentName(newExperimentName); - } - existingExperiment.unsetErrors(); - existingExperiment.unsetProcesses(); - existingExperiment.unsetExperimentStatus(); - if (existingExperiment.getUserConfigurationData() != null - && existingExperiment.getUserConfigurationData().getComputationalResourceScheduling() != null - && existingExperiment - .getUserConfigurationData() - .getComputationalResourceScheduling() - .getResourceHostId() - != null) { - String compResourceId = existingExperiment - .getUserConfigurationData() - .getComputationalResourceScheduling() - .getResourceHostId(); - - ComputeResourceDescription computeResourceDescription = regClient.getComputeResource(compResourceId); - if (!computeResourceDescription.isEnabled()) { - existingExperiment.getUserConfigurationData().setComputationalResourceScheduling(null); - } - } - logger.debug("Airavata cloned experiment with experiment id : " + existingExperimentID); - existingExperiment.setUserName(userId); - String expId = regClient.createExperiment(gatewayId, existingExperiment); - - if (ServerSettings.isEnableSharing()) { - try { - Entity entity = new Entity(); - entity.setEntityId(expId); - final String domainId = existingExperiment.getGatewayId(); - entity.setDomainId(domainId); - entity.setEntityTypeId(domainId + ":" + "EXPERIMENT"); - entity.setOwnerId(existingExperiment.getUserName() + "@" + domainId); - entity.setName(existingExperiment.getExperimentName()); - entity.setDescription(existingExperiment.getDescription()); - sharingClient.createEntity(entity); - shareEntityWithAdminGatewayGroups(regClient, sharingClient, entity); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - logger.error("rolling back experiment creation Exp ID : " + expId); - regClient.deleteExperiment(expId); - } - } - - return expId; + AiravataSystemException, AuthorizationException, ProjectNotFoundException { + // get existing experiment by bypassing normal sharing permissions for the admin user + ExperimentModel existingExperiment = airavataService.getExperimentByAdmin(authzToken, existingExperimentID); + return airavataService.cloneExperiment( + authzToken, existingExperimentID, newExperimentName, newExperimentProjectId, existingExperiment); } /** * Terminate a running experiment. * * @param airavataExperimentId The identifier for the requested experiment. This is returned during the create experiment step. - * @return This method call does not have a return value. + * @This method call does not have a value. * @throws org.apache.airavata.model.error.InvalidRequestException For any incorrect forming of the request itself. * @throws org.apache.airavata.model.error.ExperimentNotFoundException If the specified experiment is not previously created, then an Experiment Not Found Exception is thrown. * @throws org.apache.airavata.model.error.AiravataClientException The following list of exceptions are thrown which Airavata Client can take corrective actions to resolve: @@ -2709,49 +873,9 @@ private String cloneExperimentInternal( @Override @SecurityCheck public void terminateExperiment(AuthzToken authzToken, String airavataExperimentId, String gatewayId) - throws TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - ExperimentModel existingExperiment = regClient.getExperiment(airavataExperimentId); - ExperimentStatus experimentLastStatus = regClient.getExperimentStatus(airavataExperimentId); - if (existingExperiment == null) { - logger.error( - airavataExperimentId, - "Error while cancelling experiment {}, experiment doesn't exist.", - airavataExperimentId); - throw new ExperimentNotFoundException( - "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); - } - switch (experimentLastStatus.getState()) { - case COMPLETED: - case CANCELED: - case FAILED: - case CANCELING: - logger.warn( - "Can't terminate already {} experiment", - existingExperiment - .getExperimentStatus() - .get(0) - .getState() - .name()); - break; - case CREATED: - logger.warn("Experiment termination is only allowed for launched experiments."); - break; - default: - submitCancelExperiment(gatewayId, airavataExperimentId); - logger.debug("Airavata cancelled experiment with experiment id : " + airavataExperimentId); - break; - } - registryClientPool.returnResource(regClient); - } catch (RegistryServiceException | AiravataException e) { - logger.error(airavataExperimentId, "Error while cancelling the experiment...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while cancelling the experiment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, + ExperimentNotFoundException { + airavataService.terminateExperiment(airavataExperimentId, gatewayId); } /** @@ -2765,21 +889,8 @@ public void terminateExperiment(AuthzToken authzToken, String airavataExperiment @SecurityCheck public String registerApplicationModule( AuthzToken authzToken, String gatewayId, ApplicationModule applicationModule) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.registerApplicationModule(gatewayId, applicationModule); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while adding application module...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding application module. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.registerApplicationModule(gatewayId, applicationModule); } /** @@ -2792,21 +903,8 @@ public String registerApplicationModule( @Override @SecurityCheck public ApplicationModule getApplicationModule(AuthzToken authzToken, String appModuleId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - ApplicationModule result = regClient.getApplicationModule(appModuleId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(appModuleId, "Error while retrieving application module...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving the adding application module. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getApplicationModule(appModuleId); } /** @@ -2821,21 +919,8 @@ public ApplicationModule getApplicationModule(AuthzToken authzToken, String appM @SecurityCheck public boolean updateApplicationModule( AuthzToken authzToken, String appModuleId, ApplicationModule applicationModule) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateApplicationModule(appModuleId, applicationModule); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(appModuleId, "Error while updating application module...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating application module. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateApplicationModule(appModuleId, applicationModule); } /** @@ -2847,21 +932,8 @@ public boolean updateApplicationModule( @Override @SecurityCheck public List getAllAppModules(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getAllAppModules(gatewayId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving all application modules...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving all application modules. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllAppModules(gatewayId); } /** @@ -2873,58 +945,8 @@ public List getAllAppModules(AuthzToken authzToken, String ga @Override @SecurityCheck public List getAccessibleAppModules(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - List accessibleAppDeploymentIds = new ArrayList<>(); - if (ServerSettings.isEnableSharing()) { - List sharingFilters = new ArrayList<>(); - SearchCriteria entityTypeFilter = new SearchCriteria(); - entityTypeFilter.setSearchField(EntitySearchField.ENTITY_TYPE_ID); - entityTypeFilter.setSearchCondition(SearchCondition.EQUAL); - entityTypeFilter.setValue(gatewayId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); - sharingFilters.add(entityTypeFilter); - SearchCriteria permissionTypeFilter = new SearchCriteria(); - permissionTypeFilter.setSearchField(EntitySearchField.PERMISSION_TYPE_ID); - permissionTypeFilter.setSearchCondition(SearchCondition.EQUAL); - permissionTypeFilter.setValue(gatewayId + ":" + ResourcePermissionType.READ); - sharingFilters.add(permissionTypeFilter); - sharingClient - .searchEntities( - authzToken.getClaimsMap().get(Constants.GATEWAY_ID), - userName + "@" + gatewayId, - sharingFilters, - 0, - -1) - .forEach(a -> accessibleAppDeploymentIds.add(a.getEntityId())); - } - List accessibleComputeResourceIds = new ArrayList<>(); - List groupResourceProfileList = getGroupResourceList(authzToken, gatewayId); - for (GroupResourceProfile groupResourceProfile : groupResourceProfileList) { - List groupComputeResourcePreferenceList = - groupResourceProfile.getComputePreferences(); - for (GroupComputeResourcePreference groupComputeResourcePreference : - groupComputeResourcePreferenceList) { - accessibleComputeResourceIds.add(groupComputeResourcePreference.getComputeResourceId()); - } - } - List result = regClient.getAccessibleAppModules( - gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving all application modules...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving all application modules. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAccessibleAppModules(authzToken, gatewayId); } /** @@ -2937,21 +959,8 @@ public List getAccessibleAppModules(AuthzToken authzToken, St @Override @SecurityCheck public boolean deleteApplicationModule(AuthzToken authzToken, String appModuleId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteApplicationModule(appModuleId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(appModuleId, "Error while deleting application module...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while deleting the application module. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteApplicationModule(appModuleId); } /** @@ -2964,36 +973,8 @@ public boolean deleteApplicationModule(AuthzToken authzToken, String appModuleId @SecurityCheck public String registerApplicationDeployment( AuthzToken authzToken, String gatewayId, ApplicationDeploymentDescription applicationDeployment) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - // TODO: verify that gatewayId matches authzToken gatewayId - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - String result = regClient.registerApplicationDeployment(gatewayId, applicationDeployment); - Entity entity = new Entity(); - entity.setEntityId(result); - final String domainId = gatewayId; - entity.setDomainId(domainId); - entity.setEntityTypeId(domainId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); - String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - entity.setOwnerId(userName + "@" + domainId); - entity.setName(result); - entity.setDescription(applicationDeployment.getAppDeploymentDescription()); - sharingClient.createEntity(entity); - shareEntityWithAdminGatewayGroups(regClient, sharingClient, entity); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error("Error while adding application deployment...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding application deployment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.registerApplicationDeployment(authzToken, gatewayId, applicationDeployment); } /** @@ -3006,32 +987,8 @@ public String registerApplicationDeployment( @Override @SecurityCheck public ApplicationDeploymentDescription getApplicationDeployment(AuthzToken authzToken, String appDeploymentId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - final boolean hasAccess = - userHasAccessInternal(sharingClient, authzToken, appDeploymentId, ResourcePermissionType.READ); - if (!hasAccess) { - throw new AuthorizationException( - "User does not have access to application deployment " + appDeploymentId); - } - } - ApplicationDeploymentDescription result = regClient.getApplicationDeployment(appDeploymentId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error(appDeploymentId, "Error while retrieving application deployment...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving application deployment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getApplicationDeployment(authzToken, appDeploymentId); } /** @@ -3046,32 +1003,8 @@ public ApplicationDeploymentDescription getApplicationDeployment(AuthzToken auth @SecurityCheck public boolean updateApplicationDeployment( AuthzToken authzToken, String appDeploymentId, ApplicationDeploymentDescription applicationDeployment) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - final boolean hasAccess = - userHasAccessInternal(sharingClient, authzToken, appDeploymentId, ResourcePermissionType.WRITE); - if (!hasAccess) { - throw new AuthorizationException( - "User does not have WRITE access to application deployment " + appDeploymentId); - } - } - boolean result = regClient.updateApplicationDeployment(appDeploymentId, applicationDeployment); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error(appDeploymentId, "Error while updating application deployment...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating application deployment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateApplicationDeployment(authzToken, appDeploymentId, applicationDeployment); } /** @@ -3084,32 +1017,8 @@ public boolean updateApplicationDeployment( @Override @SecurityCheck public boolean deleteApplicationDeployment(AuthzToken authzToken, String appDeploymentId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - final boolean hasAccess = - userHasAccessInternal(sharingClient, authzToken, appDeploymentId, ResourcePermissionType.WRITE); - if (!hasAccess) { - throw new AuthorizationException( - "User does not have WRITE access to application deployment " + appDeploymentId); - } - final String domainId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - boolean result = regClient.deleteApplicationDeployment(appDeploymentId); - sharingClient.deleteEntity(domainId, appDeploymentId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error(appDeploymentId, "Error while deleting application deployment...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while deleting application deployment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteApplicationDeployment(authzToken, appDeploymentId); } /** @@ -3121,8 +1030,7 @@ public boolean deleteApplicationDeployment(AuthzToken authzToken, String appDepl @Override @SecurityCheck public List getAllApplicationDeployments(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { return getAccessibleApplicationDeployments(authzToken, gatewayId, ResourcePermissionType.READ); } @@ -3136,58 +1044,8 @@ public List getAllApplicationDeployments(Authz @SecurityCheck public List getAccessibleApplicationDeployments( AuthzToken authzToken, String gatewayId, ResourcePermissionType permissionType) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - List accessibleAppDeploymentIds = new ArrayList<>(); - if (ServerSettings.isEnableSharing()) { - List sharingFilters = new ArrayList<>(); - SearchCriteria entityTypeFilter = new SearchCriteria(); - entityTypeFilter.setSearchField(EntitySearchField.ENTITY_TYPE_ID); - entityTypeFilter.setSearchCondition(SearchCondition.EQUAL); - entityTypeFilter.setValue(gatewayId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); - sharingFilters.add(entityTypeFilter); - SearchCriteria permissionTypeFilter = new SearchCriteria(); - permissionTypeFilter.setSearchField(EntitySearchField.PERMISSION_TYPE_ID); - permissionTypeFilter.setSearchCondition(SearchCondition.EQUAL); - permissionTypeFilter.setValue(gatewayId + ":" + permissionType.name()); - sharingFilters.add(permissionTypeFilter); - sharingClient - .searchEntities( - authzToken.getClaimsMap().get(Constants.GATEWAY_ID), - userName + "@" + gatewayId, - sharingFilters, - 0, - -1) - .forEach(a -> accessibleAppDeploymentIds.add(a.getEntityId())); - } - List accessibleComputeResourceIds = new ArrayList<>(); - List groupResourceProfileList = getGroupResourceList(authzToken, gatewayId); - for (GroupResourceProfile groupResourceProfile : groupResourceProfileList) { - List groupComputeResourcePreferenceList = - groupResourceProfile.getComputePreferences(); - for (GroupComputeResourcePreference groupComputeResourcePreference : - groupComputeResourcePreferenceList) { - accessibleComputeResourceIds.add(groupComputeResourcePreference.getComputeResourceId()); - } - } - List result = regClient.getAccessibleApplicationDeployments( - gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving application deployments...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving application deployments. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAccessibleApplicationDeployments(authzToken, gatewayId, permissionType); } /** @@ -3201,22 +1059,8 @@ public List getAccessibleApplicationDeployment @SecurityCheck @Deprecated public List getAppModuleDeployedResources(AuthzToken authzToken, String appModuleId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - // TODO: restrict to only application deployments that are accessible to user - List result = regClient.getAppModuleDeployedResources(appModuleId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(appModuleId, "Error while retrieving application deployments...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving application deployment. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAppModuleDeployedResources(appModuleId); } /** @@ -3236,60 +1080,9 @@ public List getAppModuleDeployedResources(AuthzToken authzToken, String @SecurityCheck public List getApplicationDeploymentsForAppModuleAndGroupResourceProfile( AuthzToken authzToken, String appModuleId, String groupResourceProfileId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - // Get list of compute resources for this Group Resource Profile - if (!userHasAccessInternal( - sharingClient, authzToken, groupResourceProfileId, ResourcePermissionType.READ)) { - throw new AuthorizationException( - "User is not authorized to access Group Resource Profile " + groupResourceProfileId); - } - GroupResourceProfile groupResourceProfile = regClient.getGroupResourceProfile(groupResourceProfileId); - List accessibleComputeResourceIds = groupResourceProfile.getComputePreferences().stream() - .map(compPref -> compPref.getComputeResourceId()) - .collect(Collectors.toList()); - - // Get list of accessible Application Deployments - List accessibleAppDeploymentIds = new ArrayList<>(); - List sharingFilters = new ArrayList<>(); - SearchCriteria entityTypeFilter = new SearchCriteria(); - entityTypeFilter.setSearchField(EntitySearchField.ENTITY_TYPE_ID); - entityTypeFilter.setSearchCondition(SearchCondition.EQUAL); - entityTypeFilter.setValue(gatewayId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); - sharingFilters.add(entityTypeFilter); - SearchCriteria permissionTypeFilter = new SearchCriteria(); - permissionTypeFilter.setSearchField(EntitySearchField.PERMISSION_TYPE_ID); - permissionTypeFilter.setSearchCondition(SearchCondition.EQUAL); - permissionTypeFilter.setValue(gatewayId + ":" + ResourcePermissionType.READ); - sharingFilters.add(permissionTypeFilter); - sharingClient - .searchEntities(gatewayId, userName + "@" + gatewayId, sharingFilters, 0, -1) - .forEach(a -> accessibleAppDeploymentIds.add(a.getEntityId())); - - List result = regClient.getAccessibleApplicationDeploymentsForAppModule( - gatewayId, appModuleId, accessibleAppDeploymentIds, accessibleComputeResourceIds); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (AuthorizationException checkedException) { - logger.error("Error while retrieving application deployments...", checkedException); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - throw checkedException; - } catch (Exception e) { - logger.error("Error while retrieving application deployments...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving application deployments. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getApplicationDeploymentsForAppModuleAndGroupResourceProfile( + authzToken, appModuleId, groupResourceProfileId); } /** @@ -3302,54 +1095,16 @@ public List getApplicationDeploymentsForAppMod @SecurityCheck public String registerApplicationInterface( AuthzToken authzToken, String gatewayId, ApplicationInterfaceDescription applicationInterface) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.registerApplicationInterface(gatewayId, applicationInterface); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while adding application interface...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding application interface. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.registerApplicationInterface(gatewayId, applicationInterface); } @Override @SecurityCheck public String cloneApplicationInterface( AuthzToken authzToken, String existingAppInterfaceID, String newApplicationName, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - ApplicationInterfaceDescription existingInterface = - regClient.getApplicationInterface(existingAppInterfaceID); - if (existingInterface == null) { - logger.error( - "Provided application interface does not exist.Please provide a valid application interface id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - - existingInterface.setApplicationName(newApplicationName); - existingInterface.setApplicationInterfaceId(airavata_commonsConstants.DEFAULT_ID); - String interfaceId = regClient.registerApplicationInterface(gatewayId, existingInterface); - logger.debug("Airavata cloned application interface : " + existingAppInterfaceID + " for gateway id : " - + gatewayId); - registryClientPool.returnResource(regClient); - return interfaceId; - } catch (Exception e) { - logger.error("Error while adding application interface...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding application interface. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.cloneApplicationInterface(existingAppInterfaceID, newApplicationName, gatewayId); } /** @@ -3362,21 +1117,8 @@ public String cloneApplicationInterface( @Override @SecurityCheck public ApplicationInterfaceDescription getApplicationInterface(AuthzToken authzToken, String appInterfaceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - ApplicationInterfaceDescription result = regClient.getApplicationInterface(appInterfaceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(appInterfaceId, "Error while retrieving application interface...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving application interface. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getApplicationInterface(appInterfaceId); } /** @@ -3391,21 +1133,8 @@ public ApplicationInterfaceDescription getApplicationInterface(AuthzToken authzT @SecurityCheck public boolean updateApplicationInterface( AuthzToken authzToken, String appInterfaceId, ApplicationInterfaceDescription applicationInterface) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateApplicationInterface(appInterfaceId, applicationInterface); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(appInterfaceId, "Error while updating application interface...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating application interface. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateApplicationInterface(appInterfaceId, applicationInterface); } /** @@ -3418,21 +1147,8 @@ public boolean updateApplicationInterface( @Override @SecurityCheck public boolean deleteApplicationInterface(AuthzToken authzToken, String appInterfaceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteApplicationInterface(appInterfaceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(appInterfaceId, "Error while deleting application interface...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while deleting application interface. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteApplicationInterface(appInterfaceId); } /** @@ -3444,21 +1160,8 @@ public boolean deleteApplicationInterface(AuthzToken authzToken, String appInter @Override @SecurityCheck public Map getAllApplicationInterfaceNames(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - Map result = regClient.getAllApplicationInterfaceNames(gatewayId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving application interfaces...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving application interfaces. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllApplicationInterfaceNames(gatewayId); } /** @@ -3470,21 +1173,8 @@ public Map getAllApplicationInterfaceNames(AuthzToken authzToken @Override @SecurityCheck public List getAllApplicationInterfaces(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getAllApplicationInterfaces(gatewayId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving application interfaces...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving application interfaces. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllApplicationInterfaces(gatewayId); } /** @@ -3497,21 +1187,8 @@ public List getAllApplicationInterfaces(AuthzTo @Override @SecurityCheck public List getApplicationInputs(AuthzToken authzToken, String appInterfaceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getApplicationInputs(appInterfaceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(appInterfaceId, "Error while retrieving application inputs...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving application inputs. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getApplicationInputs(appInterfaceId); } /** @@ -3524,19 +1201,8 @@ public List getApplicationInputs(AuthzToken authzToken, Str @Override @SecurityCheck public List getApplicationOutputs(AuthzToken authzToken, String appInterfaceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getApplicationOutputs(appInterfaceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - AiravataSystemException exception = new AiravataSystemException(); - exception.setMessage(e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getApplicationOutputs(appInterfaceId); } /** @@ -3551,21 +1217,8 @@ public List getApplicationOutputs(AuthzToken authzToken, S @SecurityCheck @Deprecated public Map getAvailableAppInterfaceComputeResources(AuthzToken authzToken, String appInterfaceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - Map result = regClient.getAvailableAppInterfaceComputeResources(appInterfaceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(appInterfaceId, "Error while saving compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while saving compute resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAvailableAppInterfaceComputeResources(appInterfaceId); } /** @@ -3578,21 +1231,8 @@ public Map getAvailableAppInterfaceComputeResources(AuthzToken a @Override @SecurityCheck public String registerComputeResource(AuthzToken authzToken, ComputeResourceDescription computeResourceDescription) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.registerComputeResource(computeResourceDescription); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while saving compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while saving compute resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.registerComputeResource(computeResourceDescription); } /** @@ -3605,21 +1245,8 @@ public String registerComputeResource(AuthzToken authzToken, ComputeResourceDesc @Override @SecurityCheck public ComputeResourceDescription getComputeResource(AuthzToken authzToken, String computeResourceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - ComputeResourceDescription result = regClient.getComputeResource(computeResourceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(computeResourceId, "Error while retrieving compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving compute resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getComputeResource(computeResourceId); } /** @@ -3631,21 +1258,8 @@ public ComputeResourceDescription getComputeResource(AuthzToken authzToken, Stri @Override @SecurityCheck public Map getAllComputeResourceNames(AuthzToken authzToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - Map result = regClient.getAllComputeResourceNames(); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving compute resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllComputeResourceNames(); } /** @@ -3660,21 +1274,8 @@ public Map getAllComputeResourceNames(AuthzToken authzToken) @SecurityCheck public boolean updateComputeResource( AuthzToken authzToken, String computeResourceId, ComputeResourceDescription computeResourceDescription) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateComputeResource(computeResourceId, computeResourceDescription); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(computeResourceId, "Error while updating compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updaing compute resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateComputeResource(computeResourceId, computeResourceDescription); } /** @@ -3687,21 +1288,8 @@ public boolean updateComputeResource( @Override @SecurityCheck public boolean deleteComputeResource(AuthzToken authzToken, String computeResourceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteComputeResource(computeResourceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(computeResourceId, "Error while deleting compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while deleting compute resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteComputeResource(computeResourceId); } /** @@ -3715,21 +1303,8 @@ public boolean deleteComputeResource(AuthzToken authzToken, String computeResour @Override @SecurityCheck public String registerStorageResource(AuthzToken authzToken, StorageResourceDescription storageResourceDescription) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.registerStorageResource(storageResourceDescription); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while saving storage resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while saving storage resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.registerStorageResource(storageResourceDescription); } /** @@ -3743,21 +1318,8 @@ public String registerStorageResource(AuthzToken authzToken, StorageResourceDesc @Override @SecurityCheck public StorageResourceDescription getStorageResource(AuthzToken authzToken, String storageResourceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - StorageResourceDescription result = regClient.getStorageResource(storageResourceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(storageResourceId, "Error while retrieving storage resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving storage resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getStorageResource(storageResourceId); } /** @@ -3770,21 +1332,8 @@ public StorageResourceDescription getStorageResource(AuthzToken authzToken, Stri @Override @SecurityCheck public Map getAllStorageResourceNames(AuthzToken authzToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - Map result = regClient.getAllStorageResourceNames(); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving storage resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving storage resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllStorageResourceNames(); } /** @@ -3800,21 +1349,8 @@ public Map getAllStorageResourceNames(AuthzToken authzToken) @SecurityCheck public boolean updateStorageResource( AuthzToken authzToken, String storageResourceId, StorageResourceDescription storageResourceDescription) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateStorageResource(storageResourceId, storageResourceDescription); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(storageResourceId, "Error while updating storage resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updaing storage resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateStorageResource(storageResourceId, storageResourceDescription); } /** @@ -3828,171 +1364,22 @@ public boolean updateStorageResource( @Override @SecurityCheck public boolean deleteStorageResource(AuthzToken authzToken, String storageResourceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteStorageResource(storageResourceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(storageResourceId, "Error while deleting storage resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while deleting storage resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteStorageResource(storageResourceId); } @Override @SecurityCheck public StorageVolumeInfo getResourceStorageInfo(AuthzToken authzToken, String resourceId, String location) - throws TException { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - RegistryService.Client regClient = registryClientPool.getResource(); - StorageInfoContext context; - - try { - Optional computeResourceOp = Optional.empty(); - try { - ComputeResourceDescription computeResource = regClient.getComputeResource(resourceId); - if (computeResource != null) { - computeResourceOp = Optional.of(computeResource); - } - } catch (TApplicationException e) { - // TApplicationException with "unknown result" means resource not found (null return for non-nullable - // type) - logger.debug("Compute resource {} not found (TApplicationException): {}", resourceId, e.getMessage()); - } - - Optional storageResourceOp = Optional.empty(); - if (computeResourceOp.isEmpty()) { - try { - StorageResourceDescription storageResource = regClient.getStorageResource(resourceId); - if (storageResource != null) { - storageResourceOp = Optional.of(storageResource); - } - } catch (TApplicationException e) { - // TApplicationException with "unknown result" means resource not found (null return for - // non-nullable type) - logger.debug( - "Storage resource {} not found (TApplicationException): {}", resourceId, e.getMessage()); - } - } - - if (computeResourceOp.isEmpty() && storageResourceOp.isEmpty()) { - logger.error( - "Resource with ID {} not found as either compute resource or storage resource", resourceId); - throw new InvalidRequestException("Resource with ID '" + resourceId - + "' not found as either compute resource or storage resource"); - } - - if (computeResourceOp.isPresent()) { - logger.debug("Found compute resource with ID {}. Resolving login username and credentials", resourceId); - context = resolveComputeStorageInfoContext(authzToken, gatewayId, userId, resourceId); - } else { - logger.debug("Found storage resource with ID {}. Resolving login username and credentials", resourceId); - context = resolveStorageStorageInfoContext(authzToken, gatewayId, userId, resourceId); - } - - registryClientPool.returnResource(regClient); - regClient = null; - - return context.adaptor.getStorageVolumeInfo(location); - - } catch (InvalidRequestException | AiravataClientException e) { - if (regClient != null) { - registryClientPool.returnResource(regClient); - } - logger.error("Error while retrieving storage resource.", e); - throw e; - - } catch (Exception e) { - logger.error("Error while retrieving storage volume info for resource {}", resourceId, e); - registryClientPool.returnBrokenResource(regClient); - - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving storage volume info. More info: " + e.getMessage()); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getResourceStorageInfo(authzToken, resourceId, location); } @Override @SecurityCheck public StorageDirectoryInfo getStorageDirectoryInfo(AuthzToken authzToken, String resourceId, String location) - throws TException { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - RegistryService.Client regClient = registryClientPool.getResource(); - StorageInfoContext context; - - try { - Optional computeResourceOp = Optional.empty(); - try { - ComputeResourceDescription computeResource = regClient.getComputeResource(resourceId); - if (computeResource != null) { - computeResourceOp = Optional.of(computeResource); - } - } catch (TApplicationException e) { - // TApplicationException with "unknown result" means resource not found (null return for non-nullable - // type) - logger.debug("Compute resource {} not found (TApplicationException): {}", resourceId, e.getMessage()); - } - - Optional storageResourceOp = Optional.empty(); - if (computeResourceOp.isEmpty()) { - try { - StorageResourceDescription storageResource = regClient.getStorageResource(resourceId); - if (storageResource != null) { - storageResourceOp = Optional.of(storageResource); - } - } catch (TApplicationException e) { - // TApplicationException with "unknown result" means resource not found (null return for - // non-nullable type) - logger.debug( - "Storage resource {} not found (TApplicationException): {}", resourceId, e.getMessage()); - } - } - - if (computeResourceOp.isEmpty() && storageResourceOp.isEmpty()) { - logger.error( - "Resource with ID {} not found as either compute resource or storage resource", resourceId); - throw new InvalidRequestException("Resource with ID '" + resourceId - + "' not found as either compute resource or storage resource"); - } - - if (computeResourceOp.isPresent()) { - logger.debug("Found compute resource with ID {}. Resolving login username and credentials", resourceId); - context = resolveComputeStorageInfoContext(authzToken, gatewayId, userId, resourceId); - } else { - logger.debug("Found storage resource with ID {}. Resolving login username and credentials", resourceId); - context = resolveStorageStorageInfoContext(authzToken, gatewayId, userId, resourceId); - } - - registryClientPool.returnResource(regClient); - regClient = null; - - return context.adaptor.getStorageDirectoryInfo(location); - - } catch (InvalidRequestException | AiravataClientException e) { - if (regClient != null) { - registryClientPool.returnResource(regClient); - } - logger.error("Error while retrieving storage resource.", e); - throw e; - - } catch (Exception e) { - logger.error("Error while retrieving storage volume info for resource {}", resourceId, e); - registryClientPool.returnBrokenResource(regClient); - - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving storage volume info. More info: " + e.getMessage()); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getStorageDirectoryInfo(authzToken, resourceId, location); } /** @@ -4009,26 +1396,8 @@ public StorageDirectoryInfo getStorageDirectoryInfo(AuthzToken authzToken, Strin @SecurityCheck public String addLocalSubmissionDetails( AuthzToken authzToken, String computeResourceId, int priorityOrder, LOCALSubmission localSubmission) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.addLocalSubmissionDetails(computeResourceId, priorityOrder, localSubmission); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - computeResourceId, - "Error while adding job submission interface to resource compute resource...", - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws AiravataSystemException { + return airavataService.addLocalSubmissionDetails(computeResourceId, priorityOrder, localSubmission); } /** @@ -4043,47 +1412,15 @@ public String addLocalSubmissionDetails( @SecurityCheck public boolean updateLocalSubmissionDetails( AuthzToken authzToken, String jobSubmissionInterfaceId, LOCALSubmission localSubmission) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateLocalSubmissionDetails(jobSubmissionInterfaceId, localSubmission); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - jobSubmissionInterfaceId, - "Error while adding job submission interface to resource compute resource...", - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateLocalSubmissionDetails(jobSubmissionInterfaceId, localSubmission); } @Override @SecurityCheck public LOCALSubmission getLocalJobSubmission(AuthzToken authzToken, String jobSubmissionId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - LOCALSubmission result = regClient.getLocalJobSubmission(jobSubmissionId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String errorMsg = "Error while retrieving local job submission interface to resource compute resource..."; - logger.error(jobSubmissionId, errorMsg, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(errorMsg + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getLocalJobSubmission(jobSubmissionId); } /** @@ -4100,26 +1437,8 @@ public LOCALSubmission getLocalJobSubmission(AuthzToken authzToken, String jobSu @SecurityCheck public String addSSHJobSubmissionDetails( AuthzToken authzToken, String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.addSSHJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - computeResourceId, - "Error while adding job submission interface to resource compute resource...", - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addSSHJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission); } /** @@ -4136,48 +1455,15 @@ public String addSSHJobSubmissionDetails( @SecurityCheck public String addSSHForkJobSubmissionDetails( AuthzToken authzToken, String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = - regClient.addSSHForkJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - computeResourceId, - "Error while adding job submission interface to resource compute resource...", - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addSSHForkJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission); } @Override @SecurityCheck public SSHJobSubmission getSSHJobSubmission(AuthzToken authzToken, String jobSubmissionId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - SSHJobSubmission result = regClient.getSSHJobSubmission(jobSubmissionId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String errorMsg = "Error while retrieving SSH job submission interface to resource compute resource..."; - logger.error(jobSubmissionId, errorMsg, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(errorMsg + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getSSHJobSubmission(jobSubmissionId); } /** @@ -4194,48 +1480,15 @@ public SSHJobSubmission getSSHJobSubmission(AuthzToken authzToken, String jobSub @SecurityCheck public String addCloudJobSubmissionDetails( AuthzToken authzToken, String computeResourceId, int priorityOrder, CloudJobSubmission cloudJobSubmission) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = - regClient.addCloudJobSubmissionDetails(computeResourceId, priorityOrder, cloudJobSubmission); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - computeResourceId, - "Error while adding job submission interface to resource compute resource...", - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addCloudJobSubmissionDetails(computeResourceId, priorityOrder, cloudJobSubmission); } @Override @SecurityCheck public CloudJobSubmission getCloudJobSubmission(AuthzToken authzToken, String jobSubmissionId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - CloudJobSubmission result = regClient.getCloudJobSubmission(jobSubmissionId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String errorMsg = "Error while retrieving Cloud job submission interface to resource compute resource..."; - logger.error(jobSubmissionId, errorMsg, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(errorMsg + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getCloudJobSubmission(jobSubmissionId); } @Override @@ -4245,45 +1498,15 @@ public String addUNICOREJobSubmissionDetails( String computeResourceId, int priorityOrder, UnicoreJobSubmission unicoreJobSubmission) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = - regClient.addUNICOREJobSubmissionDetails(computeResourceId, priorityOrder, unicoreJobSubmission); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while adding job submission interface to resource compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addUNICOREJobSubmissionDetails(computeResourceId, priorityOrder, unicoreJobSubmission); } @Override @SecurityCheck public UnicoreJobSubmission getUnicoreJobSubmission(AuthzToken authzToken, String jobSubmissionId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - UnicoreJobSubmission result = regClient.getUnicoreJobSubmission(jobSubmissionId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String errorMsg = "Error while retrieving Unicore job submission interface to resource compute resource..."; - logger.error(jobSubmissionId, errorMsg, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(errorMsg + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getUnicoreJobSubmission(jobSubmissionId); } /** @@ -4298,26 +1521,8 @@ public UnicoreJobSubmission getUnicoreJobSubmission(AuthzToken authzToken, Strin @SecurityCheck public boolean updateSSHJobSubmissionDetails( AuthzToken authzToken, String jobSubmissionInterfaceId, SSHJobSubmission sshJobSubmission) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateSSHJobSubmissionDetails(jobSubmissionInterfaceId, sshJobSubmission); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - jobSubmissionInterfaceId, - "Error while adding job submission interface to resource compute resource...", - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateSSHJobSubmissionDetails(jobSubmissionInterfaceId, sshJobSubmission); } /** @@ -4332,53 +1537,16 @@ public boolean updateSSHJobSubmissionDetails( @SecurityCheck public boolean updateCloudJobSubmissionDetails( AuthzToken authzToken, String jobSubmissionInterfaceId, CloudJobSubmission cloudJobSubmission) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateCloudJobSubmissionDetails(jobSubmissionInterfaceId, cloudJobSubmission); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - jobSubmissionInterfaceId, - "Error while adding job submission interface to resource compute resource...", - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateCloudJobSubmissionDetails(jobSubmissionInterfaceId, cloudJobSubmission); } @Override @SecurityCheck public boolean updateUnicoreJobSubmissionDetails( AuthzToken authzToken, String jobSubmissionInterfaceId, UnicoreJobSubmission unicoreJobSubmission) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = - regClient.updateUnicoreJobSubmissionDetails(jobSubmissionInterfaceId, unicoreJobSubmission); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - jobSubmissionInterfaceId, - "Error while adding job submission interface to resource compute resource...", - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateUnicoreJobSubmissionDetails(jobSubmissionInterfaceId, unicoreJobSubmission); } /** @@ -4399,22 +1567,8 @@ public String addLocalDataMovementDetails( DMType dmType, int priorityOrder, LOCALDataMovement localDataMovement) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.addLocalDataMovementDetails(resourceId, dmType, priorityOrder, localDataMovement); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(resourceId, "Error while adding data movement interface to resource resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding data movement interface to resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addLocalDataMovementDetails(resourceId, dmType, priorityOrder, localDataMovement); } /** @@ -4429,42 +1583,8 @@ public String addLocalDataMovementDetails( @SecurityCheck public boolean updateLocalDataMovementDetails( AuthzToken authzToken, String dataMovementInterfaceId, LOCALDataMovement localDataMovement) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateLocalDataMovementDetails(dataMovementInterfaceId, localDataMovement); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(dataMovementInterfaceId, "Error while updating local data movement interface..", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating local data movement interface. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } - } - - @Override - @SecurityCheck - public LOCALDataMovement getLocalDataMovement(AuthzToken authzToken, String dataMovementId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - LOCALDataMovement result = regClient.getLocalDataMovement(dataMovementId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String errorMsg = "Error while retrieving local data movement interface to resource compute resource..."; - logger.error(dataMovementId, errorMsg, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(errorMsg + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateLocalDataMovementDetails(dataMovementInterfaceId, localDataMovement); } /** @@ -4481,22 +1601,8 @@ public LOCALDataMovement getLocalDataMovement(AuthzToken authzToken, String data @SecurityCheck public String addSCPDataMovementDetails( AuthzToken authzToken, String resourceId, DMType dmType, int priorityOrder, SCPDataMovement scpDataMovement) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.addSCPDataMovementDetails(resourceId, dmType, priorityOrder, scpDataMovement); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(resourceId, "Error while adding data movement interface to resource compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addSCPDataMovementDetails(resourceId, dmType, priorityOrder, scpDataMovement); } /** @@ -4512,47 +1618,15 @@ public String addSCPDataMovementDetails( @SecurityCheck public boolean updateSCPDataMovementDetails( AuthzToken authzToken, String dataMovementInterfaceId, SCPDataMovement scpDataMovement) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateSCPDataMovementDetails(dataMovementInterfaceId, scpDataMovement); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - dataMovementInterfaceId, - "Error while adding job submission interface to resource compute resource...", - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateSCPDataMovementDetails(dataMovementInterfaceId, scpDataMovement); } @Override @SecurityCheck public SCPDataMovement getSCPDataMovement(AuthzToken authzToken, String dataMovementId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - SCPDataMovement result = regClient.getSCPDataMovement(dataMovementId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String errorMsg = "Error while retrieving SCP data movement interface to resource compute resource..."; - logger.error(dataMovementId, errorMsg, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(errorMsg + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getSCPDataMovement(dataMovementId); } @Override @@ -4563,67 +1637,30 @@ public String addUnicoreDataMovementDetails( DMType dmType, int priorityOrder, UnicoreDataMovement unicoreDataMovement) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = - regClient.addUnicoreDataMovementDetails(resourceId, dmType, priorityOrder, unicoreDataMovement); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(resourceId, "Error while adding data movement interface to resource compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addUnicoreDataMovementDetails(resourceId, dmType, priorityOrder, unicoreDataMovement); } @Override @SecurityCheck public boolean updateUnicoreDataMovementDetails( AuthzToken authzToken, String dataMovementInterfaceId, UnicoreDataMovement unicoreDataMovement) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateUnicoreDataMovementDetails(dataMovementInterfaceId, unicoreDataMovement); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - dataMovementInterfaceId, "Error while updating unicore data movement to compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while updating unicore data movement to compute resource. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateUnicoreDataMovementDetails(dataMovementInterfaceId, unicoreDataMovement); + } + + @Override + @SecurityCheck + public LOCALDataMovement getLocalDataMovement(AuthzToken authzToken, String dataMovementId) + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getLocalDataMovement(dataMovementId); } @Override @SecurityCheck public UnicoreDataMovement getUnicoreDataMovement(AuthzToken authzToken, String dataMovementId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - UnicoreDataMovement result = regClient.getUnicoreDataMovement(dataMovementId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String errorMsg = "Error while retrieving UNICORE data movement interface..."; - logger.error(dataMovementId, errorMsg, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(errorMsg + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getUnicoreDataMovement(dataMovementId); } /** @@ -4644,24 +1681,9 @@ public String addGridFTPDataMovementDetails( DMType dmType, int priorityOrder, GridFTPDataMovement gridFTPDataMovement) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.addGridFTPDataMovementDetails( - computeResourceId, dmType, priorityOrder, gridFTPDataMovement); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - computeResourceId, "Error while adding data movement interface to resource compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addGridFTPDataMovementDetails( + computeResourceId, dmType, priorityOrder, gridFTPDataMovement); } /** @@ -4677,47 +1699,15 @@ public String addGridFTPDataMovementDetails( @SecurityCheck public boolean updateGridFTPDataMovementDetails( AuthzToken authzToken, String dataMovementInterfaceId, GridFTPDataMovement gridFTPDataMovement) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateGridFTPDataMovementDetails(dataMovementInterfaceId, gridFTPDataMovement); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error( - dataMovementInterfaceId, - "Error while adding job submission interface to resource compute resource...", - e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateGridFTPDataMovementDetails(dataMovementInterfaceId, gridFTPDataMovement); } @Override @SecurityCheck public GridFTPDataMovement getGridFTPDataMovement(AuthzToken authzToken, String dataMovementId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - GridFTPDataMovement result = regClient.getGridFTPDataMovement(dataMovementId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String errorMsg = "Error while retrieving GridFTP data movement interface to resource compute resource..."; - logger.error(dataMovementId, errorMsg, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(errorMsg + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getGridFTPDataMovement(dataMovementId); } /** @@ -4732,8 +1722,7 @@ public GridFTPDataMovement getGridFTPDataMovement(AuthzToken authzToken, String @SecurityCheck public boolean changeJobSubmissionPriority( AuthzToken authzToken, String jobSubmissionInterfaceId, int newPriorityOrder) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { return false; } @@ -4749,8 +1738,7 @@ public boolean changeJobSubmissionPriority( @SecurityCheck public boolean changeDataMovementPriority( AuthzToken authzToken, String dataMovementInterfaceId, int newPriorityOrder) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { return false; } @@ -4764,8 +1752,7 @@ public boolean changeDataMovementPriority( @Override @SecurityCheck public boolean changeJobSubmissionPriorities(AuthzToken authzToken, Map jobSubmissionPriorityMap) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { return false; } @@ -4779,8 +1766,7 @@ public boolean changeJobSubmissionPriorities(AuthzToken authzToken, Map dataMovementPriorityMap) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { return false; } @@ -4795,21 +1781,8 @@ public boolean changeDataMovementPriorities(AuthzToken authzToken, Map getAllGatewayComputeResourcePreferences( AuthzToken authzToken, String gatewayID) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getAllGatewayComputeResourcePreferences(gatewayID); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway compute resource preferences...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while reading gateway compute resource preferences. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllGatewayComputeResourcePreferences(gatewayID); } @Override @SecurityCheck public List getAllGatewayStoragePreferences(AuthzToken authzToken, String gatewayID) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getAllGatewayStoragePreferences(gatewayID); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway data storage preferences...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while reading gateway data storage preferences. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllGatewayStoragePreferences(gatewayID); } @Override @SecurityCheck public List getAllGatewayResourceProfiles(AuthzToken authzToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getAllGatewayResourceProfiles(); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while reading retrieving all gateway profiles. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllGatewayResourceProfiles(); } /** @@ -5242,44 +1994,17 @@ public boolean updateGatewayComputeResourcePreference( String gatewayID, String computeResourceId, ComputeResourcePreference computeResourcePreference) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateGatewayComputeResourcePreference( - gatewayID, computeResourceId, computeResourcePreference); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway compute resource preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while updating gateway compute resource preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateGatewayComputeResourcePreference( + gatewayID, computeResourceId, computeResourcePreference); } @Override @SecurityCheck public boolean updateGatewayStoragePreference( AuthzToken authzToken, String gatewayID, String storageId, StoragePreference dataStoragePreference) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateGatewayStoragePreference(gatewayID, storageId, dataStoragePreference); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway data storage preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating gateway data storage preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateGatewayStoragePreference(gatewayID, storageId, dataStoragePreference); } /** @@ -5294,49 +2019,21 @@ public boolean updateGatewayStoragePreference( @SecurityCheck public boolean deleteGatewayComputeResourcePreference( AuthzToken authzToken, String gatewayID, String computeResourceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteGatewayComputeResourcePreference(gatewayID, computeResourceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway compute resource preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while updating gateway compute resource preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteGatewayComputeResourcePreference(gatewayID, computeResourceId); } @Override @SecurityCheck public boolean deleteGatewayStoragePreference(AuthzToken authzToken, String gatewayID, String storageId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteGatewayStoragePreference(gatewayID, storageId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway data storage preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating gateway data storage preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteGatewayStoragePreference(gatewayID, storageId); } @Override @SecurityCheck public List getSSHAccountProvisioners(AuthzToken authzToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { List sshAccountProvisioners = new ArrayList<>(); List sshAccountProvisionerProviders = @@ -5374,90 +2071,24 @@ public List getSSHAccountProvisioners(AuthzToken authzTok @Override @SecurityCheck public boolean doesUserHaveSSHAccount(AuthzToken authzToken, String computeResourceId, String userId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - return SSHAccountManager.doesUserHaveSSHAccount(gatewayId, computeResourceId, userId); - } catch (Exception e) { - String errorMessage = "Error occurred while checking if [" + userId + "] has an SSH Account on [" - + computeResourceId + "]."; - logger.error(errorMessage, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(errorMessage + " More info : " + e.getMessage()); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.doesUserHaveSSHAccount(authzToken, computeResourceId, userId); } @Override @SecurityCheck public boolean isSSHSetupCompleteForUserComputeResourcePreference( AuthzToken authzToken, String computeResourceId, String airavataCredStoreToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - CredentialStoreService.Client csClient = csClientPool.getResource(); - SSHCredential sshCredential = null; - try { - sshCredential = csClient.getSSHCredential(airavataCredStoreToken, gatewayId); - csClientPool.returnResource(csClient); - } catch (Exception e) { - logger.error("Error occurred while retrieving SSH Credential", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error occurred while retrieving SSH Credential. More info : " + e.getMessage()); - csClientPool.returnBrokenResource(csClient); - throw exception; - } - - try { - return SSHAccountManager.isSSHAccountSetupComplete(gatewayId, computeResourceId, userId, sshCredential); - } catch (Exception e) { - final String msg = - "Error occurred while checking if setup of SSH account is complete for user [" + userId + "]."; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.isSSHAccountSetupComplete(authzToken, computeResourceId, airavataCredStoreToken); } @Override @SecurityCheck public UserComputeResourcePreference setupUserComputeResourcePreferencesForSSH( AuthzToken authzToken, String computeResourceId, String userId, String airavataCredStoreToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - CredentialStoreService.Client csClient = csClientPool.getResource(); - SSHCredential sshCredential = null; - try { - sshCredential = csClient.getSSHCredential(airavataCredStoreToken, gatewayId); - csClientPool.returnResource(csClient); - } catch (Exception e) { - logger.error("Error occurred while retrieving SSH Credential", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error occurred while retrieving SSH Credential. More info : " + e.getMessage()); - csClientPool.returnBrokenResource(csClient); - throw exception; - } - - try { - UserComputeResourcePreference userComputeResourcePreference = - SSHAccountManager.setupSSHAccount(gatewayId, computeResourceId, userId, sshCredential); - return userComputeResourcePreference; - } catch (Exception e) { - logger.error("Error occurred while automatically setting up SSH account for user [" + userId + "]", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error occurred while automatically setting up SSH account for user [" + userId - + "]. More info : " + e.getMessage()); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.setupSSHAccount(authzToken, computeResourceId, userId, airavataCredStoreToken); } /** @@ -5472,42 +2103,15 @@ public UserComputeResourcePreference setupUserComputeResourcePreferencesForSSH( @Override @SecurityCheck public String registerUserResourceProfile(AuthzToken authzToken, UserResourceProfile userResourceProfile) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.registerUserResourceProfile(userResourceProfile); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while registering user resource profile...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while registering user resource profile. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.registerUserResourceProfile(userResourceProfile); } @Override @SecurityCheck public boolean isUserResourceProfileExists(AuthzToken authzToken, String userId, String gatewayID) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.isUserResourceProfileExists(userId, gatewayID); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while checking existence of user resource profile for " + userId, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while checking existence of user resource profile. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.isUserResourceProfileExists(userId, gatewayID); } /** @@ -5523,21 +2127,8 @@ public boolean isUserResourceProfileExists(AuthzToken authzToken, String userId, @Override @SecurityCheck public UserResourceProfile getUserResourceProfile(AuthzToken authzToken, String userId, String gatewayID) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - UserResourceProfile result = regClient.getUserResourceProfile(userId, gatewayID); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error("Error while retrieving user resource profile for " + userId, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getUserResourceProfile(userId, gatewayID); } /** @@ -5553,20 +2144,8 @@ public UserResourceProfile getUserResourceProfile(AuthzToken authzToken, String @SecurityCheck public boolean updateUserResourceProfile( AuthzToken authzToken, String userId, String gatewayID, UserResourceProfile userResourceProfile) - throws TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateUserResourceProfile(userId, gatewayID, userResourceProfile); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while updating user resource profile...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating user resource profile. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateUserResourceProfile(userId, gatewayID, userResourceProfile); } /** @@ -5579,20 +2158,9 @@ public boolean updateUserResourceProfile( */ @Override @SecurityCheck - public boolean deleteUserResourceProfile(AuthzToken authzToken, String userId, String gatewayID) throws TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteUserResourceProfile(userId, gatewayID); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while removing user resource profile...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while removing user resource profile. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + public boolean deleteUserResourceProfile(AuthzToken authzToken, String userId, String gatewayID) + throws AiravataClientException, AiravataSystemException, AuthorizationException, InvalidRequestException { + return airavataService.deleteUserResourceProfile(userId, gatewayID); } /** @@ -5614,23 +2182,9 @@ public boolean addUserComputeResourcePreference( String gatewayID, String userComputeResourceId, UserComputeResourcePreference userComputeResourcePreference) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.addUserComputeResourcePreference( - userId, gatewayID, userComputeResourceId, userComputeResourcePreference); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while registering user resource profile preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while registering user resource profile preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addUserComputeResourcePreference( + userId, gatewayID, userComputeResourceId, userComputeResourcePreference); } @Override @@ -5641,22 +2195,9 @@ public boolean addUserStoragePreference( String gatewayID, String userStorageResourceId, UserStoragePreference dataStoragePreference) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = - regClient.addUserStoragePreference(userId, gatewayID, userStorageResourceId, dataStoragePreference); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while registering user storage preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while registering user storage preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.addUserStoragePreference( + userId, gatewayID, userStorageResourceId, dataStoragePreference); } /** @@ -5672,43 +2213,16 @@ public boolean addUserStoragePreference( @SecurityCheck public UserComputeResourcePreference getUserComputeResourcePreference( AuthzToken authzToken, String userId, String gatewayID, String userComputeResourceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - UserComputeResourcePreference result = - regClient.getUserComputeResourcePreference(userId, gatewayID, userComputeResourceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while reading user compute resource preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while reading user compute resource preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getUserComputeResourcePreference(userId, gatewayID, userComputeResourceId); } @Override @SecurityCheck public UserStoragePreference getUserStoragePreference( AuthzToken authzToken, String userId, String gatewayID, String userStorageId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - UserStoragePreference result = regClient.getUserStoragePreference(userId, gatewayID, userStorageId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while reading user data storage preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while reading user data storage preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getUserStoragePreference(userId, gatewayID, userStorageId); } /** @@ -5723,64 +2237,23 @@ public UserStoragePreference getUserStoragePreference( @SecurityCheck public List getAllUserComputeResourcePreferences( AuthzToken authzToken, String userId, String gatewayID) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = - regClient.getAllUserComputeResourcePreferences(userId, gatewayID); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while reading User compute resource preferences...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while reading User compute resource preferences. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllUserComputeResourcePreferences(userId, gatewayID); } @Override @SecurityCheck public List getAllUserStoragePreferences( AuthzToken authzToken, String userId, String gatewayID) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getAllUserStoragePreferences(userId, gatewayID); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while reading User data storage preferences...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while reading User data storage preferences. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllUserStoragePreferences(userId, gatewayID); } @Override @SecurityCheck public List getAllUserResourceProfiles(AuthzToken authzToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getAllUserResourceProfiles(); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while reading retrieving all user resource profiles. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllUserResourceProfiles(); } /** @@ -5801,23 +2274,9 @@ public boolean updateUserComputeResourcePreference( String gatewayID, String userComputeResourceId, UserComputeResourcePreference userComputeResourcePreference) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.updateUserComputeResourcePreference( - userId, gatewayID, userComputeResourceId, userComputeResourcePreference); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while reading user compute resource preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while updating user compute resource preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateUserComputeResourcePreference( + userId, gatewayID, userComputeResourceId, userComputeResourcePreference); } @Override @@ -5828,22 +2287,8 @@ public boolean updateUserStoragePreference( String gatewayID, String userStorageId, UserStoragePreference dataStoragePreference) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = - regClient.updateUserStoragePreference(userId, gatewayID, userStorageId, dataStoragePreference); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while reading user data storage preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating user data storage preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.updateUserStoragePreference(userId, gatewayID, userStorageId, dataStoragePreference); } /** @@ -5859,169 +2304,63 @@ public boolean updateUserStoragePreference( @SecurityCheck public boolean deleteUserComputeResourcePreference( AuthzToken authzToken, String userId, String gatewayID, String userComputeResourceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteUserComputeResourcePreference(userId, gatewayID, userComputeResourceId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while reading user compute resource preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while updating user compute resource preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteUserComputeResourcePreference(userId, gatewayID, userComputeResourceId); } @Override @SecurityCheck public boolean deleteUserStoragePreference( AuthzToken authzToken, String userId, String gatewayID, String userStorageId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - boolean result = regClient.deleteUserStoragePreference(userId, gatewayID, userStorageId); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - logger.error(userId, "Error while reading user data storage preference...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating user data storage preference. More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.deleteUserStoragePreference(userId, gatewayID, userStorageId); } @Override @SecurityCheck public List getLatestQueueStatuses(AuthzToken authzToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getLatestQueueStatuses(); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String msg = "Error in retrieving queue statuses"; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getLatestQueueStatuses(); } /** * ReplicaCatalog Related Methods * @return - * @throws TException * @throws ApplicationSettingsException */ @Override @SecurityCheck public String registerDataProduct(AuthzToken authzToken, DataProductModel dataProductModel) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.registerDataProduct(dataProductModel); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String msg = "Error in registering the data resource" + dataProductModel.getProductName() + "."; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.registerDataProduct(dataProductModel); } @Override @SecurityCheck public DataProductModel getDataProduct(AuthzToken authzToken, String productUri) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - DataProductModel result = regClient.getDataProduct(productUri); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String msg = "Error in retreiving the data product " + productUri + "."; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getDataProduct(productUri); } @Override @SecurityCheck public String registerReplicaLocation(AuthzToken authzToken, DataReplicaLocationModel replicaLocationModel) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String result = regClient.registerReplicaLocation(replicaLocationModel); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String msg = "Error in retreiving the replica " + replicaLocationModel.getReplicaName() + "."; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.registerReplicaLocation(replicaLocationModel); } @Override @SecurityCheck public DataProductModel getParentDataProduct(AuthzToken authzToken, String productUri) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - DataProductModel result = regClient.getParentDataProduct(productUri); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String msg = "Error in retreiving the parent data product for " + productUri + "."; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getParentDataProduct(productUri); } @Override @SecurityCheck public List getChildDataProducts(AuthzToken authzToken, String productUri) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List result = regClient.getChildDataProducts(productUri); - registryClientPool.returnResource(regClient); - return result; - } catch (Exception e) { - String msg = "Error in retreiving the child products for " + productUri + "."; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getChildDataProducts(productUri); } /** @@ -6035,1621 +2374,251 @@ public List getChildDataProducts(AuthzToken authzToken, String @SecurityCheck public boolean shareResourceWithUsers( AuthzToken authzToken, String resourceId, Map userPermissionList) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (!userHasAccessInternal(sharingClient, authzToken, resourceId, ResourcePermissionType.OWNER) - && !userHasAccessInternal( - sharingClient, authzToken, resourceId, ResourcePermissionType.MANAGE_SHARING)) { - throw new AuthorizationException( - "User is not allowed to change sharing because the user is either not the resource owner or does not have access to share the resource"); - } - for (Map.Entry userPermission : userPermissionList.entrySet()) { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - if (userPermission.getValue().equals(ResourcePermissionType.WRITE)) - sharingClient.shareEntityWithUsers( - gatewayId, - resourceId, - Arrays.asList(userPermission.getKey()), - authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "WRITE", - true); - else if (userPermission.getValue().equals(ResourcePermissionType.READ)) - sharingClient.shareEntityWithUsers( - gatewayId, - resourceId, - Arrays.asList(userPermission.getKey()), - authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "READ", - true); - else if (userPermission.getValue().equals(ResourcePermissionType.MANAGE_SHARING)) { - if (userHasAccessInternal(sharingClient, authzToken, resourceId, ResourcePermissionType.OWNER)) { - createManageSharingPermissionTypeIfMissing(sharingClient, gatewayId); - sharingClient.shareEntityWithUsers( - gatewayId, - resourceId, - Arrays.asList(userPermission.getKey()), - authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "MANAGE_SHARING", - true); - } else - throw new AuthorizationException( - "User is not allowed to grant sharing permission because the user is not the resource owner."); - } else { - logger.error("Invalid ResourcePermissionType : " - + userPermission.getValue().toString()); - throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION); - } - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return true; - } catch (Exception e) { - String msg = "Error in sharing resource with users. Resource ID : " + resourceId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - sharingClientPool.returnBrokenResource(sharingClient); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.shareResourceWithUsers(authzToken, resourceId, userPermissionList); } @Override @SecurityCheck public boolean shareResourceWithGroups( AuthzToken authzToken, String resourceId, Map groupPermissionList) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (!userHasAccessInternal(sharingClient, authzToken, resourceId, ResourcePermissionType.OWNER) - && !userHasAccessInternal( - sharingClient, authzToken, resourceId, ResourcePermissionType.MANAGE_SHARING)) { - throw new AuthorizationException( - "User is not allowed to change sharing because the user is either not the resource owner or does not have access to share the resource"); - } - for (Map.Entry groupPermission : groupPermissionList.entrySet()) { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - if (groupPermission.getValue().equals(ResourcePermissionType.WRITE)) - sharingClient.shareEntityWithGroups( - gatewayId, - resourceId, - Arrays.asList(groupPermission.getKey()), - authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "WRITE", - true); - else if (groupPermission.getValue().equals(ResourcePermissionType.READ)) - sharingClient.shareEntityWithGroups( - gatewayId, - resourceId, - Arrays.asList(groupPermission.getKey()), - authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "READ", - true); - else if (groupPermission.getValue().equals(ResourcePermissionType.MANAGE_SHARING)) { - if (userHasAccessInternal(sharingClient, authzToken, resourceId, ResourcePermissionType.OWNER)) { - createManageSharingPermissionTypeIfMissing(sharingClient, gatewayId); - sharingClient.shareEntityWithGroups( - gatewayId, - resourceId, - Arrays.asList(groupPermission.getKey()), - authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "MANAGE_SHARING", - true); - } else - throw new AuthorizationException( - "User is not allowed to grant sharing permission because the user is not the resource owner."); - } else { - logger.error("Invalid ResourcePermissionType : " - + groupPermission.getValue().toString()); - throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION); - } - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return true; - } catch (Exception e) { - String msg = "Error in sharing resource with groups. Resource ID : " + resourceId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - sharingClientPool.returnBrokenResource(sharingClient); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.shareResourceWithGroups(authzToken, resourceId, groupPermissionList); } @Override @SecurityCheck public boolean revokeSharingOfResourceFromUsers( AuthzToken authzToken, String resourceId, Map userPermissionList) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (!userHasAccessInternal(sharingClient, authzToken, resourceId, ResourcePermissionType.OWNER) - && !userHasAccessInternal( - sharingClient, authzToken, resourceId, ResourcePermissionType.MANAGE_SHARING)) { - throw new AuthorizationException( - "User is not allowed to change sharing because the user is either not the resource owner or does not have access to share the resource"); - } - for (Map.Entry userPermission : userPermissionList.entrySet()) { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - if (userPermission.getValue().equals(ResourcePermissionType.WRITE)) - sharingClient.revokeEntitySharingFromUsers( - gatewayId, - resourceId, - Arrays.asList(userPermission.getKey()), - authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "WRITE"); - else if (userPermission.getValue().equals(ResourcePermissionType.READ)) - sharingClient.revokeEntitySharingFromUsers( - gatewayId, - resourceId, - Arrays.asList(userPermission.getKey()), - authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "READ"); - else if (userPermission.getValue().equals(ResourcePermissionType.MANAGE_SHARING)) { - if (userHasAccessInternal(sharingClient, authzToken, resourceId, ResourcePermissionType.OWNER)) { - createManageSharingPermissionTypeIfMissing(sharingClient, gatewayId); - sharingClient.revokeEntitySharingFromUsers( - gatewayId, - resourceId, - Arrays.asList(userPermission.getKey()), - authzToken.getClaimsMap().get(Constants.GATEWAY_ID) + ":" + "MANAGE_SHARING"); - } else - throw new AuthorizationException( - "User is not allowed to change sharing permission because the user is not the resource owner."); - } else { - logger.error("Invalid ResourcePermissionType : " - + userPermission.getValue().toString()); - throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION); - } - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return true; - } catch (Exception e) { - String msg = "Error in revoking access to resource from users. Resource ID : " + resourceId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - sharingClientPool.returnBrokenResource(sharingClient); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.revokeSharingOfResourceFromUsers(authzToken, resourceId, userPermissionList); } @Override @SecurityCheck public boolean revokeSharingOfResourceFromGroups( AuthzToken authzToken, String resourceId, Map groupPermissionList) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - final String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - if (!userHasAccessInternal(sharingClient, authzToken, resourceId, ResourcePermissionType.OWNER) - && !userHasAccessInternal( - sharingClient, authzToken, resourceId, ResourcePermissionType.MANAGE_SHARING)) { - throw new AuthorizationException( - "User is not allowed to change sharing because the user is either not the resource owner or does not have access to share the resource"); - } - // For certain resource types, restrict them from being unshared with admin groups - ResourceType resourceType = getResourceType(sharingClient, gatewayId, resourceId); - Set adminRestrictedResourceTypes = new HashSet<>(Arrays.asList( - ResourceType.EXPERIMENT, ResourceType.APPLICATION_DEPLOYMENT, ResourceType.GROUP_RESOURCE_PROFILE)); - if (adminRestrictedResourceTypes.contains(resourceType)) { - // Prevent removing Admins WRITE/MANAGE_SHARING access and Read Only Admins READ access - GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId); - if (groupPermissionList.containsKey(gatewayGroups.getAdminsGroupId()) - && groupPermissionList - .get(gatewayGroups.getAdminsGroupId()) - .equals(ResourcePermissionType.WRITE)) { - throw new Exception("Not allowed to remove Admins group's WRITE access."); - } - if (groupPermissionList.containsKey(gatewayGroups.getReadOnlyAdminsGroupId()) - && groupPermissionList - .get(gatewayGroups.getReadOnlyAdminsGroupId()) - .equals(ResourcePermissionType.READ)) { - throw new Exception("Not allowed to remove Read Only Admins group's READ access."); - } - if (groupPermissionList.containsKey(gatewayGroups.getAdminsGroupId()) - && groupPermissionList - .get(gatewayGroups.getAdminsGroupId()) - .equals(ResourcePermissionType.READ)) { - throw new Exception("Not allowed to remove Admins group's READ access."); - } - if (groupPermissionList.containsKey(gatewayGroups.getAdminsGroupId()) - && groupPermissionList - .get(gatewayGroups.getAdminsGroupId()) - .equals(ResourcePermissionType.MANAGE_SHARING)) { - throw new Exception("Not allowed to remove Admins group's MANAGE_SHARING access."); - } - } - for (Map.Entry groupPermission : groupPermissionList.entrySet()) { - if (groupPermission.getValue().equals(ResourcePermissionType.WRITE)) - sharingClient.revokeEntitySharingFromUsers( - gatewayId, resourceId, Arrays.asList(groupPermission.getKey()), gatewayId + ":" + "WRITE"); - else if (groupPermission.getValue().equals(ResourcePermissionType.READ)) - sharingClient.revokeEntitySharingFromUsers( - gatewayId, resourceId, Arrays.asList(groupPermission.getKey()), gatewayId + ":" + "READ"); - else if (groupPermission.getValue().equals(ResourcePermissionType.MANAGE_SHARING)) { - if (userHasAccessInternal(sharingClient, authzToken, resourceId, ResourcePermissionType.OWNER)) { - createManageSharingPermissionTypeIfMissing(sharingClient, gatewayId); - sharingClient.revokeEntitySharingFromUsers( - gatewayId, - resourceId, - Arrays.asList(groupPermission.getKey()), - gatewayId + ":" + "MANAGE_SHARING"); - } else - throw new AuthorizationException( - "User is not allowed to change sharing because the user is not the resource owner"); - } else { - logger.error("Invalid ResourcePermissionType : " - + groupPermission.getValue().toString()); - throw new AiravataClientException(AiravataErrorType.UNSUPPORTED_OPERATION); - } - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return true; - } catch (Exception e) { - String msg = "Error in revoking access to resource from groups. Resource ID : " + resourceId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - sharingClientPool.returnBrokenResource(sharingClient); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.revokeSharingOfResourceFromGroups(authzToken, resourceId, groupPermissionList); } @Override @SecurityCheck public List getAllAccessibleUsers( AuthzToken authzToken, String resourceId, ResourcePermissionType permissionType) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - return getAllAccessibleUsersInternal(authzToken, resourceId, permissionType, (c, t) -> { - try { - return c.getListOfSharedUsers(gatewayId, resourceId, gatewayId + ":" + t.name()); - } catch (TException e) { - throw new RuntimeException(e); - } - }); + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllAccessibleUsers(authzToken, resourceId, permissionType, false); } @Override @SecurityCheck public List getAllDirectlyAccessibleUsers( AuthzToken authzToken, String resourceId, ResourcePermissionType permissionType) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - return getAllAccessibleUsersInternal(authzToken, resourceId, permissionType, (c, t) -> { - try { - return c.getListOfDirectlySharedUsers(gatewayId, resourceId, gatewayId + ":" + t.name()); - } catch (TException e) { - throw new RuntimeException(e); - } - }); - } - - private List getAllAccessibleUsersInternal( - AuthzToken authzToken, - String resourceId, - ResourcePermissionType permissionType, - BiFunction> userListFunction) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - HashSet accessibleUsers = new HashSet<>(); - if (permissionType.equals(ResourcePermissionType.WRITE)) { - userListFunction.apply(sharingClient, ResourcePermissionType.WRITE).stream() - .forEach(u -> accessibleUsers.add(u.getUserId())); - userListFunction.apply(sharingClient, ResourcePermissionType.OWNER).stream() - .forEach(u -> accessibleUsers.add(u.getUserId())); - } else if (permissionType.equals(ResourcePermissionType.READ)) { - userListFunction.apply(sharingClient, ResourcePermissionType.READ).stream() - .forEach(u -> accessibleUsers.add(u.getUserId())); - userListFunction.apply(sharingClient, ResourcePermissionType.OWNER).stream() - .forEach(u -> accessibleUsers.add(u.getUserId())); - } else if (permissionType.equals(ResourcePermissionType.OWNER)) { - userListFunction.apply(sharingClient, ResourcePermissionType.OWNER).stream() - .forEach(u -> accessibleUsers.add(u.getUserId())); - } else if (permissionType.equals(ResourcePermissionType.MANAGE_SHARING)) { - userListFunction.apply(sharingClient, ResourcePermissionType.MANAGE_SHARING).stream() - .forEach(u -> accessibleUsers.add(u.getUserId())); - userListFunction.apply(sharingClient, ResourcePermissionType.OWNER).stream() - .forEach(u -> accessibleUsers.add(u.getUserId())); - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return new ArrayList<>(accessibleUsers); - } catch (Exception e) { - String msg = "Error in getting all accessible users for resource. Resource ID : " + resourceId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - sharingClientPool.returnBrokenResource(sharingClient); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllAccessibleUsers(authzToken, resourceId, permissionType, true); } @Override @SecurityCheck public List getAllAccessibleGroups( AuthzToken authzToken, String resourceId, ResourcePermissionType permissionType) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - return getAllAccessibleGroupsInternal(authzToken, resourceId, permissionType, (c, t) -> { - try { - return c.getListOfSharedGroups(gatewayId, resourceId, gatewayId + ":" + t.name()); - } catch (TException e) { - throw new RuntimeException(e); - } - }); + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllAccessibleGroups(authzToken, resourceId, permissionType, false); } @Override @SecurityCheck public List getAllDirectlyAccessibleGroups( AuthzToken authzToken, String resourceId, ResourcePermissionType permissionType) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - return getAllAccessibleGroupsInternal(authzToken, resourceId, permissionType, (c, t) -> { - try { - return c.getListOfDirectlySharedGroups(gatewayId, resourceId, gatewayId + ":" + t.name()); - } catch (TException e) { - throw new RuntimeException(e); - } - }); - } - - private List getAllAccessibleGroupsInternal( - AuthzToken authzToken, - String resourceId, - ResourcePermissionType permissionType, - BiFunction> groupListFunction) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - HashSet accessibleGroups = new HashSet<>(); - if (permissionType.equals(ResourcePermissionType.WRITE)) { - groupListFunction.apply(sharingClient, ResourcePermissionType.WRITE).stream() - .forEach(g -> accessibleGroups.add(g.getGroupId())); - } else if (permissionType.equals(ResourcePermissionType.READ)) { - groupListFunction.apply(sharingClient, ResourcePermissionType.READ).stream() - .forEach(g -> accessibleGroups.add(g.getGroupId())); - } else if (permissionType.equals(ResourcePermissionType.MANAGE_SHARING)) { - groupListFunction.apply(sharingClient, ResourcePermissionType.MANAGE_SHARING).stream() - .forEach(g -> accessibleGroups.add(g.getGroupId())); - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return new ArrayList<>(accessibleGroups); - } catch (Exception e) { - String msg = "Error in getting all accessible groups for resource. Resource ID : " + resourceId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - sharingClientPool.returnBrokenResource(sharingClient); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getAllAccessibleGroups(authzToken, resourceId, permissionType, true); } @Override @SecurityCheck public boolean userHasAccess(AuthzToken authzToken, String resourceId, ResourcePermissionType permissionType) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - final String domainId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - final String userId = authzToken.getClaimsMap().get(Constants.USER_NAME) + "@" + domainId; - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - final boolean hasAccess = userHasAccessInternal(sharingClient, authzToken, resourceId, permissionType); - sharingClientPool.returnResource(sharingClient); - return hasAccess; - } catch (Exception e) { - String msg = "Error in if user can access resource. User ID : " + userId + ", Resource ID : " + resourceId - + ", Resource Permission Type : " + permissionType.toString(); - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.userHasAccess(authzToken, resourceId, permissionType); } @Override @SecurityCheck public String createGroupResourceProfile(AuthzToken authzToken, GroupResourceProfile groupResourceProfile) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - // TODO: verify that gatewayId in groupResourceProfile matches authzToken gatewayId - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - try { - validateGroupResourceProfile(sharingClient, authzToken, groupResourceProfile); - String groupResourceProfileId = regClient.createGroupResourceProfile(groupResourceProfile); - if (ServerSettings.isEnableSharing()) { - try { - Entity entity = new Entity(); - entity.setEntityId(groupResourceProfileId); - final String domainId = groupResourceProfile.getGatewayId(); - entity.setDomainId(groupResourceProfile.getGatewayId()); - entity.setEntityTypeId(groupResourceProfile.getGatewayId() + ":" + "GROUP_RESOURCE_PROFILE"); - entity.setOwnerId(userName + "@" + groupResourceProfile.getGatewayId()); - entity.setName(groupResourceProfile.getGroupResourceProfileName()); - - sharingClient.createEntity(entity); - - shareEntityWithAdminGatewayGroups(regClient, sharingClient, entity); - } catch (Exception ex) { - logger.error(ex.getMessage(), ex); - logger.error("Rolling back group resource profile creation Group Resource Profile ID : " - + groupResourceProfileId); - regClient.removeGroupResourceProfile(groupResourceProfileId); - AiravataSystemException ase = new AiravataSystemException(); - ase.setMessage("Failed to create sharing registry record"); - throw ase; - } - } - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return groupResourceProfileId; - } catch (AuthorizationException ae) { - logger.info("User " + userName - + " not allowed access to resources referenced in this GroupResourceProfile. Reason: " - + ae.getMessage()); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - throw ae; - } catch (Exception e) { - String msg = "Error creating group resource profile."; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } - } - - private void validateGroupResourceProfile( - SharingRegistryService.Client sharingClient, - AuthzToken authzToken, - GroupResourceProfile groupResourceProfile) - throws AuthorizationException { - Set tokenIds = new HashSet<>(); - if (groupResourceProfile.getComputePreferences() != null) { - for (GroupComputeResourcePreference groupComputeResourcePreference : - groupResourceProfile.getComputePreferences()) { - if (groupComputeResourcePreference.getResourceSpecificCredentialStoreToken() != null) { - tokenIds.add(groupComputeResourcePreference.getResourceSpecificCredentialStoreToken()); - } - } - } - if (groupResourceProfile.getDefaultCredentialStoreToken() != null) { - tokenIds.add(groupResourceProfile.getDefaultCredentialStoreToken()); - } - for (String tokenId : tokenIds) { - if (!userHasAccessInternal(sharingClient, authzToken, tokenId, ResourcePermissionType.READ)) { - throw new AuthorizationException( - "User does not have READ permission to credential token " + tokenId + "."); - } - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.createGroupResourceProfile(authzToken, groupResourceProfile); } @Override @SecurityCheck public void updateGroupResourceProfile(AuthzToken authzToken, GroupResourceProfile groupResourceProfile) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - validateGroupResourceProfile(sharingClient, authzToken, groupResourceProfile); - if (!userHasAccessInternal( - sharingClient, - authzToken, - groupResourceProfile.getGroupResourceProfileId(), - ResourcePermissionType.WRITE)) { - throw new AuthorizationException("User does not have permission to update group resource profile"); - } - regClient.updateGroupResourceProfile(groupResourceProfile); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - } catch (AuthorizationException ae) { - String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - logger.info("User " + userName + " not allowed access to update GroupResourceProfile " - + groupResourceProfile.getGroupResourceProfileId() + ", reason: " + ae.getMessage()); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - throw ae; - } catch (Exception e) { - String msg = "Error updating group resource profile. groupResourceProfileId: " - + groupResourceProfile.getGroupResourceProfileId(); - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + airavataService.updateGroupResourceProfile(authzToken, groupResourceProfile); } @Override @SecurityCheck public GroupResourceProfile getGroupResourceProfile(AuthzToken authzToken, String groupResourceProfileId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":READ")) { - throw new AuthorizationException( - "User does not have permission to access group resource profile"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access group resource profile"); - } - } - GroupResourceProfile groupResourceProfile = regClient.getGroupResourceProfile(groupResourceProfileId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return groupResourceProfile; - } catch (AuthorizationException checkedException) { - logger.error( - "Error while retrieving group resource profile. groupResourceProfileId: " + groupResourceProfileId, - checkedException); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - throw checkedException; - } catch (Exception e) { - String msg = "Error retrieving group resource profile. groupResourceProfileId: " + groupResourceProfileId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getGroupResourceProfile(authzToken, groupResourceProfileId); } @Override @SecurityCheck public boolean removeGroupResourceProfile(AuthzToken authzToken, String groupResourceProfileId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - if (ServerSettings.isEnableSharing()) { - try { - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":WRITE")) { - throw new AuthorizationException( - "User does not have permission to remove group resource profile"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to remove group resource profile"); - } - } - boolean result = regClient.removeGroupResourceProfile(groupResourceProfileId); - sharingClient.deleteEntity(gatewayId, groupResourceProfileId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - String msg = "Error removing group resource profile. groupResourceProfileId: " + groupResourceProfileId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.removeGroupResourceProfile(authzToken, groupResourceProfileId); } @Override @SecurityCheck public List getGroupResourceList(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); - try { - List accessibleGroupResProfileIds = new ArrayList<>(); - if (ServerSettings.isEnableSharing()) { - List filters = new ArrayList<>(); - SearchCriteria searchCriteria = new SearchCriteria(); - searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); - searchCriteria.setSearchCondition(SearchCondition.EQUAL); - searchCriteria.setValue(gatewayId + ":" + ResourceType.GROUP_RESOURCE_PROFILE.name()); - filters.add(searchCriteria); - sharingClient - .searchEntities( - authzToken.getClaimsMap().get(Constants.GATEWAY_ID), - userName + "@" + gatewayId, - filters, - 0, - -1) - .stream() - .forEach(p -> accessibleGroupResProfileIds.add(p.getEntityId())); - } - List groupResourceProfileList = - regClient.getGroupResourceList(gatewayId, accessibleGroupResProfileIds); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return groupResourceProfileList; - } catch (Exception e) { - String msg = "Error retrieving list group resource profile list. GatewayId: " + gatewayId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - sharingClientPool.returnBrokenResource(sharingClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getGroupResourceList(authzToken, gatewayId); } @Override @SecurityCheck public boolean removeGroupComputePrefs( AuthzToken authzToken, String computeResourceId, String groupResourceProfileId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":WRITE")) { - throw new AuthorizationException( - "User does not have permission to remove group compute preferences"); - } - } catch (Exception e) { - throw new AuthorizationException( - "User does not have permission to remove group compute preferences"); - } - } - boolean result = regClient.removeGroupComputePrefs(computeResourceId, groupResourceProfileId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - String msg = "Error removing group compute resource preferences. GroupResourceProfileId: " - + groupResourceProfileId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.removeGroupComputePrefs(authzToken, computeResourceId, groupResourceProfileId); } @Override @SecurityCheck public boolean removeGroupComputeResourcePolicy(AuthzToken authzToken, String resourcePolicyId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - try { - ComputeResourcePolicy computeResourcePolicy = - regClient.getGroupComputeResourcePolicy(resourcePolicyId); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, - userId + "@" + gatewayId, - computeResourcePolicy.getGroupResourceProfileId(), - gatewayId + ":WRITE")) { - throw new AuthorizationException( - "User does not have permission to remove group compute resource policy"); - } - } catch (Exception e) { - throw new AuthorizationException( - "User does not have permission to remove group compute resource policy"); - } - } - boolean result = regClient.removeGroupComputeResourcePolicy(resourcePolicyId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - String msg = "Error removing group compute resource policy. ResourcePolicyId: " + resourcePolicyId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.removeGroupComputeResourcePolicy(authzToken, resourcePolicyId); } @Override @SecurityCheck public boolean removeGroupBatchQueueResourcePolicy(AuthzToken authzToken, String resourcePolicyId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - try { - BatchQueueResourcePolicy batchQueueResourcePolicy = - regClient.getBatchQueueResourcePolicy(resourcePolicyId); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, - userId + "@" + gatewayId, - batchQueueResourcePolicy.getGroupResourceProfileId(), - gatewayId + ":WRITE")) { - throw new AuthorizationException( - "User does not have permission to remove batch queue resource policy"); - } - } catch (Exception e) { - throw new AuthorizationException( - "User does not have permission to remove batch queue resource policy"); - } - } - boolean result = regClient.removeGroupBatchQueueResourcePolicy(resourcePolicyId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return result; - } catch (Exception e) { - String msg = "Error removing batch queue resource policy. ResourcePolicyId: " + resourcePolicyId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.removeGroupBatchQueueResourcePolicy(authzToken, resourcePolicyId); } @Override @SecurityCheck public GroupComputeResourcePreference getGroupComputeResourcePreference( AuthzToken authzToken, String computeResourceId, String groupResourceProfileId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":READ")) { - throw new AuthorizationException( - "User does not have permission to access group resource profile"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access group resource profile"); - } - } - GroupComputeResourcePreference groupComputeResourcePreference = - regClient.getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return groupComputeResourcePreference; - } catch (Exception e) { - String msg = "Error retrieving Group compute preference. GroupResourceProfileId: " + groupResourceProfileId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getGroupComputeResourcePreference(authzToken, computeResourceId, groupResourceProfileId); } @Override @SecurityCheck public ComputeResourcePolicy getGroupComputeResourcePolicy(AuthzToken authzToken, String resourcePolicyId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - try { - ComputeResourcePolicy computeResourcePolicy = - regClient.getGroupComputeResourcePolicy(resourcePolicyId); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, - userId + "@" + gatewayId, - computeResourcePolicy.getGroupResourceProfileId(), - gatewayId + ":READ")) { - throw new AuthorizationException( - "User does not have permission to access group resource profile"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access group resource profile"); - } - } - - ComputeResourcePolicy computeResourcePolicy = regClient.getGroupComputeResourcePolicy(resourcePolicyId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return computeResourcePolicy; - } catch (Exception e) { - String msg = "Error retrieving Group compute resource policy. ResourcePolicyId: " + resourcePolicyId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getGroupComputeResourcePolicy(authzToken, resourcePolicyId); } @Override @SecurityCheck public BatchQueueResourcePolicy getBatchQueueResourcePolicy(AuthzToken authzToken, String resourcePolicyId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - try { - BatchQueueResourcePolicy batchQueueResourcePolicy = - regClient.getBatchQueueResourcePolicy(resourcePolicyId); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, - userId + "@" + gatewayId, - batchQueueResourcePolicy.getGroupResourceProfileId(), - gatewayId + ":READ")) { - throw new AuthorizationException( - "User does not have permission to access group resource profile"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access group resource profile"); - } - } - BatchQueueResourcePolicy batchQueueResourcePolicy = regClient.getBatchQueueResourcePolicy(resourcePolicyId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return batchQueueResourcePolicy; - } catch (Exception e) { - String msg = "Error retrieving Group batch queue resource policy. ResourcePolicyId: " + resourcePolicyId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getBatchQueueResourcePolicy(authzToken, resourcePolicyId); } @Override @SecurityCheck public List getGroupComputeResourcePrefList( AuthzToken authzToken, String groupResourceProfileId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":READ")) { - throw new AuthorizationException( - "User does not have permission to access group resource profile"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access group resource profile"); - } - } - List groupComputeResourcePreferenceList = - regClient.getGroupComputeResourcePrefList(groupResourceProfileId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return groupComputeResourcePreferenceList; - } catch (Exception e) { - String msg = "Error retrieving Group compute resource preference. GroupResourceProfileId: " - + groupResourceProfileId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getGroupComputeResourcePrefList(authzToken, groupResourceProfileId); } @Override @SecurityCheck public List getGroupBatchQueueResourcePolicyList( AuthzToken authzToken, String groupResourceProfileId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":READ")) { - throw new AuthorizationException( - "User does not have permission to access group resource profile"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access group resource profile"); - } - } - List batchQueueResourcePolicyList = - regClient.getGroupBatchQueueResourcePolicyList(groupResourceProfileId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return batchQueueResourcePolicyList; - } catch (Exception e) { - String msg = "Error retrieving Group batch queue resource policy list. GroupResourceProfileId: " - + groupResourceProfileId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getGroupBatchQueueResourcePolicyList(authzToken, groupResourceProfileId); } @Override @SecurityCheck public List getGroupComputeResourcePolicyList( AuthzToken authzToken, String groupResourceProfileId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - SharingRegistryService.Client sharingClient = sharingClientPool.getResource(); - try { - if (ServerSettings.isEnableSharing()) { - try { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - String userId = authzToken.getClaimsMap().get(Constants.USER_NAME); - if (!sharingClient.userHasAccess( - gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":READ")) { - throw new AuthorizationException( - "User does not have permission to access group resource profile"); - } - } catch (Exception e) { - throw new AuthorizationException("User does not have permission to access group resource profile"); - } - } - List computeResourcePolicyList = - regClient.getGroupComputeResourcePolicyList(groupResourceProfileId); - registryClientPool.returnResource(regClient); - sharingClientPool.returnResource(sharingClient); - return computeResourcePolicyList; - } catch (Exception e) { - String msg = "Error retrieving Group compute resource policy list. GroupResourceProfileId: " - + groupResourceProfileId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getGroupComputeResourcePolicyList(authzToken, groupResourceProfileId); } @Override @SecurityCheck public GatewayGroups getGatewayGroups(AuthzToken authzToken) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - - RegistryService.Client regClient = registryClientPool.getResource(); - try { - GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, gatewayId); - registryClientPool.returnResource(regClient); - return gatewayGroups; - } catch (Exception e) { - String msg = "Error retrieving GatewayGroups for gateway: " + gatewayId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + return airavataService.retrieveGatewayGroups(gatewayId); } @Override @SecurityCheck public Parser getParser(AuthzToken authzToken, String parserId, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - Parser parser = regClient.getParser(parserId, gatewayId); - registryClientPool.returnResource(regClient); - return parser; - } catch (Exception e) { - String msg = "Error retrieving parser with id: " + parserId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getParser(parserId, gatewayId); } @Override @SecurityCheck public String saveParser(AuthzToken authzToken, Parser parser) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String parserId = regClient.saveParser(parser); - registryClientPool.returnResource(regClient); - return parserId; - } catch (Exception e) { - String msg = "Error while saving the parser"; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.saveParser(parser); } @Override @SecurityCheck public List listAllParsers(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List parsers = regClient.listAllParsers(gatewayId); - registryClientPool.returnResource(regClient); - return parsers; - } catch (Exception e) { - String msg = "Error while listing the parsers for gateway " + gatewayId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.listAllParsers(gatewayId); } @Override @SecurityCheck public boolean removeParser(AuthzToken authzToken, String parserId, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - regClient.removeParser(parserId, gatewayId); - registryClientPool.returnResource(regClient); - return true; - } catch (Exception e) { - String msg = "Error while removing the parser " + parserId + " in gateway " + gatewayId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws AiravataSystemException { + airavataService.removeParser(parserId, gatewayId); + return true; } @Override @SecurityCheck public ParsingTemplate getParsingTemplate(AuthzToken authzToken, String templateId, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - ParsingTemplate parsingTemplate = regClient.getParsingTemplate(templateId, gatewayId); - registryClientPool.returnResource(regClient); - return parsingTemplate; - } catch (Exception e) { - String msg = "Error retrieving parsing template with id: " + templateId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getParsingTemplate(templateId, gatewayId); } @Override @SecurityCheck public List getParsingTemplatesForExperiment( AuthzToken authzToken, String experimentId, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List parsingTemplates = - regClient.getParsingTemplatesForExperiment(experimentId, gatewayId); - registryClientPool.returnResource(regClient); - return parsingTemplates; - } catch (Exception e) { - String msg = "Error retrieving parsing templates for experiment: " + experimentId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.getParsingTemplatesForExperiment(experimentId, gatewayId); } @Override @SecurityCheck public String saveParsingTemplate(AuthzToken authzToken, ParsingTemplate parsingTemplate) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - String templateId = regClient.saveParsingTemplate(parsingTemplate); - registryClientPool.returnResource(regClient); - return templateId; - } catch (Exception e) { - String msg = "Error saving the parsing template"; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.saveParsingTemplate(parsingTemplate); } @Override @SecurityCheck public boolean removeParsingTemplate(AuthzToken authzToken, String templateId, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - regClient.removeParsingTemplate(templateId, gatewayId); - registryClientPool.returnResource(regClient); - return true; - } catch (Exception e) { - String msg = "Error while removing the parsing template " + templateId + " in gateway " + gatewayId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + airavataService.removeParsingTemplate(templateId, gatewayId); + return true; } @Override @SecurityCheck public List listAllParsingTemplates(AuthzToken authzToken, String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - List templates = regClient.listAllParsingTemplates(gatewayId); - registryClientPool.returnResource(regClient); - return templates; - } catch (Exception e) { - String msg = "Error while listing the parsing templates for gateway " + gatewayId; - logger.error(msg, e); - AiravataSystemException exception = new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage(msg + " More info : " + e.getMessage()); - registryClientPool.returnBrokenResource(regClient); - throw exception; - } - } - - private void submitExperiment(String gatewayId, String experimentId) throws AiravataException { - ExperimentSubmitEvent event = new ExperimentSubmitEvent(experimentId, gatewayId); - MessageContext messageContext = new MessageContext( - event, MessageType.EXPERIMENT, "LAUNCH.EXP-" + UUID.randomUUID().toString(), gatewayId); - messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); - experimentPublisher.publish(messageContext); - } - - private void submitCancelExperiment(String gatewayId, String experimentId) throws AiravataException { - ExperimentSubmitEvent event = new ExperimentSubmitEvent(experimentId, gatewayId); - MessageContext messageContext = new MessageContext( - event, - MessageType.EXPERIMENT_CANCEL, - "CANCEL.EXP-" + UUID.randomUUID().toString(), - gatewayId); - messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); - experimentPublisher.publish(messageContext); - } - - private void submitExperimentIntermediateOutputsEvent( - String gatewayId, String experimentId, List outputNames) throws AiravataException { - - ExperimentIntermediateOutputsEvent event = - new ExperimentIntermediateOutputsEvent(experimentId, gatewayId, outputNames); - MessageContext messageContext = new MessageContext( - event, - MessageType.INTERMEDIATE_OUTPUTS, - "INTERMEDIATE_OUTPUTS.EXP-" + UUID.randomUUID().toString(), - gatewayId); - messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); - experimentPublisher.publish(messageContext); - } - - private void shareEntityWithAdminGatewayGroups( - RegistryService.Client regClient, SharingRegistryService.Client sharingClient, Entity entity) - throws TException { - final String domainId = entity.getDomainId(); - GatewayGroups gatewayGroups = retrieveGatewayGroups(regClient, domainId); - createManageSharingPermissionTypeIfMissing(sharingClient, domainId); - sharingClient.shareEntityWithGroups( - domainId, - entity.getEntityId(), - Arrays.asList(gatewayGroups.getAdminsGroupId()), - domainId + ":MANAGE_SHARING", - true); - sharingClient.shareEntityWithGroups( - domainId, - entity.getEntityId(), - Arrays.asList(gatewayGroups.getAdminsGroupId()), - domainId + ":WRITE", - true); - sharingClient.shareEntityWithGroups( - domainId, - entity.getEntityId(), - Arrays.asList(gatewayGroups.getAdminsGroupId(), gatewayGroups.getReadOnlyAdminsGroupId()), - domainId + ":READ", - true); - } - - private boolean userHasAccessInternal( - SharingRegistryService.Client sharingClient, - AuthzToken authzToken, - String entityId, - ResourcePermissionType permissionType) { - final String domainId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - final String userId = authzToken.getClaimsMap().get(Constants.USER_NAME) + "@" + domainId; - try { - final boolean hasOwnerAccess = sharingClient.userHasAccess( - domainId, userId, entityId, domainId + ":" + ResourcePermissionType.OWNER); - boolean hasAccess = false; - if (permissionType.equals(ResourcePermissionType.WRITE)) { - hasAccess = hasOwnerAccess - || sharingClient.userHasAccess( - domainId, userId, entityId, domainId + ":" + ResourcePermissionType.WRITE); - } else if (permissionType.equals(ResourcePermissionType.READ)) { - hasAccess = hasOwnerAccess - || sharingClient.userHasAccess( - domainId, userId, entityId, domainId + ":" + ResourcePermissionType.READ); - } else if (permissionType.equals(ResourcePermissionType.MANAGE_SHARING)) { - hasAccess = hasOwnerAccess - || sharingClient.userHasAccess( - domainId, userId, entityId, domainId + ":" + ResourcePermissionType.MANAGE_SHARING); - } else if (permissionType.equals(ResourcePermissionType.OWNER)) { - hasAccess = hasOwnerAccess; - } - return hasAccess; - } catch (Exception e) { - throw new RuntimeException("Unable to check if user has access", e); - } - } - - private ResourceType getResourceType(SharingRegistryService.Client sharingClient, String domainId, String entityId) - throws TException { - Entity entity = sharingClient.getEntity(domainId, entityId); - for (ResourceType resourceType : ResourceType.values()) { - if (entity.getEntityTypeId().equals(domainId + ":" + resourceType.name())) { - return resourceType; - } - } - throw new RuntimeException("Unrecognized entity type id: " + entity.getEntityTypeId()); - } - - private void createManageSharingPermissionTypeIfMissing( - SharingRegistryService.Client sharingClient, String domainId) throws TException { - // AIRAVATA-3297 Some gateways were created without the MANAGE_SHARING permission, so add it if missing - String permissionTypeId = domainId + ":MANAGE_SHARING"; - if (!sharingClient.isPermissionExists(domainId, permissionTypeId)) { - PermissionType permissionType = new PermissionType(); - permissionType.setPermissionTypeId(permissionTypeId); - permissionType.setDomainId(domainId); - permissionType.setName("MANAGE_SHARING"); - permissionType.setDescription("Manage sharing permission type"); - sharingClient.createPermissionType(permissionType); - logger.info("Created MANAGE_SHARING permission type for domain " + domainId); - } - } - - private GatewayGroups retrieveGatewayGroups(RegistryService.Client regClient, String gatewayId) throws TException { - - if (regClient.isGatewayGroupsExists(gatewayId)) { - return regClient.getGatewayGroups(gatewayId); - } else { - return GatewayGroupsInitializer.initializeGatewayGroups(gatewayId); - } + throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException { + return airavataService.listAllParsingTemplates(gatewayId); } /** * To hold storage info context (login username, credential token, and adaptor) */ - private record StorageInfoContext(String loginUserName, String credentialToken, AgentAdaptor adaptor) {} - - /** - * Check if a gateway resource profile exists - */ - private boolean isGatewayResourceProfileExists(String gatewayId) throws TException { - RegistryService.Client regClient = registryClientPool.getResource(); - try { - try { - GatewayResourceProfile profile = regClient.getGatewayResourceProfile(gatewayId); - registryClientPool.returnResource(regClient); - return profile != null; - } catch (org.apache.thrift.TApplicationException e) { - logger.error("Gateway resource profile does not exist for gateway: {}", gatewayId, e); - registryClientPool.returnResource(regClient); - return false; - } - } catch (Exception e) { - registryClientPool.returnBrokenResource(regClient); - logger.error("Error while checking if gateway resource profile exists", e); - throw e; - } - } - - private AiravataClientException clientException(AiravataErrorType errorType, String parameter) { - AiravataClientException exception = new AiravataClientException(); - exception.setAiravataErrorType(errorType); - exception.setParameter(parameter); - return exception; - } - - /** - * Resolves compute resource storage info context (login username, credential token, and adaptor). - * Handles user preference → group preference fallback for both login and credentials. - */ - private StorageInfoContext resolveComputeStorageInfoContext( - AuthzToken authzToken, String gatewayId, String userId, String resourceId) - throws AgentException, TException { - String loginUserName = null; - boolean loginFromUserPref = false; - GroupComputeResourcePreference groupComputePref = null; - GroupResourceProfile groupResourceProfile = null; - - UserComputeResourcePreference userComputePref = null; - if (isUserResourceProfileExists(authzToken, userId, gatewayId)) { - userComputePref = getUserComputeResourcePreference(authzToken, userId, gatewayId, resourceId); - } else { - logger.debug( - "User resource profile does not exist for user {} in gateway {}, will try group preferences", - userId, - gatewayId); - } - - if (userComputePref != null - && userComputePref.getLoginUserName() != null - && !userComputePref.getLoginUserName().trim().isEmpty()) { - loginUserName = userComputePref.getLoginUserName(); - loginFromUserPref = true; - logger.debug("Using user preference login username: {}", loginUserName); - - } else { - // Fallback to GroupComputeResourcePreference - List groupResourceProfiles = getGroupResourceList(authzToken, gatewayId); - for (GroupResourceProfile groupProfile : groupResourceProfiles) { - List groupComputePrefs = groupProfile.getComputePreferences(); - - if (groupComputePrefs != null && !groupComputePrefs.isEmpty()) { - for (GroupComputeResourcePreference groupPref : groupComputePrefs) { - if (resourceId.equals(groupPref.getComputeResourceId()) - && groupPref.getLoginUserName() != null - && !groupPref.getLoginUserName().trim().isEmpty()) { - loginUserName = groupPref.getLoginUserName(); - groupComputePref = groupPref; - groupResourceProfile = groupProfile; - logger.debug( - "Using login username from group compute resource preference for resource {}", - resourceId); - break; - } - } - } - if (loginUserName != null) { - break; - } - } - if (loginUserName == null) { - logger.debug("No login username found for compute resource {}", resourceId); - throw new InvalidRequestException("No login username found for compute resource " + resourceId); - } - } - - // Resolve credential token based on where login came from - String credentialToken; - if (loginFromUserPref) { - // Login username came from user preference. Use user preference token → user profile token - if (userComputePref != null - && userComputePref.getResourceSpecificCredentialStoreToken() != null - && !userComputePref - .getResourceSpecificCredentialStoreToken() - .trim() - .isEmpty()) { - credentialToken = userComputePref.getResourceSpecificCredentialStoreToken(); - } else { - UserResourceProfile userResourceProfile = getUserResourceProfile(authzToken, userId, gatewayId); - if (userResourceProfile == null - || userResourceProfile.getCredentialStoreToken() == null - || userResourceProfile.getCredentialStoreToken().trim().isEmpty()) { - logger.error("No credential store token found for user {} in gateway {}", userId, gatewayId); - throw clientException( - AiravataErrorType.AUTHENTICATION_FAILURE, - "No credential store token found for user " + userId + " in gateway " + gatewayId); - } - credentialToken = userResourceProfile.getCredentialStoreToken(); - } - } else { - // Login username came from group preference. Use group preference token → group profile default token → - // user profile token (fallback) - if (groupComputePref != null - && groupComputePref.getResourceSpecificCredentialStoreToken() != null - && !groupComputePref - .getResourceSpecificCredentialStoreToken() - .trim() - .isEmpty()) { - credentialToken = groupComputePref.getResourceSpecificCredentialStoreToken(); - - } else if (groupResourceProfile != null - && groupResourceProfile.getDefaultCredentialStoreToken() != null - && !groupResourceProfile - .getDefaultCredentialStoreToken() - .trim() - .isEmpty()) { - credentialToken = groupResourceProfile.getDefaultCredentialStoreToken(); - - } else { - UserResourceProfile userResourceProfile = getUserResourceProfile(authzToken, userId, gatewayId); - if (userResourceProfile == null - || userResourceProfile.getCredentialStoreToken() == null - || userResourceProfile.getCredentialStoreToken().trim().isEmpty()) { - logger.error("No credential store token found for user {} in gateway {}", userId, gatewayId); - throw clientException( - AiravataErrorType.AUTHENTICATION_FAILURE, - "No credential store token found for compute resource " + resourceId); - } - credentialToken = userResourceProfile.getCredentialStoreToken(); - } - } - - AgentAdaptor adaptor = AdaptorSupportImpl.getInstance() - .fetchComputeSSHAdaptor(gatewayId, resourceId, credentialToken, userId, loginUserName); - logger.info("Resolved resource {} as compute resource to fetch storage details", resourceId); - - return new StorageInfoContext(loginUserName, credentialToken, adaptor); - } - - /** - * Resolves storage resource storage info context (login username, credential token, and adaptor). - * Handles user preference → gateway preference fallback for both login and credentials. - */ - private StorageInfoContext resolveStorageStorageInfoContext( - AuthzToken authzToken, String gatewayId, String userId, String resourceId) - throws AgentException, TException { - UserStoragePreference userStoragePref = null; - if (isUserResourceProfileExists(authzToken, userId, gatewayId)) { - userStoragePref = getUserStoragePreference(authzToken, userId, gatewayId, resourceId); - } else { - logger.debug( - "User resource profile does not exist for user {} in gateway {}, will try gateway preferences", - userId, - gatewayId); - } - - StoragePreference storagePref = null; - if (isGatewayResourceProfileExists(gatewayId)) { - storagePref = getGatewayStoragePreference(authzToken, gatewayId, resourceId); - } else { - logger.debug( - "Gateway resource profile does not exist for gateway {}, will check if user preference exists", - gatewayId); - } - - String loginUserName; - boolean loginFromUserPref; - - if (userStoragePref != null - && userStoragePref.getLoginUserName() != null - && !userStoragePref.getLoginUserName().trim().isEmpty()) { - loginUserName = userStoragePref.getLoginUserName(); - loginFromUserPref = true; - logger.debug("Using login username from user storage preference for resource {}", resourceId); - - } else if (storagePref != null - && storagePref.getLoginUserName() != null - && !storagePref.getLoginUserName().trim().isEmpty()) { - loginUserName = storagePref.getLoginUserName(); - loginFromUserPref = false; - logger.debug("Using login username from gateway storage preference for resource {}", resourceId); - - } else { - logger.error("No login username found for storage resource {}", resourceId); - throw new InvalidRequestException("No login username found for storage resource " + resourceId); - } - - // Resolve credential token based on where login came from - String credentialToken; - if (loginFromUserPref) { - // Login came from user preference. Use user preference token or user profile token - if (userStoragePref != null - && userStoragePref.getResourceSpecificCredentialStoreToken() != null - && !userStoragePref - .getResourceSpecificCredentialStoreToken() - .trim() - .isEmpty()) { - credentialToken = userStoragePref.getResourceSpecificCredentialStoreToken(); - logger.debug("Using login username from user preference for resource {}", resourceId); - - } else { - UserResourceProfile userResourceProfile = getUserResourceProfile(authzToken, userId, gatewayId); - if (userResourceProfile == null - || userResourceProfile.getCredentialStoreToken() == null - || userResourceProfile.getCredentialStoreToken().trim().isEmpty()) { - logger.error("No credential store token found for user {} in gateway {}", userId, gatewayId); - throw clientException( - AiravataErrorType.AUTHENTICATION_FAILURE, - "No credential store token found for user " + userId + " in gateway " + gatewayId); - } - credentialToken = userResourceProfile.getCredentialStoreToken(); - } - } else { - // Login came from gateway preference. Use gateway preference token or gateway profile token - if (storagePref != null - && storagePref.getResourceSpecificCredentialStoreToken() != null - && !storagePref - .getResourceSpecificCredentialStoreToken() - .trim() - .isEmpty()) { - credentialToken = storagePref.getResourceSpecificCredentialStoreToken(); - - } else { - GatewayResourceProfile gatewayResourceProfile = getGatewayResourceProfile(authzToken, gatewayId); - if (gatewayResourceProfile == null - || gatewayResourceProfile.getCredentialStoreToken() == null - || gatewayResourceProfile - .getCredentialStoreToken() - .trim() - .isEmpty()) { - logger.error("No credential store token found for gateway {}", gatewayId); - throw clientException( - AiravataErrorType.AUTHENTICATION_FAILURE, - "No credential store token found for gateway " + gatewayId); - } - credentialToken = gatewayResourceProfile.getCredentialStoreToken(); - } - } - - AgentAdaptor adaptor = AdaptorSupportImpl.getInstance() - .fetchStorageSSHAdaptor(gatewayId, resourceId, credentialToken, userId, loginUserName); - logger.info("Resolved resource {} as storage resource to fetch storage details", resourceId); - - return new StorageInfoContext(loginUserName, credentialToken, adaptor); - } } diff --git a/airavata-api/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServerHandler.java b/airavata-api/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServerHandler.java index 113d2f770e..a016cb9abb 100644 --- a/airavata-api/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServerHandler.java +++ b/airavata-api/src/main/java/org/apache/airavata/credential/store/server/CredentialStoreServerHandler.java @@ -19,562 +19,103 @@ */ package org.apache.airavata.credential.store.server; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.sql.SQLException; -import java.util.*; -import java.util.stream.Collectors; +import java.util.List; +import java.util.Map; import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.DBInitializer; -import org.apache.airavata.common.utils.DBUtil; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.credential.store.cpi.CredentialStoreService; import org.apache.airavata.credential.store.cpi.credential_store_cpiConstants; -import org.apache.airavata.credential.store.credential.CommunityUser; -import org.apache.airavata.credential.store.credential.Credential; -import org.apache.airavata.credential.store.credential.CredentialOwnerType; -import org.apache.airavata.credential.store.store.CredentialStoreException; -import org.apache.airavata.credential.store.store.impl.CertificateCredentialWriter; -import org.apache.airavata.credential.store.store.impl.CredentialReaderImpl; -import org.apache.airavata.credential.store.store.impl.SSHCredentialWriter; -import org.apache.airavata.credential.store.store.impl.util.CredentialStoreDBInitConfig; -import org.apache.airavata.credential.store.util.TokenGenerator; -import org.apache.airavata.credential.store.util.Utility; +import org.apache.airavata.credential.store.exception.CredentialStoreException; import org.apache.airavata.model.credential.store.*; -import org.apache.commons.codec.binary.Base64; -import org.apache.thrift.TException; +import org.apache.airavata.model.error.AiravataSystemException; +import org.apache.airavata.service.CredentialStoreService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -// import sun.security.provider.X509Factory; -public class CredentialStoreServerHandler implements CredentialStoreService.Iface { +public class CredentialStoreServerHandler + implements org.apache.airavata.credential.store.cpi.CredentialStoreService.Iface { protected static Logger log = LoggerFactory.getLogger(CredentialStoreServerHandler.class); - private DBUtil dbUtil; - private SSHCredentialWriter sshCredentialWriter; - private CertificateCredentialWriter certificateCredentialWriter; - private CredentialReaderImpl credentialReader; + private CredentialStoreService credentialStoreService; public CredentialStoreServerHandler() - throws ApplicationSettingsException, IllegalAccessException, ClassNotFoundException, InstantiationException, - SQLException, IOException { - String jdbcUrl = ServerSettings.getCredentialStoreDBURL(); - String userName = ServerSettings.getCredentialStoreDBUser(); - String password = ServerSettings.getCredentialStoreDBPassword(); - String driverName = ServerSettings.getCredentialStoreDBDriver(); - - log.debug("Starting credential store, connecting to database - " + jdbcUrl + " DB user - " + userName - + " driver name - " + driverName); - DBInitializer.initializeDB(new CredentialStoreDBInitConfig()); - - dbUtil = new DBUtil(jdbcUrl, userName, password, driverName); - sshCredentialWriter = new SSHCredentialWriter(dbUtil); - certificateCredentialWriter = new CertificateCredentialWriter(dbUtil); - credentialReader = new CredentialReaderImpl(dbUtil); + throws ApplicationSettingsException, IllegalAccessException, ClassNotFoundException, + InstantiationException { + credentialStoreService = new CredentialStoreService(); } @Override - public String getAPIVersion() throws TException { + public String getAPIVersion() throws AiravataSystemException { return credential_store_cpiConstants.CS_CPI_VERSION; } @Override - public String addSSHCredential(SSHCredential sshCredential) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - try { - org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential credential = - new org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential(); - credential.setGateway(sshCredential.getGatewayId()); - credential.setPortalUserName(sshCredential.getUsername()); - // only username and gateway id will be sent by client. - String token = TokenGenerator.generateToken(sshCredential.getGatewayId(), null); - credential.setToken(token); - credential.setPassphrase(String.valueOf(UUID.randomUUID())); - if (sshCredential.getPrivateKey() != null) { - credential.setPrivateKey(sshCredential.getPrivateKey().getBytes()); - } - if (sshCredential.getDescription() != null) { - credential.setDescription(sshCredential.getDescription()); - } - if (sshCredential.getPublicKey() != null) { - credential.setPublicKey(sshCredential.getPublicKey().getBytes()); - } - if (sshCredential.getPublicKey() == null || sshCredential.getPrivateKey() == null) { - credential = Utility.generateKeyPair(credential); - } - credential.setCredentialOwnerType(CredentialOwnerType.GATEWAY); - sshCredentialWriter.writeCredentials(credential); - return token; - } catch (CredentialStoreException e) { - log.error("Error occurred while saving SSH Credentials.", e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while saving SSH Credentials."); - } catch (Exception e) { - log.error("Error occurred while generating key pair.", e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while generating key pair.."); - } + public String addSSHCredential(SSHCredential sshCredential) throws CredentialStoreException { + return credentialStoreService.addSSHCredential(sshCredential); } @Override public String addCertificateCredential(CertificateCredential certificateCredential) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - try { - org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential credential = - new org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential(); - credential.setPortalUserName( - certificateCredential.getCommunityUser().getUsername()); - credential.setCommunityUser(new CommunityUser( - certificateCredential.getCommunityUser().getGatewayName(), - certificateCredential.getCommunityUser().getUsername(), - certificateCredential.getCommunityUser().getUserEmail())); - String token = TokenGenerator.generateToken( - certificateCredential.getCommunityUser().getGatewayName(), null); - credential.setToken(token); - Base64 encoder = new Base64(64); - byte[] decoded = encoder.decode(certificateCredential - .getX509Cert() - .replaceAll("-----BEGIN CERTIFICATE-----", "") - .replaceAll("-----END CERTIFICATE-----", "")); - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - X509Certificate certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(decoded)); - X509Certificate[] certificates = new X509Certificate[1]; - certificates[0] = certificate; - credential.setCertificates(certificates); - certificateCredentialWriter.writeCredentials(credential); - return token; - } catch (CredentialStoreException e) { - log.error("Error occurred while saving Certificate Credentials.", e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while saving Certificate Credentials."); - } catch (Exception e) { - log.error("Error occurred while converting to X509 certificate.", e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while converting to X509 certificate.."); - } + throws CredentialStoreException { + return credentialStoreService.addCertificateCredential(certificateCredential); } @Override - public String addPasswordCredential(PasswordCredential passwordCredential) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - try { - org.apache.airavata.credential.store.credential.impl.password.PasswordCredential credential = - new org.apache.airavata.credential.store.credential.impl.password.PasswordCredential(); - credential.setGateway(passwordCredential.getGatewayId()); - credential.setPortalUserName(passwordCredential.getPortalUserName()); - credential.setUserName(passwordCredential.getLoginUserName()); - credential.setPassword(passwordCredential.getPassword()); - credential.setDescription(passwordCredential.getDescription()); - String token = TokenGenerator.generateToken(passwordCredential.getGatewayId(), null); - credential.setToken(token); - sshCredentialWriter.writeCredentials(credential); - return token; - } catch (CredentialStoreException e) { - log.error("Error occurred while saving PWD Credentials.", e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while saving PWD Credentials."); - } catch (Exception e) { - log.error("Error occurred while registering PWD Credentials.", e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while registering PWD Credentials.."); - } + public String addPasswordCredential(PasswordCredential passwordCredential) throws CredentialStoreException { + return credentialStoreService.addPasswordCredential(passwordCredential); } @Override - public SSHCredential getSSHCredential(String tokenId, String gatewayId) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - try { - Credential credential = credentialReader.getCredential(gatewayId, tokenId); - if (credential instanceof org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential - && !(credential - instanceof - org.apache.airavata.credential.store.credential.impl.password.PasswordCredential)) { - org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential credential1 = - (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) credential; - SSHCredential sshCredential = new SSHCredential(); - sshCredential.setUsername(credential1.getPortalUserName()); - sshCredential.setGatewayId(credential1.getGateway()); - sshCredential.setPublicKey(new String(credential1.getPublicKey())); - sshCredential.setPrivateKey(new String(credential1.getPrivateKey())); - sshCredential.setPassphrase(credential1.getPassphrase()); - sshCredential.setToken(credential1.getToken()); - sshCredential.setPersistedTime( - credential1.getCertificateRequestedTime().getTime()); - sshCredential.setDescription(credential1.getDescription()); - return sshCredential; - } else { - log.info("Could not find SSH credentials for token - " + tokenId + " and " + "gateway id - " - + gatewayId); - return null; - } - } catch (CredentialStoreException e) { - log.error( - "Error occurred while retrieving SSH credentialfor token - " + tokenId + " and gateway id - " - + gatewayId, - e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while retrieving SSH credential for token - " + tokenId + " and gateway id - " - + gatewayId); - } + public SSHCredential getSSHCredential(String tokenId, String gatewayId) throws CredentialStoreException { + return credentialStoreService.getSSHCredential(tokenId, gatewayId); } @Override - public CredentialSummary getCredentialSummary(String tokenId, String gatewayId) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - try { - Credential credential = credentialReader.getCredential(gatewayId, tokenId); - if (isSSHCredential(credential)) { - return convertToCredentialSummary( - (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) credential); - } else if (isCertificateCredential(credential)) { - return convertToCredentialSummary( - (org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential) - credential); - } else if (isPasswordCredential(credential)) { - return convertToCredentialSummary( - (org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) credential); - } - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Unrecognized type of credential for token: " + tokenId); - } catch (CredentialStoreException e) { - final String msg = "Error occurred while retrieving credential summary for token - " + tokenId - + " and gateway id - " + gatewayId; - log.error(msg, e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException(msg); - } + public CredentialSummary getCredentialSummary(String tokenId, String gatewayId) throws CredentialStoreException { + return credentialStoreService.getCredentialSummary(tokenId, gatewayId); } @Override public List getAllCredentialSummaries( - SummaryType type, List accessibleTokenIds, String gatewayId) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - try { - List credentials = - credentialReader.getAllAccessibleCredentialsPerGateway(gatewayId, accessibleTokenIds); - if (type.equals(SummaryType.SSH)) { - return credentials.stream() - .filter(this::isSSHCredential) - .map(cred -> (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) cred) - .map(cred -> convertToCredentialSummary(cred)) - .collect(Collectors.toList()); - } else if (type.equals(SummaryType.CERT)) { - return credentials.stream() - .filter(this::isCertificateCredential) - .map(cred -> - (org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential) - cred) - .map(cred -> convertToCredentialSummary(cred)) - .collect(Collectors.toList()); - } else if (type.equals(SummaryType.PASSWD)) { - return credentials.stream() - .filter(this::isPasswordCredential) - .map(cred -> - (org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) cred) - .map(cred -> convertToCredentialSummary(cred)) - .collect(Collectors.toList()); - } else { - throw new RuntimeException("Summary Type " + type + " is not supported."); - } - } catch (CredentialStoreException e) { - final String msg = "Error occurred while retrieving " + type + " credential Summary for tokens - " - + accessibleTokenIds + " and gateway id - " + gatewayId; - log.error(msg, e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException(msg); - } - } - - private boolean isSSHCredential(Credential cred) { - return cred instanceof org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential - && !(cred instanceof org.apache.airavata.credential.store.credential.impl.password.PasswordCredential); - } - - private boolean isCertificateCredential(Credential cred) { - return cred instanceof org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential; - } - - private boolean isPasswordCredential(Credential cred) { - return cred instanceof org.apache.airavata.credential.store.credential.impl.password.PasswordCredential; - } - - private CredentialSummary convertToCredentialSummary( - org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential cred) { - CredentialSummary credentialSummary = new CredentialSummary(); - credentialSummary.setType(SummaryType.SSH); - credentialSummary.setUsername(cred.getPortalUserName()); - credentialSummary.setGatewayId(cred.getGateway()); - credentialSummary.setPublicKey(new String(cred.getPublicKey())); - credentialSummary.setToken(cred.getToken()); - credentialSummary.setPersistedTime(cred.getCertificateRequestedTime().getTime()); - credentialSummary.setDescription(cred.getDescription()); - return credentialSummary; - } - - private CredentialSummary convertToCredentialSummary( - org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential cred) { - CredentialSummary credentialSummary = new CredentialSummary(); - credentialSummary.setType(SummaryType.CERT); - credentialSummary.setUsername(cred.getPortalUserName()); - // FIXME: need to get gatewayId for CertificateCredentials - credentialSummary.setGatewayId(""); - // FIXME: get the public key? Or what would be appropriate for a summary of a CertificateCredential? - // credentialSummary.setPublicKey(new String(cred.getPublicKey())); - credentialSummary.setToken(cred.getToken()); - credentialSummary.setPersistedTime(cred.getCertificateRequestedTime().getTime()); - credentialSummary.setDescription(cred.getDescription()); - return credentialSummary; - } - - private CredentialSummary convertToCredentialSummary( - org.apache.airavata.credential.store.credential.impl.password.PasswordCredential cred) { - CredentialSummary credentialSummary = new CredentialSummary(); - credentialSummary.setType(SummaryType.PASSWD); - credentialSummary.setUsername(cred.getPortalUserName()); - credentialSummary.setGatewayId(cred.getGateway()); - credentialSummary.setToken(cred.getToken()); - credentialSummary.setPersistedTime(cred.getCertificateRequestedTime().getTime()); - credentialSummary.setDescription(cred.getDescription()); - return credentialSummary; + SummaryType type, List accessibleTokenIds, String gatewayId) throws CredentialStoreException { + return credentialStoreService.getAllCredentialSummaries(type, accessibleTokenIds, gatewayId); } @Override public CertificateCredential getCertificateCredential(String tokenId, String gatewayId) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - try { - Credential credential = credentialReader.getCredential(gatewayId, tokenId); - if (credential - instanceof org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential) { - org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential credential1 = - (org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential) - credential; - CertificateCredential certificateCredential = new CertificateCredential(); - org.apache.airavata.model.credential.store.CommunityUser communityUser = - new org.apache.airavata.model.credential.store.CommunityUser(); - communityUser.setGatewayName(credential1.getCommunityUser().getGatewayName()); - communityUser.setUsername(credential1.getCommunityUser().getUserName()); - communityUser.setUserEmail(credential1.getCommunityUser().getUserEmail()); - certificateCredential.setCommunityUser(communityUser); - certificateCredential.setToken(credential1.getToken()); - certificateCredential.setLifeTime(credential1.getLifeTime()); - certificateCredential.setNotAfter(credential1.getNotAfter()); - certificateCredential.setNotBefore(credential1.getNotBefore()); - certificateCredential.setPersistedTime( - credential1.getCertificateRequestedTime().getTime()); - if (credential1.getPrivateKey() != null) { - certificateCredential.setPrivateKey( - credential1.getPrivateKey().toString()); - } - certificateCredential.setX509Cert(credential1.getCertificates()[0].toString()); - return certificateCredential; - } else { - log.info("Could not find Certificate credentials for token - " + tokenId + " and " + "gateway id - " - + gatewayId); - return null; - } - } catch (CredentialStoreException e) { - log.error( - "Error occurred while retrieving Certificate credential for token - " + tokenId - + " and gateway id - " + gatewayId, - e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while retrieving Certificate credential for token - " + tokenId - + " and gateway id - " + gatewayId); - } + throws CredentialStoreException { + return credentialStoreService.getCertificateCredential(tokenId, gatewayId); } @Override - public PasswordCredential getPasswordCredential(String tokenId, String gatewayId) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - try { - Credential credential = credentialReader.getCredential(gatewayId, tokenId); - if (credential - instanceof org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) { - org.apache.airavata.credential.store.credential.impl.password.PasswordCredential credential1 = - (org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) credential; - PasswordCredential pwdCredential = new PasswordCredential(); - pwdCredential.setGatewayId(credential1.getGateway()); - pwdCredential.setPortalUserName(credential1.getPortalUserName()); - pwdCredential.setLoginUserName(credential1.getUserName()); - pwdCredential.setPassword(credential1.getPassword()); - pwdCredential.setDescription(credential1.getDescription()); - pwdCredential.setToken(credential1.getToken()); - pwdCredential.setPersistedTime( - credential1.getCertificateRequestedTime().getTime()); - return pwdCredential; - } else { - log.info("Could not find PWD credentials for token - " + tokenId + " and " + "gateway id - " - + gatewayId); - return null; - } - } catch (CredentialStoreException e) { - log.error( - "Error occurred while retrieving PWD credentialfor token - " + tokenId + " and gateway id - " - + gatewayId, - e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while retrieving PWD credential for token - " + tokenId + " and gateway id - " - + gatewayId); - } + public PasswordCredential getPasswordCredential(String tokenId, String gatewayId) throws CredentialStoreException { + return credentialStoreService.getPasswordCredential(tokenId, gatewayId); } @Override @Deprecated public List getAllCredentialSummaryForGateway(SummaryType type, String gatewayId) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - if (type.equals(SummaryType.SSH)) { - Map sshKeyMap = new HashMap<>(); - List summaryList = new ArrayList<>(); - try { - List allCredentials = credentialReader.getAllCredentialsPerGateway(gatewayId); - if (allCredentials != null && !allCredentials.isEmpty()) { - for (Credential credential : allCredentials) { - if (credential instanceof org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential - && !(credential - instanceof - org.apache.airavata.credential.store.credential.impl.password - .PasswordCredential) - && credential.getCredentialOwnerType() == CredentialOwnerType.GATEWAY) { - org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential sshCredential = - (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) credential; - CredentialSummary sshCredentialSummary = new CredentialSummary(); - sshCredentialSummary.setType(SummaryType.SSH); - sshCredentialSummary.setToken(sshCredential.getToken()); - sshCredentialSummary.setUsername(sshCredential.getPortalUserName()); - sshCredentialSummary.setGatewayId(sshCredential.getGateway()); - sshCredentialSummary.setDescription(sshCredential.getDescription()); - sshCredentialSummary.setPublicKey(new String(sshCredential.getPublicKey())); - summaryList.add(sshCredentialSummary); - } - } - } - } catch (CredentialStoreException e) { - log.error("Error occurred while retrieving credential Summary", e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while retrieving credential Summary"); - } - return summaryList; - } else { - log.info("Summay Type" + type.toString() + " not supported for gateway id - " + gatewayId); - return null; - } + throws CredentialStoreException { + return credentialStoreService.getAllCredentialSummaryForGateway(type, gatewayId); } @Override @Deprecated public List getAllCredentialSummaryForUserInGateway( - SummaryType type, String gatewayId, String userId) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - if (type.equals(SummaryType.SSH)) { - Map sshKeyMap = new HashMap<>(); - List summaryList = new ArrayList<>(); - try { - List allCredentials = credentialReader.getAllCredentials(); - if (allCredentials != null && !allCredentials.isEmpty()) { - for (Credential credential : allCredentials) { - if (credential instanceof org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential - && !(credential - instanceof - org.apache.airavata.credential.store.credential.impl.password - .PasswordCredential)) { - org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential sshCredential = - (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) credential; - String portalUserName = sshCredential.getPortalUserName(); - String gateway = sshCredential.getGateway(); - if (portalUserName != null && gateway != null) { - if (portalUserName.equals(userId) - && gateway.equals(gatewayId) - && sshCredential.getCredentialOwnerType() == CredentialOwnerType.USER) { - org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential - sshCredentialKey = - (org.apache.airavata.credential.store.credential.impl.ssh - .SSHCredential) - credential; - CredentialSummary sshCredentialSummary = new CredentialSummary(); - sshCredentialSummary.setType(SummaryType.SSH); - sshCredentialSummary.setToken(sshCredentialKey.getToken()); - sshCredentialSummary.setUsername(sshCredentialKey.getPortalUserName()); - sshCredentialSummary.setGatewayId(sshCredentialKey.getGateway()); - sshCredentialSummary.setDescription(sshCredentialKey.getDescription()); - sshCredentialSummary.setPublicKey(new String(sshCredentialKey.getPublicKey())); - summaryList.add(sshCredentialSummary); - } - } - } - } - } - } catch (CredentialStoreException e) { - log.error("Error occurred while retrieving credential Summary", e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while retrieving credential Summary"); - } - return summaryList; - } else { - log.info("Summay Type" + type.toString() + " not supported for user Id - " + userId + " and " - + "gateway id - " + gatewayId); - return null; - } + SummaryType type, String gatewayId, String userId) throws CredentialStoreException { + return credentialStoreService.getAllCredentialSummaryForUserInGateway(type, gatewayId, userId); } @Override @Deprecated - public Map getAllPWDCredentialsForGateway(String gatewayId) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - Map pwdCredMap = new HashMap<>(); - try { - List allCredentials = credentialReader.getAllCredentialsPerGateway(gatewayId); - if (allCredentials != null && !allCredentials.isEmpty()) { - for (Credential credential : allCredentials) { - if (credential - instanceof - org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) { - org.apache.airavata.credential.store.credential.impl.password.PasswordCredential pwdCredential = - (org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) - credential; - pwdCredMap.put( - pwdCredential.getToken(), - pwdCredential.getDescription() == null ? "" : pwdCredential.getDescription()); - } - } - } - } catch (CredentialStoreException e) { - log.error("Error occurred while retrieving credentials", e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while retrieving credentials"); - } - return pwdCredMap; + public Map getAllPWDCredentialsForGateway(String gatewayId) throws CredentialStoreException { + return credentialStoreService.getAllPWDCredentialsForGateway(gatewayId); } @Override - public boolean deleteSSHCredential(String tokenId, String gatewayId) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - try { - credentialReader.removeCredentials(gatewayId, tokenId); - return true; - } catch (CredentialStoreException e) { - log.error( - "Error occurred while deleting SSH credential for token - " + tokenId + " and gateway id - " - + gatewayId, - e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while deleting SSH credential for token - " + tokenId + " and gateway id - " - + gatewayId); - } + public boolean deleteSSHCredential(String tokenId, String gatewayId) throws CredentialStoreException { + return credentialStoreService.deleteSSHCredential(tokenId, gatewayId); } @Override - public boolean deletePWDCredential(String tokenId, String gatewayId) - throws org.apache.airavata.credential.store.exception.CredentialStoreException, TException { - try { - credentialReader.removeCredentials(gatewayId, tokenId); - return true; - } catch (CredentialStoreException e) { - log.error( - "Error occurred while deleting PWD credential for token - " + tokenId + " and gateway id - " - + gatewayId, - e); - throw new org.apache.airavata.credential.store.exception.CredentialStoreException( - "Error occurred while deleting PWD credential for token - " + tokenId + " and gateway id - " - + gatewayId); - } + public boolean deletePWDCredential(String tokenId, String gatewayId) throws CredentialStoreException { + return credentialStoreService.deletePWDCredential(tokenId, gatewayId); } } diff --git a/airavata-api/src/main/java/org/apache/airavata/orchestrator/server/OrchestratorServerHandler.java b/airavata-api/src/main/java/org/apache/airavata/orchestrator/server/OrchestratorServerHandler.java index e00a9d1c3c..daefcaa194 100644 --- a/airavata-api/src/main/java/org/apache/airavata/orchestrator/server/OrchestratorServerHandler.java +++ b/airavata-api/src/main/java/org/apache/airavata/orchestrator/server/OrchestratorServerHandler.java @@ -19,117 +19,37 @@ */ package org.apache.airavata.orchestrator.server; -import java.text.MessageFormat; -import java.util.*; -import org.apache.airavata.common.exception.AiravataException; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.logging.MDCConstants; -import org.apache.airavata.common.logging.MDCUtil; -import org.apache.airavata.common.utils.AiravataUtils; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.common.utils.ThriftUtils; -import org.apache.airavata.common.utils.ZkConstants; -import org.apache.airavata.messaging.core.*; -import org.apache.airavata.metascheduler.core.api.ProcessScheduler; -import org.apache.airavata.metascheduler.process.scheduling.api.ProcessSchedulerImpl; -import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription; -import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription; -import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription; -import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference; -import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile; -import org.apache.airavata.model.application.io.DataType; -import org.apache.airavata.model.application.io.OutputDataObjectType; -import org.apache.airavata.model.commons.ErrorModel; -import org.apache.airavata.model.data.replica.DataProductModel; -import org.apache.airavata.model.data.replica.DataReplicaLocationModel; -import org.apache.airavata.model.data.replica.ReplicaLocationCategory; +import java.util.List; +import org.apache.airavata.model.error.AiravataErrorType; +import org.apache.airavata.model.error.AiravataSystemException; import org.apache.airavata.model.error.LaunchValidationException; -import org.apache.airavata.model.experiment.ExperimentModel; -import org.apache.airavata.model.experiment.ExperimentType; -import org.apache.airavata.model.experiment.UserConfigurationDataModel; -import org.apache.airavata.model.messaging.event.*; import org.apache.airavata.model.process.ProcessModel; -import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel; -import org.apache.airavata.model.status.*; -import org.apache.airavata.model.task.TaskTypes; -import org.apache.airavata.model.util.ExperimentModelUtil; -import org.apache.airavata.orchestrator.core.exception.OrchestratorException; -import org.apache.airavata.orchestrator.core.schedule.HostScheduler; -import org.apache.airavata.orchestrator.core.utils.OrchestratorConstants; -import org.apache.airavata.orchestrator.cpi.OrchestratorService; -import org.apache.airavata.orchestrator.cpi.impl.SimpleOrchestratorImpl; import org.apache.airavata.orchestrator.util.OrchestratorServerThreadPoolExecutor; -import org.apache.airavata.orchestrator.util.OrchestratorUtils; -import org.apache.airavata.registry.api.RegistryService; -import org.apache.airavata.registry.api.RegistryService.Client; -import org.apache.airavata.registry.api.client.RegistryServiceClientFactory; -import org.apache.airavata.registry.api.exception.RegistryServiceException; -import org.apache.commons.lang3.StringUtils; -import org.apache.curator.RetryPolicy; -import org.apache.curator.framework.CuratorFramework; -import org.apache.curator.framework.CuratorFrameworkFactory; -import org.apache.curator.retry.ExponentialBackoffRetry; -import org.apache.curator.utils.ZKPaths; -import org.apache.thrift.TBase; -import org.apache.thrift.TException; -import org.apache.zookeeper.data.Stat; +import org.apache.airavata.service.OrchestratorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -public class OrchestratorServerHandler implements OrchestratorService.Iface { +public class OrchestratorServerHandler implements org.apache.airavata.orchestrator.cpi.OrchestratorService.Iface { private static Logger log = LoggerFactory.getLogger(OrchestratorServerHandler.class); - private SimpleOrchestratorImpl orchestrator = null; - private String airavataUserName; - private String gatewayName; - private Publisher publisher; - private final Subscriber statusSubscribe; - private final Subscriber experimentSubscriber; - - private CuratorFramework curatorClient; + private OrchestratorService orchestratorService; /** * Query orchestrator server to fetch the CPI version */ @Override - public String getAPIVersion() throws TException { - return null; + public String getAPIVersion() throws AiravataSystemException { + return org.apache.airavata.orchestrator.cpi.orchestrator_cpiConstants.ORCHESTRATOR_CPI_VERSION; } - public OrchestratorServerHandler() throws OrchestratorException, TException { - // orchestrator init + public OrchestratorServerHandler() { try { - // first constructing the monitorManager and orchestrator, then fill - // the required properties - setAiravataUserName(ServerSettings.getDefaultUser()); - orchestrator = new SimpleOrchestratorImpl(); - - publisher = MessagingFactory.getPublisher(Type.STATUS); - orchestrator.initialize(); - orchestrator.getOrchestratorContext().setPublisher(this.publisher); - statusSubscribe = getStatusSubscriber(); - experimentSubscriber = getExperimentSubscriber(); - startCurator(); - } catch (OrchestratorException | AiravataException e) { - log.error(e.getMessage(), e); - throw new OrchestratorException("Error while initializing orchestrator service", e); + orchestratorService = new OrchestratorService(); + } catch (Exception e) { + log.error("Error while initializing orchestrator service", e); + throw new RuntimeException("Error while initializing orchestrator service", e); } } - private Subscriber getStatusSubscriber() throws AiravataException { - List routingKeys = new ArrayList<>(); - // routingKeys.add("*"); // listen for gateway level messages - // routingKeys.add("*.*"); // listen for gateway/experiment level messages - routingKeys.add("*.*.*"); // listen for gateway/experiment/process level messages - return MessagingFactory.getSubscriber(new ProcessStatusHandler(), routingKeys, Type.STATUS); - } - - private Subscriber getExperimentSubscriber() throws AiravataException { - List routingKeys = new ArrayList<>(); - routingKeys.add(ServerSettings.getRabbitmqExperimentLaunchQueueName()); - return MessagingFactory.getSubscriber(new ExperimentHandler(), routingKeys, Type.EXPERIMENT_LAUNCH); - } - /** * * After creating the experiment Data user have the * experimentID as the * handler to the experiment, during the launchProcess * We just have to @@ -138,179 +58,19 @@ private Subscriber getExperimentSubscriber() throws AiravataException { * * @param experimentId */ - public boolean launchExperiment(String experimentId, String gatewayId) throws TException { - ExperimentModel experiment = null; - final RegistryService.Client registryClient = getRegistryServiceClient(); + @Override + public boolean launchExperiment(String experimentId, String gatewayId) throws AiravataSystemException { + var pool = OrchestratorServerThreadPoolExecutor.getCachedThreadPool(); try { - // TODO deprecate this approach as we are replacing gfac - String experimentNodePath = getExperimentNodePath(experimentId); - ZKPaths.mkdirs(curatorClient.getZookeeperClient().getZooKeeper(), experimentNodePath); - String experimentCancelNode = - ZKPaths.makePath(experimentNodePath, ZkConstants.ZOOKEEPER_CANCEL_LISTENER_NODE); - ZKPaths.mkdirs(curatorClient.getZookeeperClient().getZooKeeper(), experimentCancelNode); - experiment = registryClient.getExperiment(experimentId); - if (experiment == null) { - throw new Exception("Error retrieving the Experiment by the given experimentID: " + experimentId); - } - - UserConfigurationDataModel userConfigurationData = experiment.getUserConfigurationData(); - String token = null; - final String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId(); - if (groupResourceProfileId == null) { - throw new Exception("Experiment not configured with a Group Resource Profile: " + experimentId); - } - - if (userConfigurationData.getComputationalResourceScheduling() != null - && userConfigurationData - .getComputationalResourceScheduling() - .isSet(ComputationalResourceSchedulingModel._Fields.RESOURCE_HOST_ID)) { - GroupComputeResourcePreference groupComputeResourcePreference = - registryClient.getGroupComputeResourcePreference( - userConfigurationData - .getComputationalResourceScheduling() - .getResourceHostId(), - groupResourceProfileId); - - if (groupComputeResourcePreference.getResourceSpecificCredentialStoreToken() != null) { - token = groupComputeResourcePreference.getResourceSpecificCredentialStoreToken(); - } - } - if (token == null || token.isEmpty()) { - // try with group resource profile level token - GroupResourceProfile groupResourceProfile = - registryClient.getGroupResourceProfile(groupResourceProfileId); - token = groupResourceProfile.getDefaultCredentialStoreToken(); - } - // still the token is empty, then we fail the experiment - if (token == null || token.isEmpty()) { - throw new Exception( - "You have not configured credential store token at group resource profile or compute resource preference." - + " Please provide the correct token at group resource profile or compute resource preference."); - } - ExperimentType executionType = experiment.getExperimentType(); - if (executionType == ExperimentType.SINGLE_APPLICATION) { - // its an single application execution experiment - List processes = orchestrator.createProcesses(experimentId, gatewayId); - - for (ProcessModel processModel : processes) { - // FIXME Resolving replica if available. This is a very crude way of resolving input replicas. A - // full featured - // FIXME replica resolving logic should come here - processModel.getProcessInputs().stream().forEach(pi -> { - if (pi.getType().equals(DataType.URI) - && pi.getValue() != null - && pi.getValue().startsWith("airavata-dp://")) { - try { - DataProductModel dataProductModel = registryClient.getDataProduct(pi.getValue()); - Optional rpLocation = - dataProductModel.getReplicaLocations().stream() - .filter(rpModel -> rpModel.getReplicaLocationCategory() - .equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)) - .findFirst(); - if (rpLocation.isPresent()) { - pi.setValue(rpLocation.get().getFilePath()); - pi.setStorageResourceId(rpLocation.get().getStorageResourceId()); - } else { - log.error("Could not find a replica for the URI " + pi.getValue()); - } - } catch (RegistryServiceException e) { - throw new RuntimeException("Error while launching experiment", e); - } catch (TException e) { - throw new RuntimeException("Error while launching experiment", e); - } - } else if (pi.getType().equals(DataType.URI_COLLECTION) - && pi.getValue() != null - && pi.getValue().contains("airavata-dp://")) { - try { - String[] uriList = pi.getValue().split(","); - final ArrayList filePathList = new ArrayList<>(); - for (String uri : uriList) { - if (uri.startsWith("airavata-dp://")) { - DataProductModel dataProductModel = registryClient.getDataProduct(uri); - Optional rpLocation = - dataProductModel.getReplicaLocations().stream() - .filter(rpModel -> rpModel.getReplicaLocationCategory() - .equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)) - .findFirst(); - if (rpLocation.isPresent()) { - filePathList.add(rpLocation.get().getFilePath()); - } else { - log.error("Could not find a replica for the URI " + pi.getValue()); - } - } else { - // uri is in file path format - filePathList.add(uri); - } - } - pi.setValue(StringUtils.join(filePathList, ',')); - } catch (RegistryServiceException e) { - throw new RuntimeException("Error while launching experiment", e); - } catch (TException e) { - throw new RuntimeException("Error while launching experiment", e); - } - } - }); - - if (!experiment.getUserConfigurationData().isAiravataAutoSchedule()) { - String taskDag = orchestrator.createAndSaveTasks(gatewayId, processModel); - processModel.setTaskDag(taskDag); - } - registryClient.updateProcess(processModel, processModel.getProcessId()); - } - - if (!experiment.getUserConfigurationData().isAiravataAutoSchedule() - && !validateProcess(experimentId, processes)) { - throw new Exception("Validating process fails for given experiment Id : " + experimentId); - } - - ProcessScheduler scheduler = new ProcessSchedulerImpl(); - if (!experiment.getUserConfigurationData().isAiravataAutoSchedule() - || scheduler.canLaunch(experimentId)) { - createAndValidateTasks(experiment, registryClient, false); - runExperimentLauncher(experimentId, gatewayId, token); - } else { - log.debug(experimentId, "Queuing single application experiment {}.", experimentId); - ExperimentStatus status = new ExperimentStatus(ExperimentState.SCHEDULED); - status.setReason("Compute resources are not ready"); - status.setTimeOfStateChange( - AiravataUtils.getCurrentTimestamp().getTime()); - OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); - log.info("expId: {}, Scheduled experiment ", experimentId); - } - } else if (executionType == ExperimentType.WORKFLOW) { - // its a workflow execution experiment - log.debug(experimentId, "Launching workflow experiment {}.", experimentId); - launchWorkflowExperiment(experimentId, token, gatewayId); - } else { - log.error( - experimentId, - "Couldn't identify experiment type, experiment {} is neither single application nor workflow.", - experimentId); - throw new TException("Experiment '" + experimentId - + "' launch failed. Unable to figureout execution type for application " - + experiment.getExecutionId()); - } - } catch (LaunchValidationException launchValidationException) { - ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED); - status.setReason("Validation failed: " + launchValidationException.getErrorMessage()); - status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); - OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); - throw new TException( - "Experiment '" + experimentId + "' launch failed. Experiment failed to validate: " - + launchValidationException.getErrorMessage(), - launchValidationException); - } catch (Exception e) { - ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED); - status.setReason("Unexpected error occurred: " + e.getMessage()); - status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); - OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); - throw new TException("Experiment '" + experimentId + "' launch failed.", e); - } finally { - if (registryClient != null) { - ThriftUtils.close(registryClient); - } + return orchestratorService.launchExperiment(experimentId, gatewayId, pool); + } catch (Throwable e) { + log.error("Error launching experiment: " + experimentId, e); + AiravataSystemException exception = new AiravataSystemException(); + exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); + exception.setMessage("Error launching experiment: " + experimentId + ". More info: " + e.getMessage()); + exception.initCause(e); + throw exception; } - return true; } /** @@ -320,53 +80,33 @@ public boolean launchExperiment(String experimentId, String gatewayId) throws TE * * @param experimentId * @return - * @throws TException */ - public boolean validateExperiment(String experimentId) throws TException, LaunchValidationException { - final RegistryService.Client registryClient = getRegistryServiceClient(); + @Override + public boolean validateExperiment(String experimentId) throws LaunchValidationException { try { - ExperimentModel experimentModel = registryClient.getExperiment(experimentId); - return orchestrator.validateExperiment(experimentModel).isValidationState(); - } catch (OrchestratorException e) { - log.error(experimentId, "Error while validating experiment", e); - throw new TException(e); - } finally { - if (registryClient != null) { - ThriftUtils.close(registryClient); - } + return orchestratorService.validateExperiment(experimentId); + } catch (LaunchValidationException e) { + throw e; + } catch (Throwable e) { + log.error("Error validating experiment: " + experimentId, e); + LaunchValidationException exception = new LaunchValidationException(); + exception.setErrorMessage( + "Error validating experiment: " + experimentId + ". More info: " + e.getMessage()); + throw exception; } } @Override - public boolean validateProcess(String experimentId, List processes) - throws LaunchValidationException, TException { - final RegistryService.Client registryClient = getRegistryServiceClient(); + public boolean validateProcess(String experimentId, List processes) throws LaunchValidationException { try { - ExperimentModel experimentModel = registryClient.getExperiment(experimentId); - for (ProcessModel processModel : processes) { - boolean state = orchestrator - .validateProcess(experimentModel, processModel) - .isSetValidationState(); - if (!state) { - return false; - } - } - return true; - } catch (LaunchValidationException lve) { - - // If a process failed to validate, also add an error message at the experiment level - ErrorModel details = new ErrorModel(); - details.setActualErrorMessage(lve.getErrorMessage()); - details.setCreationTime(Calendar.getInstance().getTimeInMillis()); - registryClient.addErrors(OrchestratorConstants.EXPERIMENT_ERROR, details, experimentId); - throw lve; - } catch (OrchestratorException e) { - log.error(experimentId, "Error while validating process", e); - throw new TException(e); - } finally { - if (registryClient != null) { - ThriftUtils.close(registryClient); - } + return orchestratorService.validateProcess(experimentId, processes); + } catch (LaunchValidationException e) { + throw e; + } catch (Throwable e) { + log.error("Error validating process: " + experimentId, e); + LaunchValidationException exception = new LaunchValidationException(); + exception.setErrorMessage("Error validating process: " + experimentId + ". More info: " + e.getMessage()); + throw exception; } } @@ -376,724 +116,49 @@ public boolean validateProcess(String experimentId, List processes * * @param experimentId * @return - * @throws TException */ - public boolean terminateExperiment(String experimentId, String gatewayId) throws TException { - final RegistryService.Client registryClient = getRegistryServiceClient(); - log.info(experimentId, "Experiment: {} is cancelling !!!!!", experimentId); + @Override + public boolean terminateExperiment(String experimentId, String gatewayId) throws AiravataSystemException { + log.info("Experiment: {} is cancelling !!!!!", experimentId); try { - return validateStatesAndCancel(registryClient, experimentId, gatewayId); - } catch (Exception e) { - log.error("expId : " + experimentId + " :- Error while cancelling experiment", e); - return false; - } finally { - if (registryClient != null) { - ThriftUtils.close(registryClient); - } + return orchestratorService.terminateExperiment(experimentId, gatewayId); + } catch (Throwable e) { + log.error("Error terminating experiment: " + experimentId, e); + AiravataSystemException exception = new AiravataSystemException(); + exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); + exception.setMessage("Error terminating experiment: " + experimentId + ". More info: " + e.getMessage()); + exception.initCause(e); + throw exception; } } public void fetchIntermediateOutputs(String experimentId, String gatewayId, List outputNames) - throws TException { - final RegistryService.Client registryClient = getRegistryServiceClient(); - try { - submitIntermediateOutputsProcess(registryClient, experimentId, gatewayId, outputNames); - } catch (Exception e) { - log.error("expId : " + experimentId + " :- Error while fetching intermediate", e); - } finally { - if (registryClient != null) { - ThriftUtils.close(registryClient); - } - } - } - - private void submitIntermediateOutputsProcess( - Client registryClient, String experimentId, String gatewayId, List outputNames) throws Exception { - - ExperimentModel experimentModel = registryClient.getExperiment(experimentId); - ProcessModel processModel = ExperimentModelUtil.cloneProcessFromExperiment(experimentModel); - processModel.setExperimentDataDir(processModel.getExperimentDataDir() + "/intermediates"); - - List applicationOutputs = registryClient.getApplicationOutputs( - experimentModel.getExecutionId()); // This is to get a clean output object set - List requestedOutputs = new ArrayList<>(); - - for (OutputDataObjectType output : applicationOutputs) { - if (outputNames.contains(output.getName())) { - requestedOutputs.add(output); - } - } - processModel.setProcessOutputs(requestedOutputs); - String processId = registryClient.addProcess(processModel, experimentId); - processModel.setProcessId(processId); - + throws AiravataSystemException { try { - // Find the process that is responsible for main experiment workflow by - // looking for the process that has the JOB_SUBMISSION task - Optional jobSubmissionProcess = experimentModel.getProcesses().stream() - .filter(p -> p.getTasks().stream().anyMatch(t -> t.getTaskType() == TaskTypes.JOB_SUBMISSION)) - .findFirst(); - if (!jobSubmissionProcess.isPresent()) { - throw new Exception(MessageFormat.format( - "Could not find job submission process for experiment {0}, unable to fetch intermediate outputs {1}", - experimentId, outputNames)); - } - String taskDag = orchestrator.createAndSaveIntermediateOutputFetchingTasks( - gatewayId, processModel, jobSubmissionProcess.get()); - processModel.setTaskDag(taskDag); - - registryClient.updateProcess(processModel, processModel.getProcessId()); - - // Figure out the credential token - UserConfigurationDataModel userConfigurationData = experimentModel.getUserConfigurationData(); - String token = null; - final String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId(); - if (groupResourceProfileId == null) { - throw new Exception("Experiment not configured with a Group Resource Profile: " + experimentId); - } - GroupComputeResourcePreference groupComputeResourcePreference = - registryClient.getGroupComputeResourcePreference( - userConfigurationData - .getComputationalResourceScheduling() - .getResourceHostId(), - groupResourceProfileId); - if (groupComputeResourcePreference.getResourceSpecificCredentialStoreToken() != null) { - token = groupComputeResourcePreference.getResourceSpecificCredentialStoreToken(); - } - if (token == null || token.isEmpty()) { - // try with group resource profile level token - GroupResourceProfile groupResourceProfile = - registryClient.getGroupResourceProfile(groupResourceProfileId); - token = groupResourceProfile.getDefaultCredentialStoreToken(); - } - // still the token is empty, then we fail the experiment - if (token == null || token.isEmpty()) { - throw new Exception( - "You have not configured credential store token at group resource profile or compute resource preference." - + " Please provide the correct token at group resource profile or compute resource preference."); - } - orchestrator.launchProcess(processModel, token); - } catch (Exception e) { - log.error("Failed to launch process for intermediate output fetching", e); - - // Update Process status to FAILED - ProcessStatus status = new ProcessStatus(ProcessState.FAILED); - status.setReason("Intermediate output fetching process failed to launch: " + e.getMessage()); - status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); - registryClient.addProcessStatus(status, processId); - - throw e; + orchestratorService.fetchIntermediateOutputs(experimentId, gatewayId, outputNames); + } catch (Throwable e) { + log.error("Error fetching intermediate outputs for experiment: " + experimentId, e); + AiravataSystemException exception = new AiravataSystemException(); + exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); + exception.setMessage("Error fetching intermediate outputs for experiment: " + experimentId + ". More info: " + + e.getMessage()); + exception.initCause(e); + throw exception; } } - private String getAiravataUserName() { - return airavataUserName; - } - - private String getGatewayName() { - return gatewayName; - } - - public void setAiravataUserName(String airavataUserName) { - this.airavataUserName = airavataUserName; - } - - public void setGatewayName(String gatewayName) { - this.gatewayName = gatewayName; - } - @Override - public boolean launchProcess(String processId, String airavataCredStoreToken, String gatewayId) throws TException { - final RegistryService.Client registryClient = getRegistryServiceClient(); + public boolean launchProcess(String processId, String airavataCredStoreToken, String gatewayId) + throws AiravataSystemException { try { - ProcessStatus processStatus = registryClient.getProcessStatus(processId); - - switch (processStatus.getState()) { - case CREATED: - case VALIDATED: - case DEQUEUING: - ProcessModel processModel = registryClient.getProcess(processId); - String applicationId = processModel.getApplicationInterfaceId(); - if (applicationId == null) { - log.error(processId, "Application interface id shouldn't be null."); - throw new OrchestratorException( - "Error executing the job, application interface id shouldn't be null."); - } - // set application deployment id to process model - ApplicationDeploymentDescription applicationDeploymentDescription = - getAppDeployment(registryClient, processModel, applicationId); - if (applicationDeploymentDescription == null) { - log.error("Could not find an application deployment for " + processModel.getComputeResourceId() - + " and application " + applicationId); - throw new OrchestratorException("Could not find an application deployment for " - + processModel.getComputeResourceId() + " and application " + applicationId); - } - processModel.setApplicationDeploymentId(applicationDeploymentDescription.getAppDeploymentId()); - // set compute resource id to process model, default we set the same in the user preferred compute - // host id - processModel.setComputeResourceId( - processModel.getProcessResourceSchedule().getResourceHostId()); - registryClient.updateProcess(processModel, processModel.getProcessId()); - return orchestrator.launchProcess(processModel, airavataCredStoreToken); - - default: - log.warn("Process " + processId + " is already launched. So it can not be relaunched"); - return false; - } - - } catch (Exception e) { - log.error(processId, "Error while launching process ", e); - throw new TException(e); - } finally { - if (registryClient != null) { - ThriftUtils.close(registryClient); - } - } - } - - private ApplicationDeploymentDescription getAppDeployment( - RegistryService.Client registryClient, ProcessModel processModel, String applicationId) - throws OrchestratorException, ClassNotFoundException, ApplicationSettingsException, InstantiationException, - IllegalAccessException, TException { - String selectedModuleId = getModuleId(registryClient, applicationId); - return getAppDeploymentForModule(registryClient, processModel, selectedModuleId); - } - - private ApplicationDeploymentDescription getAppDeploymentForModule( - RegistryService.Client registryClient, ProcessModel processModel, String selectedModuleId) - throws ClassNotFoundException, ApplicationSettingsException, InstantiationException, IllegalAccessException, - TException { - - List applicationDeployements = - registryClient.getApplicationDeployments(selectedModuleId); - Map deploymentMap = - new HashMap(); - - for (ApplicationDeploymentDescription deploymentDescription : applicationDeployements) { - if (processModel.getComputeResourceId().equals(deploymentDescription.getComputeHostId())) { - deploymentMap.put( - registryClient.getComputeResource(deploymentDescription.getComputeHostId()), - deploymentDescription); - } - } - List computeHostList = - Arrays.asList(deploymentMap.keySet().toArray(new ComputeResourceDescription[] {})); - Class aClass = - Class.forName(ServerSettings.getHostScheduler()).asSubclass(HostScheduler.class); - HostScheduler hostScheduler = aClass.newInstance(); - ComputeResourceDescription ComputeResourceDescription = hostScheduler.schedule(computeHostList); - return deploymentMap.get(ComputeResourceDescription); - } - - private String getModuleId(RegistryService.Client registryClient, String applicationId) - throws OrchestratorException, TException { - ApplicationInterfaceDescription applicationInterface = registryClient.getApplicationInterface(applicationId); - List applicationModules = applicationInterface.getApplicationModules(); - if (applicationModules.size() == 0) { - throw new OrchestratorException("No modules defined for application " + applicationId); - } - // AiravataAPI airavataAPI = getAiravataAPI(); - String selectedModuleId = applicationModules.get(0); - return selectedModuleId; - } - - private boolean validateStatesAndCancel( - RegistryService.Client registryClient, String experimentId, String gatewayId) throws Exception { - ExperimentStatus experimentStatus = registryClient.getExperimentStatus(experimentId); - switch (experimentStatus.getState()) { - case COMPLETED: - case CANCELED: - case FAILED: - case CANCELING: - log.warn( - "Can't terminate already {} experiment", - experimentStatus.getState().name()); - return false; - case CREATED: - log.warn("Experiment termination is only allowed for launched experiments."); - return false; - default: - ExperimentModel experimentModel = registryClient.getExperiment(experimentId); - final UserConfigurationDataModel userConfigurationData = experimentModel.getUserConfigurationData(); - final String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId(); - - GroupComputeResourcePreference groupComputeResourcePreference = - registryClient.getGroupComputeResourcePreference( - userConfigurationData - .getComputationalResourceScheduling() - .getResourceHostId(), - groupResourceProfileId); - String token = groupComputeResourcePreference.getResourceSpecificCredentialStoreToken(); - if (token == null || token.isEmpty()) { - // try with group resource profile level token - GroupResourceProfile groupResourceProfile = - registryClient.getGroupResourceProfile(groupResourceProfileId); - token = groupResourceProfile.getDefaultCredentialStoreToken(); - } - // still the token is empty, then we fail the experiment - if (token == null || token.isEmpty()) { - log.error( - "You have not configured credential store token at group resource profile or compute resource preference." - + " Please provide the correct token at group resource profile or compute resource preference."); - return false; - } - - orchestrator.cancelExperiment(experimentModel, token); - // TODO deprecate this approach as we are replacing gfac - String expCancelNodePath = ZKPaths.makePath( - ZKPaths.makePath(ZkConstants.ZOOKEEPER_EXPERIMENT_NODE, experimentId), - ZkConstants.ZOOKEEPER_CANCEL_LISTENER_NODE); - Stat stat = curatorClient.checkExists().forPath(expCancelNodePath); - if (stat != null) { - curatorClient - .setData() - .withVersion(-1) - .forPath(expCancelNodePath, ZkConstants.ZOOKEEPER_CANCEL_REQEUST.getBytes()); - ExperimentStatus status = new ExperimentStatus(ExperimentState.CANCELING); - status.setReason("Experiment cancel request processed"); - status.setTimeOfStateChange( - AiravataUtils.getCurrentTimestamp().getTime()); - OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); - log.info("expId : " + experimentId + " :- Experiment status updated to " + status.getState()); - } - return true; - } - } - - private void launchWorkflowExperiment(String experimentId, String airavataCredStoreToken, String gatewayId) - throws TException { - // FIXME - // try { - // WorkflowEnactmentService.getInstance(). - // submitWorkflow(experimentId, airavataCredStoreToken, getGatewayName(), - // getRabbitMQProcessPublisher()); - // } catch (Exception e) { - // log.error("Error while launching workflow", e); - // } - } - - private class SingleAppExperimentRunner implements Runnable { - - String experimentId; - String airavataCredStoreToken; - String gatewayId; - - public SingleAppExperimentRunner(String experimentId, String airavataCredStoreToken, String gatewayId) { - this.experimentId = experimentId; - this.airavataCredStoreToken = airavataCredStoreToken; - this.gatewayId = gatewayId; - } - - @Override - public void run() { - try { - launchSingleAppExperiment(); - } catch (TException e) { - log.error("Unable to launch experiment..", e); - throw new RuntimeException("Error while launching experiment", e); - } catch (AiravataException e) { - log.error("Unable to publish experiment status..", e); - } - } - - private boolean launchSingleAppExperiment() throws TException, AiravataException { - final RegistryService.Client registryClient = getRegistryServiceClient(); - try { - List processIds = registryClient.getProcessIds(experimentId); - for (String processId : processIds) { - launchProcess(processId, airavataCredStoreToken, gatewayId); - } - // ExperimentStatus status = new ExperimentStatus(ExperimentState.LAUNCHED); - // status.setReason("submitted all processes"); - // status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); - // OrchestratorUtils.updageAndPublishExperimentStatus(experimentId, status); - // log.info("expId: {}, Launched experiment ", experimentId); - } catch (Exception e) { - ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED); - status.setReason("Error while updating task status"); - OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); - log.error( - "expId: " + experimentId - + ", Error while updating task status, hence updated experiment status to " - + ExperimentState.FAILED, - e); - ExperimentStatusChangeEvent event = - new ExperimentStatusChangeEvent(ExperimentState.FAILED, experimentId, gatewayId); - String messageId = AiravataUtils.getId("EXPERIMENT"); - MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT, messageId, gatewayId); - messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); - publisher.publish(messageContext); - throw new TException(e); - } finally { - if (registryClient != null) { - ThriftUtils.close(registryClient); - } - } - return true; - } - } - - private class ProcessStatusHandler implements MessageHandler { - /** - * This method only handle MessageType.PROCESS type messages. - * - * @param message - */ - @Override - public void onMessage(MessageContext message) { - if (message.getType().equals(MessageType.PROCESS)) { - try { - ProcessStatusChangeEvent processStatusChangeEvent = new ProcessStatusChangeEvent(); - TBase event = message.getEvent(); - byte[] bytes = ThriftUtils.serializeThriftObject(event); - ThriftUtils.createThriftFromBytes(bytes, processStatusChangeEvent); - ExperimentStatus status = new ExperimentStatus(); - ProcessIdentifier processIdentity = processStatusChangeEvent.getProcessIdentity(); - log.info( - "expId: {}, processId: {} :- Process status changed event received for status {}", - processIdentity.getExperimentId(), - processIdentity.getProcessId(), - processStatusChangeEvent.getState().name()); - try { - ProcessModel process = OrchestratorUtils.getProcess(processIdentity.getProcessId()); - boolean isIntermediateOutputFetchingProcess = - process.getTasks().stream().anyMatch(t -> t.getTaskType() == TaskTypes.OUTPUT_FETCHING); - if (isIntermediateOutputFetchingProcess) { - log.info( - "Not updating experiment status because process is an intermediate output fetching one"); - return; - } - } catch (ApplicationSettingsException e) { - throw new RuntimeException("Error getting process " + processIdentity.getProcessId(), e); - } - switch (processStatusChangeEvent.getState()) { - // case CREATED: - // case VALIDATED: - case STARTED: - try { - ExperimentStatus stat = - OrchestratorUtils.getExperimentStatus(processIdentity.getExperimentId()); - if (stat.getState() == ExperimentState.CANCELING) { - status.setState(ExperimentState.CANCELING); - status.setReason("Process started but experiment cancelling is triggered"); - } else { - status.setState(ExperimentState.EXECUTING); - status.setReason("process started"); - } - } catch (ApplicationSettingsException e) { - throw new RuntimeException("Error ", e); - } - break; - // case PRE_PROCESSING: - // break; - // case CONFIGURING_WORKSPACE: - // case INPUT_DATA_STAGING: - // case EXECUTING: - // case MONITORING: - // case OUTPUT_DATA_STAGING: - // case POST_PROCESSING: - // case CANCELLING: - // break; - case COMPLETED: - try { - ExperimentStatus stat = - OrchestratorUtils.getExperimentStatus(processIdentity.getExperimentId()); - if (stat.getState() == ExperimentState.CANCELING) { - status.setState(ExperimentState.CANCELED); - status.setReason("Process competed but experiment cancelling is triggered"); - } else { - status.setState(ExperimentState.COMPLETED); - status.setReason("process completed"); - } - } catch (ApplicationSettingsException e) { - throw new RuntimeException("Error ", e); - } - break; - case FAILED: - try { - ExperimentStatus stat = - OrchestratorUtils.getExperimentStatus(processIdentity.getExperimentId()); - if (stat.getState() == ExperimentState.CANCELING) { - status.setState(ExperimentState.CANCELED); - status.setReason("Process failed but experiment cancelling is triggered"); - } else { - status.setState(ExperimentState.FAILED); - status.setReason("process failed"); - } - } catch (ApplicationSettingsException e) { - throw new RuntimeException("Unable to create registry client...", e); - } - break; - case CANCELED: - // TODO if experiment have more than one process associated with it, then this should be - // changed. - status.setState(ExperimentState.CANCELED); - status.setReason("process cancelled"); - break; - case QUEUED: - status.setState(ExperimentState.SCHEDULED); - status.setReason("Process started but compute resource not avaialable"); - break; - case REQUEUED: - status.setState(ExperimentState.SCHEDULED); - status.setReason("Job submission failed, requeued to resubmit"); - List queueStatusModels = new ArrayList<>(); - final RegistryService.Client registryClient = getRegistryServiceClient(); - ExperimentModel experimentModel = - registryClient.getExperiment(processIdentity.getExperimentId()); - UserConfigurationDataModel userConfigurationDataModel = - experimentModel.getUserConfigurationData(); - if (userConfigurationDataModel != null) { - ComputationalResourceSchedulingModel computationalResourceSchedulingModel = - userConfigurationDataModel.getComputationalResourceScheduling(); - if (computationalResourceSchedulingModel != null) { - String queueName = computationalResourceSchedulingModel.getQueueName(); - String resourceId = computationalResourceSchedulingModel.getResourceHostId(); - ComputeResourceDescription comResourceDes = - registryClient.getComputeResource(resourceId); - QueueStatusModel queueStatusModel = new QueueStatusModel(); - queueStatusModel.setHostName(comResourceDes.getHostName()); - queueStatusModel.setQueueName(queueName); - queueStatusModel.setQueueUp(false); - queueStatusModel.setRunningJobs(0); - queueStatusModel.setQueuedJobs(0); - queueStatusModel.setTime(System.currentTimeMillis()); - queueStatusModels.add(queueStatusModel); - registryClient.registerQueueStatuses(queueStatusModels); - } - } - - break; - case DEQUEUING: - try { - ExperimentStatus stat = - OrchestratorUtils.getExperimentStatus(processIdentity.getExperimentId()); - if (stat.getState() == ExperimentState.CANCELING) { - status.setState(ExperimentState.CANCELING); - status.setReason("Process started but experiment cancelling is triggered"); - } else { - launchQueuedExperiment(processIdentity.getExperimentId()); - } - - } catch (Exception e) { - throw new RuntimeException("Error ", e); - } - break; - default: - // ignore other status changes, thoes will not affect for experiment status changes - return; - } - if (status.getState() != null) { - status.setTimeOfStateChange( - AiravataUtils.getCurrentTimestamp().getTime()); - OrchestratorUtils.updateAndPublishExperimentStatus( - processIdentity.getExperimentId(), status, publisher, processIdentity.getGatewayId()); - log.info("expId : " + processIdentity.getExperimentId() + " :- Experiment status updated to " - + status.getState()); - } - } catch (TException e) { - log.error("Message Id : " + message.getMessageId() + ", Message type : " + message.getType() - + "Error" + " while prcessing process status change event"); - throw new RuntimeException("Error while updating experiment status", e); - } - } else { - System.out.println("Message Recieved with message id " + message.getMessageId() + " and with message " - + "type " + message.getType().name()); - } - } - } - - private class ExperimentHandler implements MessageHandler { - - @Override - public void onMessage(MessageContext messageContext) { - MDC.put(MDCConstants.GATEWAY_ID, messageContext.getGatewayId()); - switch (messageContext.getType()) { - case EXPERIMENT: - launchExperiment(messageContext); - break; - case EXPERIMENT_CANCEL: - cancelExperiment(messageContext); - break; - case INTERMEDIATE_OUTPUTS: - handleIntermediateOutputsEvent(messageContext); - break; - default: - experimentSubscriber.sendAck(messageContext.getDeliveryTag()); - log.error("Orchestrator got un-support message type : " + messageContext.getType()); - break; - } - MDC.clear(); - } - - private void cancelExperiment(MessageContext messageContext) { - try { - byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent()); - ExperimentSubmitEvent expEvent = new ExperimentSubmitEvent(); - ThriftUtils.createThriftFromBytes(bytes, expEvent); - log.info( - "Cancelling experiment with experimentId: {} gateway Id: {}", - expEvent.getExperimentId(), - expEvent.getGatewayId()); - terminateExperiment(expEvent.getExperimentId(), expEvent.getGatewayId()); - } catch (TException e) { - log.error("Error while cancelling experiment", e); - throw new RuntimeException("Error while cancelling experiment", e); - } finally { - experimentSubscriber.sendAck(messageContext.getDeliveryTag()); - } - } - - private void handleIntermediateOutputsEvent(MessageContext messageContext) { - try { - byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent()); - ExperimentIntermediateOutputsEvent event = new ExperimentIntermediateOutputsEvent(); - ThriftUtils.createThriftFromBytes(bytes, event); - log.info( - "INTERMEDIATE_OUTPUTS event for experimentId: {} gateway Id: {} outputs: {}", - event.getExperimentId(), - event.getGatewayId(), - event.getOutputNames()); - fetchIntermediateOutputs(event.getExperimentId(), event.getGatewayId(), event.getOutputNames()); - } catch (TException e) { - log.error("Error while fetching intermediate outputs", e); - throw new RuntimeException("Error while fetching intermediate outputs", e); - } finally { - experimentSubscriber.sendAck(messageContext.getDeliveryTag()); - } - } - } - - private void launchExperiment(MessageContext messageContext) { - ExperimentSubmitEvent expEvent = new ExperimentSubmitEvent(); - final RegistryService.Client registryClient = getRegistryServiceClient(); - try { - byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent()); - ThriftUtils.createThriftFromBytes(bytes, expEvent); - MDC.put(MDCConstants.EXPERIMENT_ID, expEvent.getExperimentId()); - log.info( - "Launching experiment with experimentId: {} gateway Id: {}", - expEvent.getExperimentId(), - expEvent.getGatewayId()); - if (messageContext.isRedeliver()) { - ExperimentModel experimentModel = registryClient.getExperiment(expEvent.getExperimentId()); - MDC.put(MDCConstants.EXPERIMENT_NAME, experimentModel.getExperimentName()); - if (experimentModel.getExperimentStatus().get(0).getState() == ExperimentState.CREATED) { - launchExperiment(expEvent.getExperimentId(), expEvent.getGatewayId()); - } - } else { - launchExperiment(expEvent.getExperimentId(), expEvent.getGatewayId()); - } - } catch (TException e) { - String logMessage = expEvent.getExperimentId() != null && expEvent.getGatewayId() != null - ? String.format( - "Experiment launch failed due to Thrift conversion error, experimentId: %s, gatewayId: %s", - expEvent.getExperimentId(), expEvent.getGatewayId()) - : "Experiment launch failed due to Thrift conversion error"; - log.error(logMessage, e); - } catch (Exception e) { - log.error( - "An unknown issue while launching experiment " - + Optional.ofNullable(expEvent.getExperimentId()).orElse("missing experiment") - + " on gateway " - + Optional.ofNullable(expEvent.getGatewayId()).orElse("missing gateway"), - e); - } finally { - experimentSubscriber.sendAck(messageContext.getDeliveryTag()); - MDC.clear(); - if (registryClient != null) { - ThriftUtils.close(registryClient); - } - } - } - - private RegistryService.Client getRegistryServiceClient() { - try { - final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort()); - final String serverHost = ServerSettings.getRegistryServerHost(); - return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort); - } catch (RegistryServiceException | ApplicationSettingsException e) { - throw new RuntimeException("Unable to create registry client...", e); - } - } - - private void startCurator() throws ApplicationSettingsException { - String connectionSting = ServerSettings.getZookeeperConnection(); - RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5); - curatorClient = CuratorFrameworkFactory.newClient(connectionSting, retryPolicy); - curatorClient.start(); - } - - public String getExperimentNodePath(String experimentId) { - return ZKPaths.makePath(ZkConstants.ZOOKEEPER_EXPERIMENT_NODE, experimentId); - } - - private void runExperimentLauncher(String experimentId, String gatewayId, String token) throws TException { - ExperimentStatus status = new ExperimentStatus(ExperimentState.LAUNCHED); - status.setReason("submitted all processes"); - status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); - OrchestratorUtils.updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); - log.info("expId: {}, Launched experiment ", experimentId); - OrchestratorServerThreadPoolExecutor.getCachedThreadPool() - .execute(MDCUtil.wrapWithMDC(new SingleAppExperimentRunner(experimentId, token, gatewayId))); - } - - private void launchQueuedExperiment(String experimentId) throws TException, Exception { - ExperimentModel experiment = null; - final RegistryService.Client registryClient = getRegistryServiceClient(); - // TODO deprecate this approach as we are replacing gfac - experiment = registryClient.getExperiment(experimentId); - if (experiment == null) { - throw new Exception("Error retrieving the Experiment by the given experimentID: " + experimentId); - } - - UserConfigurationDataModel userConfigurationData = experiment.getUserConfigurationData(); - String token = null; - final String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId(); - if (groupResourceProfileId == null) { - throw new Exception("Experiment not configured with a Group Resource Profile: " + experimentId); - } - GroupComputeResourcePreference groupComputeResourcePreference = - registryClient.getGroupComputeResourcePreference( - userConfigurationData - .getComputationalResourceScheduling() - .getResourceHostId(), - groupResourceProfileId); - if (groupComputeResourcePreference.getResourceSpecificCredentialStoreToken() != null) { - token = groupComputeResourcePreference.getResourceSpecificCredentialStoreToken(); - } - if (token == null || token.isEmpty()) { - // try with group resource profile level token - GroupResourceProfile groupResourceProfile = registryClient.getGroupResourceProfile(groupResourceProfileId); - token = groupResourceProfile.getDefaultCredentialStoreToken(); - } - // still the token is empty, then we fail the experiment - if (token == null || token.isEmpty()) { - throw new Exception( - "You have not configured credential store token at group resource profile or compute resource preference." - + " Please provide the correct token at group resource profile or compute resource preference."); - } - createAndValidateTasks(experiment, registryClient, true); - runExperimentLauncher(experimentId, experiment.getGatewayId(), token); - } - - private void createAndValidateTasks( - ExperimentModel experiment, RegistryService.Client registryClient, boolean recreateTaskDag) - throws Exception { - if (experiment.getUserConfigurationData().isAiravataAutoSchedule()) { - List processModels = registryClient.getProcessList(experiment.getExperimentId()); - for (ProcessModel processModel : processModels) { - if (processModel.getTaskDag() == null || recreateTaskDag) { - registryClient.deleteTasks(processModel.getProcessId()); - String taskDag = orchestrator.createAndSaveTasks(experiment.getGatewayId(), processModel); - processModel.setTaskDag(taskDag); - registryClient.updateProcess(processModel, processModel.getProcessId()); - } - } - if (!validateProcess(experiment.getExperimentId(), processModels)) { - throw new Exception( - "Validating process fails for given experiment Id : " + experiment.getExperimentId()); - } + return orchestratorService.launchProcess(processId, airavataCredStoreToken, gatewayId); + } catch (Throwable e) { + log.error("Error launching process: " + processId, e); + AiravataSystemException exception = new AiravataSystemException(); + exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); + exception.setMessage("Error launching process: " + processId + ". More info: " + e.getMessage()); + exception.initCause(e); + throw exception; } } } diff --git a/airavata-api/src/main/java/org/apache/airavata/orchestrator/util/OrchestratorUtils.java b/airavata-api/src/main/java/org/apache/airavata/orchestrator/util/OrchestratorUtils.java deleted file mode 100644 index 25c5dcc932..0000000000 --- a/airavata-api/src/main/java/org/apache/airavata/orchestrator/util/OrchestratorUtils.java +++ /dev/null @@ -1,99 +0,0 @@ -/** -* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. -*/ -package org.apache.airavata.orchestrator.util; - -import org.apache.airavata.common.exception.AiravataException; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.AiravataUtils; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.common.utils.ThriftUtils; -import org.apache.airavata.messaging.core.MessageContext; -import org.apache.airavata.messaging.core.Publisher; -import org.apache.airavata.model.messaging.event.ExperimentStatusChangeEvent; -import org.apache.airavata.model.messaging.event.MessageType; -import org.apache.airavata.model.process.ProcessModel; -import org.apache.airavata.model.status.ExperimentStatus; -import org.apache.airavata.registry.api.RegistryService; -import org.apache.airavata.registry.api.client.RegistryServiceClientFactory; -import org.apache.airavata.registry.api.exception.RegistryServiceException; -import org.apache.thrift.TException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class OrchestratorUtils { - private static final Logger log = LoggerFactory.getLogger(OrchestratorUtils.class); - - public static void updateAndPublishExperimentStatus( - String experimentId, ExperimentStatus status, Publisher publisher, String gatewayId) throws TException { - RegistryService.Client registryClient = null; - try { - registryClient = getRegistryServiceClient(); - registryClient.updateExperimentStatus(status, experimentId); - ExperimentStatusChangeEvent event = - new ExperimentStatusChangeEvent(status.getState(), experimentId, gatewayId); - String messageId = AiravataUtils.getId("EXPERIMENT"); - MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT, messageId, gatewayId); - messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); - publisher.publish(messageContext); - } catch (AiravataException e) { - log.error( - "expId : " + experimentId + " Error while publishing experiment status to " + status.toString(), e); - } finally { - if (registryClient != null) { - ThriftUtils.close(registryClient); - } - } - } - - public static ExperimentStatus getExperimentStatus(String experimentId) - throws TException, ApplicationSettingsException { - RegistryService.Client registryClient = null; - try { - registryClient = getRegistryServiceClient(); - return registryClient.getExperimentStatus(experimentId); - } finally { - if (registryClient != null) { - ThriftUtils.close(registryClient); - } - } - } - - public static ProcessModel getProcess(String processId) throws TException, ApplicationSettingsException { - RegistryService.Client registryClient = null; - try { - registryClient = getRegistryServiceClient(); - return registryClient.getProcess(processId); - } finally { - if (registryClient != null) { - ThriftUtils.close(registryClient); - } - } - } - - private static RegistryService.Client getRegistryServiceClient() throws ApplicationSettingsException { - final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort()); - final String serverHost = ServerSettings.getRegistryServerHost(); - try { - return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort); - } catch (RegistryServiceException e) { - throw new RuntimeException("Unable to create registry client...", e); - } - } -} diff --git a/airavata-api/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java b/airavata-api/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java index a3432e3f75..e04a340f40 100644 --- a/airavata-api/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java +++ b/airavata-api/src/main/java/org/apache/airavata/registry/api/service/handler/RegistryServerHandler.java @@ -20,8 +20,6 @@ package org.apache.airavata.registry.api.service.handler; import java.util.*; -import org.apache.airavata.common.utils.AiravataUtils; -import org.apache.airavata.common.utils.ServerSettings; import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription; import org.apache.airavata.model.appcatalog.appdeployment.ApplicationModule; import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription; @@ -50,6 +48,7 @@ import org.apache.airavata.model.data.replica.DataProductModel; import org.apache.airavata.model.data.replica.DataReplicaLocationModel; import org.apache.airavata.model.error.*; +import org.apache.airavata.model.error.AiravataSystemException; import org.apache.airavata.model.experiment.*; import org.apache.airavata.model.job.JobModel; import org.apache.airavata.model.process.ProcessModel; @@ -65,63 +64,28 @@ import org.apache.airavata.registry.api.RegistryService; import org.apache.airavata.registry.api.exception.RegistryServiceException; import org.apache.airavata.registry.api.registry_apiConstants; -import org.apache.airavata.registry.core.entities.expcatalog.JobPK; -import org.apache.airavata.registry.core.repositories.appcatalog.*; -import org.apache.airavata.registry.core.repositories.expcatalog.*; -import org.apache.airavata.registry.core.repositories.replicacatalog.DataProductRepository; -import org.apache.airavata.registry.core.repositories.replicacatalog.DataReplicaLocationRepository; -import org.apache.airavata.registry.core.repositories.workflowcatalog.WorkflowRepository; -import org.apache.airavata.registry.core.utils.DBConstants; -import org.apache.airavata.registry.cpi.*; -import org.apache.airavata.registry.cpi.utils.Constants; -import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RegistryServerHandler implements RegistryService.Iface { private static final Logger logger = LoggerFactory.getLogger(RegistryServerHandler.class); - private ApplicationDeploymentRepository applicationDeploymentRepository = new ApplicationDeploymentRepository(); - private ApplicationInterfaceRepository applicationInterfaceRepository = new ApplicationInterfaceRepository(); - private StorageResourceRepository storageResourceRepository = new StorageResourceRepository(); - private UserResourceProfileRepository userResourceProfileRepository = new UserResourceProfileRepository(); - private GatewayRepository gatewayRepository = new GatewayRepository(); - private ProjectRepository projectRepository = new ProjectRepository(); - private NotificationRepository notificationRepository = new NotificationRepository(); - private ExperimentSummaryRepository experimentSummaryRepository = new ExperimentSummaryRepository(); - private ExperimentRepository experimentRepository = new ExperimentRepository(); - private ExperimentOutputRepository experimentOutputRepository = new ExperimentOutputRepository(); - private ExperimentStatusRepository experimentStatusRepository = new ExperimentStatusRepository(); - private ExperimentErrorRepository experimentErrorRepository = new ExperimentErrorRepository(); - private ProcessRepository processRepository = new ProcessRepository(); - private ProcessOutputRepository processOutputRepository = new ProcessOutputRepository(); - private ProcessWorkflowRepository processWorkflowRepository = new ProcessWorkflowRepository(); - private ProcessStatusRepository processStatusRepository = new ProcessStatusRepository(); - private ProcessErrorRepository processErrorRepository = new ProcessErrorRepository(); - private TaskRepository taskRepository = new TaskRepository(); - private TaskStatusRepository taskStatusRepository = new TaskStatusRepository(); - private TaskErrorRepository taskErrorRepository = new TaskErrorRepository(); - private JobRepository jobRepository = new JobRepository(); - private JobStatusRepository jobStatusRepository = new JobStatusRepository(); - private QueueStatusRepository queueStatusRepository = new QueueStatusRepository(); - private DataProductRepository dataProductRepository = new DataProductRepository(); - private DataReplicaLocationRepository dataReplicaLocationRepository = new DataReplicaLocationRepository(); - private WorkflowRepository workflowRepository = new WorkflowRepository(); - private GatewayGroupsRepository gatewayGroupsRepository = new GatewayGroupsRepository(); - private ParserRepository parserRepository = new ParserRepository(); - private ParserInputRepository parserInputRepository = new ParserInputRepository(); - private ParserOutputRepository parserOutputRepository = new ParserOutputRepository(); - private ParsingTemplateRepository parsingTemplateRepository = new ParsingTemplateRepository(); - private UserRepository userRepository = new UserRepository(); - private ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - private GatewayUsageReportingCommandRepository usageReportingCommandRepository = - new GatewayUsageReportingCommandRepository(); + private org.apache.airavata.service.RegistryService registryService = + new org.apache.airavata.service.RegistryService(); + + // Helper method to convert domain exceptions to Thrift exceptions + private RegistryServiceException convertToRegistryServiceException(Throwable e, String context) { + logger.error(context, e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage(context + ". More info : " + e.getMessage()); + return exception; + } /** * Fetch Apache Registry API version */ @Override - public String getAPIVersion() throws TException { + public String getAPIVersion() throws AiravataSystemException { return registry_apiConstants.REGISTRY_API_VERSION; } @@ -133,15 +97,8 @@ public String getAPIVersion() throws TException { * @return true/false */ @Override - public boolean isUserExists(String gatewayId, String userName) throws RegistryServiceException, TException { - try { - return userRepository.isUserExists(gatewayId, userName); - } catch (RegistryException e) { - logger.error("Error while verifying user", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while verifying user. More info : " + e.getMessage()); - throw exception; - } + public boolean isUserExists(String gatewayId, String userName) throws RegistryServiceException { + return registryService.isUserExists(gatewayId, userName); } /** @@ -152,15 +109,8 @@ public boolean isUserExists(String gatewayId, String userName) throws RegistrySe * list of usernames of the users in the gateway */ @Override - public List getAllUsersInGateway(String gatewayId) throws RegistryServiceException, TException { - try { - return userRepository.getAllUsernamesInGateway(gatewayId); - } catch (RegistryException e) { - logger.error("Error while retrieving users", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving users. More info : " + e.getMessage()); - throw exception; - } + public List getAllUsersInGateway(String gatewayId) throws RegistryServiceException { + return registryService.getAllUsersInGateway(gatewayId); } /** @@ -171,23 +121,8 @@ public List getAllUsersInGateway(String gatewayId) throws RegistryServic * Gateway obejct. */ @Override - public Gateway getGateway(String gatewayId) throws RegistryServiceException, TException { - try { - if (!gatewayRepository.isGatewayExist(gatewayId)) { - logger.error("Gateway does not exist in the system. Please provide a valid gateway ID..."); - AiravataSystemException exception = new AiravataSystemException(); - exception.setMessage("Gateway does not exist in the system. Please provide a valid gateway ID..."); - throw exception; - } - Gateway gateway = gatewayRepository.getGateway(gatewayId); - logger.debug("Airavata retrieved gateway with gateway id : " + gateway.getGatewayId()); - return gateway; - } catch (RegistryException e) { - logger.error("Error while getting the gateway", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while getting the gateway. More info : " + e.getMessage()); - throw exception; - } + public Gateway getGateway(String gatewayId) throws RegistryServiceException { + return registryService.getGateway(gatewayId); } /** @@ -198,40 +133,16 @@ public Gateway getGateway(String gatewayId) throws RegistryServiceException, TEx * Boolean identifier for the success or failure of the deletion operation. */ @Override - public boolean deleteGateway(String gatewayId) throws RegistryServiceException, TException { - try { - if (!gatewayRepository.isGatewayExist(gatewayId)) { - logger.error("Gateway does not exist in the system. Please provide a valid gateway ID..."); - AiravataSystemException exception = new AiravataSystemException(); - exception.setMessage("Gateway does not exist in the system. Please provide a valid gateway ID..."); - throw exception; - } - gatewayRepository.removeGateway(gatewayId); - logger.debug("Airavata deleted gateway with gateway id : " + gatewayId); - return true; - } catch (RegistryException e) { - logger.error("Error while deleting the gateway", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting the gateway. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteGateway(String gatewayId) throws RegistryServiceException { + return registryService.deleteGateway(gatewayId); } /** * Get All the Gateways Connected to Airavata. */ @Override - public List getAllGateways() throws RegistryServiceException, TException { - try { - List gateways = gatewayRepository.getAllGateways(); - logger.debug("Airavata retrieved all available gateways..."); - return gateways; - } catch (RegistryException e) { - logger.error("Error while getting all the gateways", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while getting all the gateways. More info : " + e.getMessage()); - throw exception; - } + public List getAllGateways() throws RegistryServiceException { + return registryService.getAllGateways(); } /** @@ -242,55 +153,23 @@ public List getAllGateways() throws RegistryServiceException, TExceptio * return the gatewayId of the existing gateway. */ @Override - public boolean isGatewayExist(String gatewayId) throws RegistryServiceException, TException { - try { - return gatewayRepository.isGatewayExist(gatewayId); - } catch (RegistryException e) { - logger.error("Error while getting gateway", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while getting gateway. More info : " + e.getMessage()); - throw exception; - } + public boolean isGatewayExist(String gatewayId) throws RegistryServiceException { + return registryService.isGatewayExist(gatewayId); } @Override - public boolean deleteNotification(String gatewayId, String notificationId) - throws RegistryServiceException, TException { - try { - notificationRepository.deleteNotification(notificationId); - return true; - } catch (RegistryException e) { - logger.error("Error while deleting notification", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting notification. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteNotification(String gatewayId, String notificationId) throws RegistryServiceException { + return registryService.deleteNotification(gatewayId, notificationId); } @Override - public Notification getNotification(String gatewayId, String notificationId) - throws RegistryServiceException, TException { - try { - return notificationRepository.getNotification(notificationId); - } catch (RegistryException e) { - logger.error("Error while retrieving notification", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retreiving notification. More info : " + e.getMessage()); - throw exception; - } + public Notification getNotification(String gatewayId, String notificationId) throws RegistryServiceException { + return registryService.getNotification(gatewayId, notificationId); } @Override - public List getAllNotifications(String gatewayId) throws RegistryServiceException, TException { - try { - List notifications = notificationRepository.getAllGatewayNotifications(gatewayId); - return notifications; - } catch (RegistryException e) { - logger.error("Error while getting all notifications", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while getting all notifications. More info : " + e.getMessage()); - throw exception; - } + public List getAllNotifications(String gatewayId) throws RegistryServiceException { + return registryService.getAllNotifications(gatewayId); } /** @@ -302,24 +181,8 @@ public List getAllNotifications(String gatewayId) throws RegistryS * project data model will be returned. */ @Override - public Project getProject(String projectId) throws RegistryServiceException, TException { - try { - if (!projectRepository.isProjectExist(projectId)) { - logger.error("Project does not exist in the system. Please provide a valid project ID..."); - ProjectNotFoundException exception = new ProjectNotFoundException(); - exception.setMessage("Project does not exist in the system. Please provide a valid project ID..."); - throw exception; - } - logger.debug("Airavata retrieved project with project Id : " + projectId); - - Project project = projectRepository.getProject(projectId); - return project; - } catch (RegistryException e) { - logger.error("Error while retrieving the project", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving the project. More info : " + e.getMessage()); - throw exception; - } + public Project getProject(String projectId) throws RegistryServiceException, ProjectNotFoundException { + return registryService.getProject(projectId); } /** @@ -333,24 +196,8 @@ public Project getProject(String projectId) throws RegistryServiceException, TEx * NOTE: This method is not used within gateways connected with Airavata. */ @Override - public boolean deleteProject(String projectId) throws RegistryServiceException, TException { - try { - if (!projectRepository.isProjectExist(projectId)) { - logger.error("Project does not exist in the system. Please provide a valid project ID..."); - ProjectNotFoundException exception = new ProjectNotFoundException(); - exception.setMessage("Project does not exist in the system. Please provide a valid project ID..."); - throw exception; - } - - projectRepository.removeProject(projectId); - logger.debug("Airavata deleted project with project Id : " + projectId); - return true; - } catch (RegistryException e) { - logger.error("Error while removing the project", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while removing the project. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteProject(String projectId) throws RegistryServiceException, ProjectNotFoundException { + return registryService.deleteProject(projectId); } /** @@ -364,40 +211,8 @@ public boolean deleteProject(String projectId) throws RegistryServiceException, */ @Override public List getUserProjects(String gatewayId, String userName, int limit, int offset) - throws RegistryServiceException, TException { - if (!validateString(userName)) { - logger.error("Username cannot be empty. Please provide a valid user.."); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Username cannot be empty. Please provide a valid user.."); - throw exception; - } - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - List projects = new ArrayList<>(); - try { - if (!userRepository.isUserExists(gatewayId, userName)) { - logger.warn("User does not exist in the system. Please provide a valid user.."); - return projects; - } - Map filters = new HashMap<>(); - filters.put(Constants.FieldConstants.ProjectConstants.OWNER, userName); - filters.put(Constants.FieldConstants.ProjectConstants.GATEWAY_ID, gatewayId); - projects = projectRepository.searchProjects( - filters, - limit, - offset, - Constants.FieldConstants.ProjectConstants.CREATION_TIME, - ResultOrderType.DESC); - logger.debug("Airavata retrieved projects for user : " + userName + " and gateway id : " + gatewayId); - return projects; - } catch (RegistryException e) { - logger.error("Error while retrieving projects", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving projects. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getUserProjects(gatewayId, userName, limit, offset); } /** @@ -419,45 +234,17 @@ public ExperimentStatistics getExperimentStatistics( List accessibleExpIds, int limit, int offset) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - // FIXME: for now allowing to pass null accessibleExpIds (only admin users should call this method) - // if (accessibleExpIds == null) { - // logger.debug("accessibleExpIds is null, defaulting to an empty list"); - // accessibleExpIds = Collections.emptyList(); - // } - try { - Map filters = new HashMap<>(); - filters.put(Constants.FieldConstants.ExperimentConstants.GATEWAY_ID, gatewayId); - filters.put(Constants.FieldConstants.ExperimentConstants.FROM_DATE, fromTime + ""); - filters.put(Constants.FieldConstants.ExperimentConstants.TO_DATE, toTime + ""); - if (userName != null) { - filters.put(Constants.FieldConstants.ExperimentConstants.USER_NAME, userName); - } - if (applicationName != null) { - filters.put(Constants.FieldConstants.ExperimentConstants.EXECUTION_ID, applicationName); - } - if (resourceHostName != null) { - filters.put(Constants.FieldConstants.ExperimentConstants.RESOURCE_HOST_ID, resourceHostName); - } - - // Cap the max returned experiment summaries at 1000 - limit = Math.min(limit, 1000); - - ExperimentStatistics result = experimentSummaryRepository.getAccessibleExperimentStatistics( - accessibleExpIds, filters, limit, offset); - logger.debug("Airavata retrieved experiments for gateway id : " + gatewayId + " between : " - + AiravataUtils.getTime(fromTime) + " and " + AiravataUtils.getTime(toTime)); - return result; - } catch (Exception e) { - logger.error("Error while retrieving experiments", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving experiments. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getExperimentStatistics( + gatewayId, + fromTime, + toTime, + userName, + applicationName, + resourceHostName, + accessibleExpIds, + limit, + offset); } /** @@ -471,41 +258,8 @@ public ExperimentStatistics getExperimentStatistics( */ @Override public List getExperimentsInProject(String gatewayId, String projectId, int limit, int offset) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - if (!validateString(projectId)) { - logger.error("Project id cannot be empty. Please provide a valid project ID..."); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Project id cannot be empty. Please provide a valid project ID..."); - throw exception; - } - try { - if (!projectRepository.isProjectExist(projectId)) { - logger.error("Project does not exist in the system. Please provide a valid project ID..."); - ProjectNotFoundException exception = new ProjectNotFoundException(); - exception.setMessage("Project does not exist in the system. Please provide a valid project ID..."); - throw exception; - } - - List experiments = experimentRepository.getExperimentList( - gatewayId, - Constants.FieldConstants.ExperimentConstants.PROJECT_ID, - projectId, - limit, - offset, - Constants.FieldConstants.ExperimentConstants.CREATION_TIME, - ResultOrderType.DESC); - logger.debug("Airavata retrieved experiments for project : " + projectId); - return experiments; - } catch (Exception e) { - logger.error("Error while retrieving the experiments", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving the experiments. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getExperimentsInProject(gatewayId, projectId, limit, offset); } /** @@ -519,40 +273,8 @@ public List getExperimentsInProject(String gatewayId, String pr */ @Override public List getUserExperiments(String gatewayId, String userName, int limit, int offset) - throws RegistryServiceException, TException { - if (!validateString(userName)) { - logger.error("Username cannot be empty. Please provide a valid user.."); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Username cannot be empty. Please provide a valid user.."); - throw exception; - } - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - List experiments = new ArrayList(); - try { - if (!userRepository.isUserExists(gatewayId, userName)) { - logger.warn("User does not exist in the system. Please provide a valid user.."); - return experiments; - } - experiments = experimentRepository.getExperimentList( - gatewayId, - Constants.FieldConstants.ExperimentConstants.USER_NAME, - userName, - limit, - offset, - Constants.FieldConstants.ExperimentConstants.CREATION_TIME, - ResultOrderType.DESC); - logger.debug("Airavata retrieved experiments for user : " + userName); - return experiments; - } catch (Exception e) { - logger.error("Error while retrieving the experiments", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving the experiments. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getUserExperiments(gatewayId, userName, limit, offset); } /** @@ -563,28 +285,8 @@ public List getUserExperiments(String gatewayId, String userNam * Identifier for the success or failure of the deletion operation. */ @Override - public boolean deleteExperiment(String experimentId) throws RegistryServiceException, TException { - try { - if (!experimentRepository.isExperimentExist(experimentId)) { - throw new ExperimentNotFoundException( - "Requested experiment id " + experimentId + " does not exist in the system.."); - } - ExperimentModel experimentModel = experimentRepository.getExperiment(experimentId); - - if (!(experimentModel.getExperimentStatus().get(0).getState() == ExperimentState.CREATED)) { - logger.error("Error while deleting the experiment"); - throw new ExperimentCatalogException( - "Experiment is not in CREATED state. Hence cannot deleted. ID:" + experimentId); - } - experimentRepository.removeExperiment(experimentId); - logger.debug("Airavata removed experiment with experiment id : " + experimentId); - return true; - } catch (Exception e) { - logger.error("Error while deleting the experiment", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting the experiment. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteExperiment(String experimentId) throws RegistryServiceException { + return registryService.deleteExperiment(experimentId); } /** @@ -626,7 +328,8 @@ public boolean deleteExperiment(String experimentId) throws RegistryServiceExcep * @param airavataExperimentId */ @Override - public ExperimentModel getExperiment(String airavataExperimentId) throws RegistryServiceException, TException { + public ExperimentModel getExperiment(String airavataExperimentId) + throws RegistryServiceException, ExperimentNotFoundException { ExperimentModel experimentModel = getExperimentInternal(airavataExperimentId); return experimentModel; } @@ -657,43 +360,8 @@ public ExperimentModel getExperiment(String airavataExperimentId) throws Registr * rather an Airavata Administrator will be notified to take corrective action. */ @Override - public ExperimentModel getDetailedExperimentTree(String airavataExperimentId) - throws RegistryServiceException, TException { - try { - ExperimentModel experimentModel = getExperimentInternal(airavataExperimentId); - List processList = processRepository.getProcessList( - Constants.FieldConstants.ExperimentConstants.EXPERIMENT_ID, experimentModel.getExperimentId()); - if (processList != null) { - processList.stream().forEach(p -> { - // Process already has the task object - (p).getTasks().stream().forEach(t -> { - try { - List jobList = jobRepository.getJobList( - Constants.FieldConstants.JobConstants.TASK_ID, ((TaskModel) t).getTaskId()); - if (jobList != null) { - Collections.sort(jobList, new Comparator() { - @Override - public int compare(JobModel o1, JobModel o2) { - return (int) (o1.getCreationTime() - o2.getCreationTime()); - } - }); - t.setJobs(jobList); - } - } catch (RegistryException e) { - logger.error(e.getMessage(), e); - } - }); - }); - experimentModel.setProcesses(processList); - } - logger.debug("Airavata retrieved detailed experiment with experiment id : " + airavataExperimentId); - return experimentModel; - } catch (Exception e) { - logger.error("Error while retrieving the experiment", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving the experiment. More info : " + e.getMessage()); - throw exception; - } + public ExperimentModel getDetailedExperimentTree(String airavataExperimentId) throws RegistryServiceException { + return registryService.getDetailedExperimentTree(airavataExperimentId); } /** @@ -706,11 +374,8 @@ public int compare(JobModel o1, JobModel o2) { * ExperimentStatus model with the current status will be returned. */ @Override - public ExperimentStatus getExperimentStatus(String airavataExperimentId) - throws RegistryServiceException, TException { - ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); - logger.debug("Airavata retrieved experiment status for experiment id : " + airavataExperimentId); - return experimentStatus; + public ExperimentStatus getExperimentStatus(String airavataExperimentId) throws RegistryServiceException { + return registryService.getExperimentStatus(airavataExperimentId); } /** @@ -723,24 +388,8 @@ public ExperimentStatus getExperimentStatus(String airavataExperimentId) */ @Override public List getExperimentOutputs(String airavataExperimentId) - throws RegistryServiceException, TException { - try { - if (!experimentRepository.isExperimentExist(airavataExperimentId)) { - logger.error( - airavataExperimentId, - "Get experiment outputs failed, experiment {} doesn't exit.", - airavataExperimentId); - throw new ExperimentNotFoundException( - "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); - } - logger.debug("Airavata retrieved experiment outputs for experiment id : " + airavataExperimentId); - return experimentOutputRepository.getExperimentOutputs(airavataExperimentId); - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while retrieving the experiment outputs", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving the experiment outputs. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getExperimentOutputs(airavataExperimentId); } /** @@ -753,8 +402,8 @@ public List getExperimentOutputs(String airavataExperiment */ @Override public List getIntermediateOutputs(String airavataExperimentId) - throws RegistryServiceException, TException { - return null; + throws RegistryServiceException { + return registryService.getIntermediateOutputs(airavataExperimentId); } /** @@ -765,505 +414,159 @@ public List getIntermediateOutputs(String airavataExperime * Job status (string) for all all the existing jobs for the experiment will be returned in the form of a map */ @Override - public Map getJobStatuses(String airavataExperimentId) - throws RegistryServiceException, TException { - try { - if (!experimentRepository.isExperimentExist(airavataExperimentId)) { - logger.error( - airavataExperimentId, - "Error while retrieving job details, experiment {} doesn't exist.", - airavataExperimentId); - throw new ExperimentNotFoundException( - "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); - } - List processModels = processRepository.getProcessList( - Constants.FieldConstants.ProcessConstants.EXPERIMENT_ID, airavataExperimentId); - Map jobStatus = new HashMap(); - if (processModels != null && !processModels.isEmpty()) { - for (ProcessModel processModel : processModels) { - List tasks = processModel.getTasks(); - if (tasks != null && !tasks.isEmpty()) { - for (TaskModel task : tasks) { - String taskId = task.getTaskId(); - List jobs = - jobRepository.getJobList(Constants.FieldConstants.JobConstants.TASK_ID, taskId); - if (jobs != null && !jobs.isEmpty()) { - for (JobModel jobModel : jobs) { - String jobID = jobModel.getJobId(); - List status = jobModel.getJobStatuses(); - if (status != null && status.size() > 0) { - JobStatus latestStatus = status.get(status.size() - 1); - jobStatus.put(jobID, latestStatus); - } - } - } - } - } - } - } - logger.debug("Airavata retrieved job statuses for experiment with experiment id : " + airavataExperimentId); - return jobStatus; - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while retrieving the job statuses", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving the job statuses. More info : " + e.getMessage()); - throw exception; - } + public Map getJobStatuses(String airavataExperimentId) throws RegistryServiceException { + return registryService.getJobStatuses(airavataExperimentId); } @Override public void addExperimentProcessOutputs(String outputType, List outputs, String id) - throws RegistryServiceException, TException { - - try { - if (ExpCatChildDataType.PROCESS_OUTPUT.equals(ExpCatChildDataType.valueOf(outputType))) { - processOutputRepository.addProcessOutputs(outputs, id); - } else if (ExpCatChildDataType.EXPERIMENT_OUTPUT.equals(ExpCatChildDataType.valueOf(outputType))) { - experimentOutputRepository.addExperimentOutputs(outputs, id); - } - } catch (Exception e) { - logger.error(id, "Error while adding outputs", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding outputs. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + registryService.addExperimentProcessOutputs(outputType, outputs, id); } @Override - public void addErrors(String errorType, ErrorModel errorModel, String id) - throws RegistryServiceException, TException { - - try { - if (ExpCatChildDataType.EXPERIMENT_ERROR.equals(ExpCatChildDataType.valueOf(errorType))) { - experimentErrorRepository.addExperimentError(errorModel, id); - } else if (ExpCatChildDataType.TASK_ERROR.equals(ExpCatChildDataType.valueOf(errorType))) { - taskErrorRepository.addTaskError(errorModel, id); - } else if (ExpCatChildDataType.PROCESS_ERROR.equals(ExpCatChildDataType.valueOf(errorType))) { - processErrorRepository.addProcessError(errorModel, id); - } - } catch (Exception e) { - logger.error(id, "Error while adding error", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding error. More info : " + e.getMessage()); - throw exception; - } + public void addErrors(String errorType, ErrorModel errorModel, String id) throws RegistryServiceException { + registryService.addErrors(errorType, errorModel, id); } @Override - public void addTaskStatus(TaskStatus taskStatus, String taskId) throws RegistryServiceException, TException { - try { - taskStatusRepository.addTaskStatus(taskStatus, taskId); - } catch (Exception e) { - logger.error(taskId, "Error while adding task status", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding task status. More info : " + e.getMessage()); - throw exception; - } + public void addTaskStatus(TaskStatus taskStatus, String taskId) throws RegistryServiceException { + registryService.addTaskStatus(taskStatus, taskId); } @Override - public void addProcessStatus(ProcessStatus processStatus, String processId) - throws RegistryServiceException, TException { - try { - processStatusRepository.addProcessStatus(processStatus, processId); - } catch (Exception e) { - logger.error(processId, "Error while adding process status", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding process status. More info : " + e.getMessage()); - throw exception; - } + public void addProcessStatus(ProcessStatus processStatus, String processId) throws RegistryServiceException { + registryService.addProcessStatus(processStatus, processId); } @Override - public void updateProcessStatus(ProcessStatus processStatus, String processId) - throws RegistryServiceException, TException { - try { - processStatusRepository.updateProcessStatus(processStatus, processId); - } catch (Exception e) { - logger.error(processId, "Error while updating process status", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating process status. More info : " + e.getMessage()); - throw exception; - } + public void updateProcessStatus(ProcessStatus processStatus, String processId) throws RegistryServiceException { + registryService.updateProcessStatus(processStatus, processId); } @Override public void updateExperimentStatus(ExperimentStatus experimentStatus, String experimentId) - throws RegistryServiceException, TException { - try { - experimentStatusRepository.updateExperimentStatus(experimentStatus, experimentId); - } catch (Exception e) { - logger.error(experimentId, "Error while updating experiment status", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating experiment status. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + registryService.updateExperimentStatus(experimentStatus, experimentId); } @Override - public void addJobStatus(JobStatus jobStatus, String taskId, String jobId) - throws RegistryServiceException, TException { - try { - JobPK jobPK = new JobPK(); - jobPK.setJobId(jobId); - jobPK.setTaskId(taskId); - jobStatusRepository.addJobStatus(jobStatus, jobPK); - } catch (Exception e) { - logger.error(jobId, "Error while adding job status", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding job status. More info : " + e.getMessage()); - throw exception; - } + public void addJobStatus(JobStatus jobStatus, String taskId, String jobId) throws RegistryServiceException { + registryService.addJobStatus(jobStatus, taskId, jobId); } @Override - public void addJob(JobModel jobModel, String processId) throws RegistryServiceException, TException { - try { - jobRepository.addJob(jobModel, processId); - } catch (Exception e) { - logger.error(processId, "Error while adding job ", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding job. More info : " + e.getMessage()); - throw exception; - } + public void addJob(JobModel jobModel, String processId) throws RegistryServiceException { + registryService.addJob(jobModel, processId); } @Override - public void deleteJobs(String processId) throws RegistryServiceException, TException { - try { - List jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.PROCESS_ID, processId); - for (JobModel jobModel : jobs) { - jobRepository.removeJob(jobModel); - } - } catch (Exception e) { - logger.error(processId, "Error while deleting job ", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while deleting job. More info : " + e.getMessage()); - throw exception; - } + public void deleteJobs(String processId) throws RegistryServiceException { + registryService.deleteJobs(processId); } @Override - public String addProcess(ProcessModel processModel, String experimentId) - throws RegistryServiceException, TException { - try { - return processRepository.addProcess(processModel, experimentId); - } catch (Exception e) { - logger.error(experimentId, "Error while adding process ", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding process. More info : " + e.getMessage()); - throw exception; - } + public String addProcess(ProcessModel processModel, String experimentId) throws RegistryServiceException { + return registryService.addProcess(processModel, experimentId); } @Override - public void updateProcess(ProcessModel processModel, String processId) throws RegistryServiceException, TException { - try { - processRepository.updateProcess(processModel, processId); - } catch (Exception e) { - logger.error(processId, "Error while updating process ", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while updating process. More info : " + e.getMessage()); - throw exception; - } + public void updateProcess(ProcessModel processModel, String processId) throws RegistryServiceException { + registryService.updateProcess(processModel, processId); } @Override - public String addTask(TaskModel taskModel, String processId) throws RegistryServiceException, TException { - try { - return taskRepository.addTask(taskModel, processId); - } catch (Exception e) { - logger.error(processId, "Error while adding task ", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding task. More info : " + e.getMessage()); - throw exception; - } + public String addTask(TaskModel taskModel, String processId) throws RegistryServiceException { + return registryService.addTask(taskModel, processId); } @Override - public void deleteTasks(String processId) throws RegistryServiceException, TException { - try { - taskRepository.deleteTasks(processId); - } catch (Exception e) { - logger.error(processId, "Error while adding task ", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding task. More info : " + e.getMessage()); - throw exception; - } + public void deleteTasks(String processId) throws RegistryServiceException { + registryService.deleteTasks(processId); } @Override - public UserConfigurationDataModel getUserConfigurationData(String experimentId) - throws RegistryServiceException, TException { - try { - return experimentRepository.getUserConfigurationData(experimentId); - } catch (Exception e) { - logger.error(experimentId, "Error while getting user configuration ", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding task. More info : " + e.getMessage()); - throw exception; - } + public UserConfigurationDataModel getUserConfigurationData(String experimentId) throws RegistryServiceException { + return registryService.getUserConfigurationData(experimentId); } @Override - public ProcessModel getProcess(String processId) throws RegistryServiceException, TException { - try { - return processRepository.getProcess(processId); - } catch (Exception e) { - logger.error(processId, "Error while retrieving user configuration ", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving user configuration. More info : " + e.getMessage()); - throw exception; - } + public ProcessModel getProcess(String processId) throws RegistryServiceException { + return registryService.getProcess(processId); } @Override - public List getProcessList(String experimentId) throws RegistryServiceException, TException { - try { - List processModels = processRepository.getProcessList( - Constants.FieldConstants.ExperimentConstants.EXPERIMENT_ID, experimentId); - return processModels; - - } catch (Exception e) { - logger.error(experimentId, "Error while retrieving process list ", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving process list. More info : " + e.getMessage()); - throw exception; - } + public List getProcessList(String experimentId) throws RegistryServiceException { + return registryService.getProcessList(experimentId); } @Override - public ProcessStatus getProcessStatus(String processId) throws RegistryServiceException, TException { - try { - return processStatusRepository.getProcessStatus(processId); - } catch (Exception e) { - logger.error(processId, "Error while retrieving process status", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving process status. More info : " + e.getMessage()); - throw exception; - } + public ProcessStatus getProcessStatus(String processId) throws RegistryServiceException { + return registryService.getProcessStatus(processId); } @Override - public List getProcessListInState(ProcessState processState) - throws RegistryServiceException, TException { - try { - - List finalProcessList = new ArrayList<>(); - int offset = 0; - int limit = 100; - int count = 0; - do { - List processStatusList = - processStatusRepository.getProcessStatusList(processState, offset, limit); - offset += processStatusList.size(); - count = processStatusList.size(); - for (ProcessStatus processStatus : processStatusList) { - ProcessStatus latestStatus = processStatusRepository.getProcessStatus(processStatus.getProcessId()); - if (latestStatus.getState().name().equals(processState.name())) { - finalProcessList.add(processRepository.getProcess(latestStatus.getProcessId())); - } - } - } while (count == limit); - return finalProcessList; - } catch (Exception e) { - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while retrieving process list with given status. More info : " + e.getMessage()); - throw exception; - } + public List getProcessListInState(ProcessState processState) throws RegistryServiceException { + return registryService.getProcessListInState(processState); } @Override - public List getProcessStatusList(String processId) throws RegistryServiceException, TException { - try { - return processStatusRepository.getProcessStatusList(processId); - } catch (Exception e) { - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while retrieving process status list for given process Id. More info : " + e.getMessage()); - throw exception; - } + public List getProcessStatusList(String processId) throws RegistryServiceException { + return registryService.getProcessStatusList(processId); } /** * queryType can be PROCESS_ID or TASK_ID */ @Override - public boolean isJobExist(String queryType, String id) throws RegistryServiceException, TException { - try { - JobModel jobModel = fetchJobModel(queryType, id); - return jobModel != null; - } catch (Exception e) { - logger.error(id, "Error while retrieving job", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving job. More info : " + e.getMessage()); - throw exception; - } + public boolean isJobExist(String queryType, String id) throws RegistryServiceException { + return registryService.isJobExist(queryType, id); } /** * queryType can be PROCESS_ID or TASK_ID */ @Override - public JobModel getJob(String queryType, String id) throws RegistryServiceException, TException { - try { - JobModel jobModel = fetchJobModel(queryType, id); - if (jobModel != null) return jobModel; - throw new Exception("Job not found for queryType: " + queryType + ", id: " + id); - } catch (Exception e) { - logger.error(id, "Error while retrieving job", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving job. More info : " + e.getMessage()); - throw exception; - } + public JobModel getJob(String queryType, String id) throws RegistryServiceException { + return registryService.getJob(queryType, id); } @Override - public List getJobs(String queryType, String id) throws RegistryServiceException, TException { - - try { - return fetchJobModels(queryType, id); - } catch (Exception e) { - logger.error(id, "Error while retrieving jobs for query " + queryType + " and id " + id, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving jobs for query " + queryType + " and id " + id - + ". More info : " + e.getMessage()); - throw exception; - } + public List getJobs(String queryType, String id) throws RegistryServiceException { + return registryService.getJobs(queryType, id); } @Override public int getJobCount( org.apache.airavata.model.status.JobStatus jobStatus, String gatewayId, double searchBackTimeInMinutes) - throws RegistryServiceException, TException { - - List jobStatusList = jobStatusRepository.getDistinctListofJobStatus( - gatewayId, jobStatus.getJobState().name(), searchBackTimeInMinutes); - return jobStatusList.size(); + throws RegistryServiceException { + return registryService.getJobCount(jobStatus, gatewayId, searchBackTimeInMinutes); } @Override public Map getAVGTimeDistribution(String gatewayId, double searchBackTimeInMinutes) - throws RegistryServiceException, TException { - return processRepository.getAVGTimeDistribution(gatewayId, searchBackTimeInMinutes); - } - - private JobModel fetchJobModel(String queryType, String id) throws RegistryException { - if (queryType.equals(Constants.FieldConstants.JobConstants.TASK_ID)) { - List jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.TASK_ID, id); - if (jobs != null) { - for (JobModel jobModel : jobs) { - if (jobModel.getJobId() != null || !jobModel.equals("")) { - return jobModel; - } - } - } - } else if (queryType.equals(Constants.FieldConstants.JobConstants.PROCESS_ID)) { - List jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.PROCESS_ID, id); - if (jobs != null) { - for (JobModel jobModel : jobs) { - if (jobModel.getJobId() != null || !jobModel.equals("")) { - return jobModel; - } - } - } - } - return null; - } - - private List fetchJobModels(String queryType, String id) throws RegistryException { - List jobs = new ArrayList<>(); - switch (queryType) { - case Constants.FieldConstants.JobConstants.TASK_ID: - jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.TASK_ID, id); - break; - case Constants.FieldConstants.JobConstants.PROCESS_ID: - jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.PROCESS_ID, id); - break; - case Constants.FieldConstants.JobConstants.JOB_ID: - jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.JOB_ID, id); - break; - } - return jobs; + throws RegistryServiceException { + return registryService.getAVGTimeDistribution(gatewayId, searchBackTimeInMinutes); } @Override - public List getProcessOutputs(String processId) throws RegistryServiceException, TException { - try { - return processOutputRepository.getProcessOutputs(processId); - } catch (Exception e) { - logger.error("Error while retrieving process outputs for process id " + processId, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving process outputs. More info : " + e.getMessage()); - throw exception; - } + public List getProcessOutputs(String processId) throws RegistryServiceException { + return registryService.getProcessOutputs(processId); } @Override - public List getProcessWorkflows(String processId) throws RegistryServiceException, TException { - - try { - return processWorkflowRepository.getProcessWorkflows(processId); - } catch (Exception e) { - logger.error("Error while retrieving process workflows for process id " + processId, e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving process workflows for process id " + processId - + ". More info : " + e.getMessage()); - throw exception; - } + public List getProcessWorkflows(String processId) throws RegistryServiceException { + return registryService.getProcessWorkflows(processId); } @Override - public void addProcessWorkflow(ProcessWorkflow processWorkflow) throws RegistryServiceException, TException { - try { - processWorkflowRepository.addProcessWorkflow(processWorkflow, processWorkflow.getProcessId()); - } catch (Exception e) { - logger.error("Error while adding process workflows for process id " + processWorkflow.getProcessId(), e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding process workflows for process id " + processWorkflow.getProcessId() - + ". More info : " + e.getMessage()); - throw exception; - } + public void addProcessWorkflow(ProcessWorkflow processWorkflow) throws RegistryServiceException { + registryService.addProcessWorkflow(processWorkflow); } @Override - public List getProcessIds(String experimentId) throws RegistryServiceException, TException { - try { - return processRepository.getProcessIds(DBConstants.Process.EXPERIMENT_ID, experimentId); - } catch (Exception e) { - logger.error(experimentId, "Error while retrieving process ids", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving process ids. More info : " + e.getMessage()); - throw exception; - } + public List getProcessIds(String experimentId) throws RegistryServiceException { + return registryService.getProcessIds(experimentId); } /** @@ -1274,40 +577,8 @@ public List getProcessIds(String experimentId) throws RegistryServiceExc * Job details. */ @Override - public List getJobDetails(String airavataExperimentId) throws RegistryServiceException, TException { - try { - if (!experimentRepository.isExperimentExist(airavataExperimentId)) { - logger.error( - airavataExperimentId, - "Error while retrieving job details, experiment {} doesn't exist.", - airavataExperimentId); - throw new ExperimentNotFoundException( - "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); - } - List processModels = processRepository.getProcessList( - Constants.FieldConstants.ProcessConstants.EXPERIMENT_ID, airavataExperimentId); - List jobList = new ArrayList<>(); - if (processModels != null && !processModels.isEmpty()) { - for (ProcessModel processModel : processModels) { - List tasks = processModel.getTasks(); - if (tasks != null && !tasks.isEmpty()) { - for (TaskModel taskModel : tasks) { - String taskId = taskModel.getTaskId(); - List taskJobs = - jobRepository.getJobList(Constants.FieldConstants.JobConstants.TASK_ID, taskId); - jobList.addAll(taskJobs); - } - } - } - } - logger.debug("Airavata retrieved job models for experiment with experiment id : " + airavataExperimentId); - return jobList; - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while retrieving the job details", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving the job details. More info : " + e.getMessage()); - throw exception; - } + public List getJobDetails(String airavataExperimentId) throws RegistryServiceException { + return registryService.getJobDetails(airavataExperimentId); } /** @@ -1318,17 +589,8 @@ public List getJobDetails(String airavataExperimentId) throws Registry * Returns an Application Module Object. */ @Override - public ApplicationModule getApplicationModule(String appModuleId) throws RegistryServiceException, TException { - try { - ApplicationModule module = applicationInterfaceRepository.getApplicationModule(appModuleId); - logger.debug("Airavata retrieved application module with module id : " + appModuleId); - return module; - } catch (AppCatalogException e) { - logger.error(appModuleId, "Error while retrieving application module...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving the adding application module. More info : " + e.getMessage()); - throw exception; - } + public ApplicationModule getApplicationModule(String appModuleId) throws RegistryServiceException { + return registryService.getApplicationModule(appModuleId); } /** @@ -1339,21 +601,8 @@ public ApplicationModule getApplicationModule(String appModuleId) throws Registr * Returns the list of all Application Module Objects. */ @Override - public List getAllAppModules(String gatewayId) throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - try { - List moduleList = applicationInterfaceRepository.getAllApplicationModules(gatewayId); - logger.debug("Airavata retrieved modules for gateway id : " + gatewayId); - return moduleList; - } catch (AppCatalogException e) { - logger.error("Error while retrieving all application modules...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving all application modules. More info : " + e.getMessage()); - throw exception; - } + public List getAllAppModules(String gatewayId) throws RegistryServiceException { + return registryService.getAllAppModules(gatewayId); } /** @@ -1367,22 +616,8 @@ public List getAllAppModules(String gatewayId) throws Registr @Override public List getAccessibleAppModules( String gatewayId, List accessibleAppIds, List accessibleComputeResourceIds) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - try { - List moduleList = applicationInterfaceRepository.getAccessibleApplicationModules( - gatewayId, accessibleAppIds, accessibleComputeResourceIds); - logger.debug("Airavata retrieved modules for gateway id : " + gatewayId); - return moduleList; - } catch (AppCatalogException e) { - logger.error("Error while retrieving all application modules...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving all application modules. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getAccessibleAppModules(gatewayId, accessibleAppIds, accessibleComputeResourceIds); } /** @@ -1393,16 +628,8 @@ public List getAccessibleAppModules( * Returns a success/failure of the deletion. */ @Override - public boolean deleteApplicationModule(String appModuleId) throws RegistryServiceException, TException { - try { - logger.debug("Airavata deleted application module with module id : " + appModuleId); - return applicationInterfaceRepository.removeApplicationModule(appModuleId); - } catch (AppCatalogException e) { - logger.error(appModuleId, "Error while deleting application module...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting the application module. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteApplicationModule(String appModuleId) throws RegistryServiceException { + return registryService.deleteApplicationModule(appModuleId); } /** @@ -1414,18 +641,8 @@ public boolean deleteApplicationModule(String appModuleId) throws RegistryServic */ @Override public ApplicationDeploymentDescription getApplicationDeployment(String appDeploymentId) - throws RegistryServiceException, TException { - try { - ApplicationDeploymentDescription deployement = - applicationDeploymentRepository.getApplicationDeployement(appDeploymentId); - logger.debug("Airavata registered application deployment for deployment id : " + appDeploymentId); - return deployement; - } catch (AppCatalogException e) { - logger.error(appDeploymentId, "Error while retrieving application deployment...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving application deployment. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getApplicationDeployment(appDeploymentId); } /** @@ -1436,17 +653,8 @@ public ApplicationDeploymentDescription getApplicationDeployment(String appDeplo * Returns a success/failure of the deletion. */ @Override - public boolean deleteApplicationDeployment(String appDeploymentId) throws RegistryServiceException, TException { - try { - applicationDeploymentRepository.removeAppDeployment(appDeploymentId); - logger.debug("Airavata removed application deployment with deployment id : " + appDeploymentId); - return true; - } catch (AppCatalogException e) { - logger.error(appDeploymentId, "Error while deleting application deployment...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting application deployment. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteApplicationDeployment(String appDeploymentId) throws RegistryServiceException { + return registryService.deleteApplicationDeployment(appDeploymentId); } /** @@ -1459,22 +667,8 @@ public boolean deleteApplicationDeployment(String appDeploymentId) throws Regist */ @Override public List getAllApplicationDeployments(String gatewayId) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - try { - List deployements = - applicationDeploymentRepository.getAllApplicationDeployements(gatewayId); - logger.debug("Airavata retrieved application deployments for gateway id : " + gatewayId); - return deployements; - } catch (AppCatalogException e) { - logger.error("Error while retrieving application deployments...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving application deployments. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getAllApplicationDeployments(gatewayId); } /** @@ -1488,23 +682,9 @@ public List getAllApplicationDeployments(Strin @Override public List getAccessibleApplicationDeployments( String gatewayId, List accessibleAppDeploymentIds, List accessibleComputeResourceIds) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - try { - List deployements = - applicationDeploymentRepository.getAccessibleApplicationDeployments( - gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds); - logger.debug("Airavata retrieved application deployments for gateway id : " + gatewayId); - return deployements; - } catch (AppCatalogException e) { - logger.error("Error while retrieving application deployments...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving application deployments. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getAccessibleApplicationDeployments( + gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds); } /** @@ -1523,22 +703,9 @@ public List getAccessibleApplicationDeployment String appModuleId, List accessibleAppDeploymentIds, List accessibleComputeResourceIds) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - try { - List deployments = - applicationDeploymentRepository.getAccessibleApplicationDeployments( - gatewayId, appModuleId, accessibleAppDeploymentIds, accessibleComputeResourceIds); - return deployments; - } catch (AppCatalogException e) { - logger.error("Error while retrieving application deployments...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving application deployments. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getAccessibleApplicationDeploymentsForAppModule( + gatewayId, appModuleId, accessibleAppDeploymentIds, accessibleComputeResourceIds); } /** @@ -1549,41 +716,14 @@ public List getAccessibleApplicationDeployment * Returns a list of Deployed Resources. */ @Override - public List getAppModuleDeployedResources(String appModuleId) throws RegistryServiceException, TException { - try { - List appDeployments = new ArrayList<>(); - Map filters = new HashMap<>(); - filters.put(DBConstants.ApplicationDeployment.APPLICATION_MODULE_ID, appModuleId); - List applicationDeployments = - applicationDeploymentRepository.getApplicationDeployments(filters); - for (ApplicationDeploymentDescription description : applicationDeployments) { - appDeployments.add(description.getAppDeploymentId()); - } - logger.debug("Airavata retrieved application deployments for module id : " + appModuleId); - return appDeployments; - } catch (AppCatalogException e) { - logger.error(appModuleId, "Error while retrieving application deployments...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving application deployment. More info : " + e.getMessage()); - throw exception; - } + public List getAppModuleDeployedResources(String appModuleId) throws RegistryServiceException { + return registryService.getAppModuleDeployedResources(appModuleId); } @Override public List getApplicationDeployments(String appModuleId) - throws RegistryServiceException, TException { - try { - Map filters = new HashMap<>(); - filters.put(DBConstants.ApplicationDeployment.APPLICATION_MODULE_ID, appModuleId); - List applicationDeployments = - applicationDeploymentRepository.getApplicationDeployments(filters); - return applicationDeployments; - } catch (AppCatalogException e) { - logger.error(appModuleId, "Error while retrieving application deployments...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving application deployment. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getApplicationDeployments(appModuleId); } /** @@ -1595,18 +735,8 @@ public List getApplicationDeployments(String a */ @Override public ApplicationInterfaceDescription getApplicationInterface(String appInterfaceId) - throws RegistryServiceException, TException { - try { - ApplicationInterfaceDescription interfaceDescription = - applicationInterfaceRepository.getApplicationInterface(appInterfaceId); - logger.debug("Airavata retrieved application interface with interface id : " + appInterfaceId); - return interfaceDescription; - } catch (AppCatalogException e) { - logger.error(appInterfaceId, "Error while retrieving application interface...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving application interface. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getApplicationInterface(appInterfaceId); } /** @@ -1617,18 +747,8 @@ public ApplicationInterfaceDescription getApplicationInterface(String appInterfa * Returns a success/failure of the deletion. */ @Override - public boolean deleteApplicationInterface(String appInterfaceId) throws RegistryServiceException, TException { - try { - boolean removeApplicationInterface = - applicationInterfaceRepository.removeApplicationInterface(appInterfaceId); - logger.debug("Airavata removed application interface with interface id : " + appInterfaceId); - return removeApplicationInterface; - } catch (AppCatalogException e) { - logger.error(appInterfaceId, "Error while deleting application interface...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting application interface. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteApplicationInterface(String appInterfaceId) throws RegistryServiceException { + return registryService.deleteApplicationInterface(appInterfaceId); } /** @@ -1639,31 +759,8 @@ public boolean deleteApplicationInterface(String appInterfaceId) throws Registry * Returns a list of application interfaces with corresponsing ID's */ @Override - public Map getAllApplicationInterfaceNames(String gatewayId) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - try { - List allApplicationInterfaces = - applicationInterfaceRepository.getAllApplicationInterfaces(gatewayId); - Map allApplicationInterfacesMap = new HashMap<>(); - if (allApplicationInterfaces != null && !allApplicationInterfaces.isEmpty()) { - for (ApplicationInterfaceDescription interfaceDescription : allApplicationInterfaces) { - allApplicationInterfacesMap.put( - interfaceDescription.getApplicationInterfaceId(), - interfaceDescription.getApplicationName()); - } - } - logger.debug("Airavata retrieved application interfaces for gateway id : " + gatewayId); - return allApplicationInterfacesMap; - } catch (AppCatalogException e) { - logger.error("Error while retrieving application interfaces...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving application interfaces. More info : " + e.getMessage()); - throw exception; - } + public Map getAllApplicationInterfaceNames(String gatewayId) throws RegistryServiceException { + return registryService.getAllApplicationInterfaceNames(gatewayId); } /** @@ -1675,22 +772,8 @@ public Map getAllApplicationInterfaceNames(String gatewayId) */ @Override public List getAllApplicationInterfaces(String gatewayId) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - try { - List interfaces = - applicationInterfaceRepository.getAllApplicationInterfaces(gatewayId); - logger.debug("Airavata retrieved application interfaces for gateway id : " + gatewayId); - return interfaces; - } catch (AppCatalogException e) { - logger.error("Error while retrieving application interfaces...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving application interfaces. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getAllApplicationInterfaces(gatewayId); } /** @@ -1701,19 +784,8 @@ public List getAllApplicationInterfaces(String * Returns a list of application inputs. */ @Override - public List getApplicationInputs(String appInterfaceId) - throws RegistryServiceException, TException { - try { - List applicationInputs = - applicationInterfaceRepository.getApplicationInputs(appInterfaceId); - logger.debug("Airavata retrieved application inputs for application interface id : " + appInterfaceId); - return applicationInputs; - } catch (AppCatalogException e) { - logger.error(appInterfaceId, "Error while retrieving application inputs...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving application inputs. More info : " + e.getMessage()); - throw exception; - } + public List getApplicationInputs(String appInterfaceId) throws RegistryServiceException { + return registryService.getApplicationInputs(appInterfaceId); } /** @@ -1724,11 +796,8 @@ public List getApplicationInputs(String appInterfaceId) * Returns a list of application outputs. */ @Override - public List getApplicationOutputs(String appInterfaceId) - throws RegistryServiceException, TException { - List list = getApplicationOutputsInternal(appInterfaceId); - logger.debug("Airavata retrieved application outputs for app interface id : " + appInterfaceId); - return list; + public List getApplicationOutputs(String appInterfaceId) throws RegistryServiceException { + return registryService.getApplicationOutputs(appInterfaceId); } /** @@ -1741,38 +810,8 @@ public List getApplicationOutputs(String appInterfaceId) */ @Override public Map getAvailableAppInterfaceComputeResources(String appInterfaceId) - throws RegistryServiceException, TException { - try { - Map allComputeResources = - new ComputeResourceRepository().getAvailableComputeResourceIdList(); - Map availableComputeResources = new HashMap(); - ApplicationInterfaceDescription applicationInterface = - applicationInterfaceRepository.getApplicationInterface(appInterfaceId); - HashMap filters = new HashMap<>(); - List applicationModules = applicationInterface.getApplicationModules(); - if (applicationModules != null && !applicationModules.isEmpty()) { - for (String moduleId : applicationModules) { - filters.put(DBConstants.ApplicationDeployment.APPLICATION_MODULE_ID, moduleId); - List applicationDeployments = - applicationDeploymentRepository.getApplicationDeployments(filters); - for (ApplicationDeploymentDescription deploymentDescription : applicationDeployments) { - if (allComputeResources.get(deploymentDescription.getComputeHostId()) != null) { - availableComputeResources.put( - deploymentDescription.getComputeHostId(), - allComputeResources.get(deploymentDescription.getComputeHostId())); - } - } - } - } - logger.debug( - "Airavata retrieved available compute resources for application interface id : " + appInterfaceId); - return availableComputeResources; - } catch (AppCatalogException e) { - logger.error(appInterfaceId, "Error while saving compute resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while saving compute resource. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getAvailableAppInterfaceComputeResources(appInterfaceId); } /** @@ -1783,19 +822,8 @@ public Map getAvailableAppInterfaceComputeResources(String appIn * Compute Resource Object created from the datamodel.. */ @Override - public ComputeResourceDescription getComputeResource(String computeResourceId) - throws RegistryServiceException, TException { - try { - ComputeResourceDescription computeResource = - new ComputeResourceRepository().getComputeResource(computeResourceId); - logger.debug("Airavata retrieved compute resource with compute resource Id : " + computeResourceId); - return computeResource; - } catch (AppCatalogException e) { - logger.error(computeResourceId, "Error while retrieving compute resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving compute resource. More info : " + e.getMessage()); - throw exception; - } + public ComputeResourceDescription getComputeResource(String computeResourceId) throws RegistryServiceException { + return registryService.getComputeResource(computeResourceId); } /** @@ -1805,17 +833,8 @@ public ComputeResourceDescription getComputeResource(String computeResourceId) * Compute Resource Object created from the datamodel.. */ @Override - public Map getAllComputeResourceNames() throws RegistryServiceException, TException { - try { - Map computeResourceIdList = new ComputeResourceRepository().getAllComputeResourceIdList(); - logger.debug("Airavata retrieved all the available compute resources..."); - return computeResourceIdList; - } catch (AppCatalogException e) { - logger.error("Error while retrieving compute resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving compute resource. More info : " + e.getMessage()); - throw exception; - } + public Map getAllComputeResourceNames() throws RegistryServiceException { + return registryService.getAllComputeResourceNames(); } /** @@ -1826,17 +845,8 @@ public Map getAllComputeResourceNames() throws RegistryServiceEx * Returns a success/failure of the deletion. */ @Override - public boolean deleteComputeResource(String computeResourceId) throws RegistryServiceException, TException { - try { - new ComputeResourceRepository().removeComputeResource(computeResourceId); - logger.debug("Airavata deleted compute resource with compute resource Id : " + computeResourceId); - return true; - } catch (AppCatalogException e) { - logger.error(computeResourceId, "Error while deleting compute resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting compute resource. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteComputeResource(String computeResourceId) throws RegistryServiceException { + return registryService.deleteComputeResource(computeResourceId); } /** @@ -1847,19 +857,8 @@ public boolean deleteComputeResource(String computeResourceId) throws RegistrySe * Storage Resource Object created from the datamodel.. */ @Override - public StorageResourceDescription getStorageResource(String storageResourceId) - throws RegistryServiceException, TException { - try { - StorageResourceDescription storageResource = - storageResourceRepository.getStorageResource(storageResourceId); - logger.debug("Airavata retrieved storage resource with storage resource Id : " + storageResourceId); - return storageResource; - } catch (AppCatalogException e) { - logger.error(storageResourceId, "Error while retrieving storage resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving storage resource. More info : " + e.getMessage()); - throw exception; - } + public StorageResourceDescription getStorageResource(String storageResourceId) throws RegistryServiceException { + return registryService.getStorageResource(storageResourceId); } /** @@ -1869,17 +868,8 @@ public StorageResourceDescription getStorageResource(String storageResourceId) * Compute Resource Object created from the datamodel.. */ @Override - public Map getAllStorageResourceNames() throws RegistryServiceException, TException { - try { - Map resourceIdList = storageResourceRepository.getAllStorageResourceIdList(); - logger.debug("Airavata retrieved storage resources list..."); - return resourceIdList; - } catch (AppCatalogException e) { - logger.error("Error while retrieving storage resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving storage resource. More info : " + e.getMessage()); - throw exception; - } + public Map getAllStorageResourceNames() throws RegistryServiceException { + return registryService.getAllStorageResourceNames(); } /** @@ -1890,17 +880,8 @@ public Map getAllStorageResourceNames() throws RegistryServiceEx * Returns a success/failure of the deletion. */ @Override - public boolean deleteStorageResource(String storageResourceId) throws RegistryServiceException, TException { - try { - storageResourceRepository.removeStorageResource(storageResourceId); - logger.debug("Airavata deleted storage resource with storage resource Id : " + storageResourceId); - return true; - } catch (AppCatalogException e) { - logger.error(storageResourceId, "Error while deleting storage resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting storage resource. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteStorageResource(String storageResourceId) throws RegistryServiceException { + return registryService.deleteStorageResource(storageResourceId); } /** @@ -1909,18 +890,8 @@ public boolean deleteStorageResource(String storageResourceId) throws RegistrySe * @param jobSubmissionId@return LOCALSubmission instance */ @Override - public LOCALSubmission getLocalJobSubmission(String jobSubmissionId) throws RegistryServiceException, TException { - try { - LOCALSubmission localJobSubmission = new ComputeResourceRepository().getLocalJobSubmission(jobSubmissionId); - logger.debug("Airavata retrieved local job submission for job submission interface id: " + jobSubmissionId); - return localJobSubmission; - } catch (AppCatalogException e) { - String errorMsg = "Error while retrieving local job submission interface to resource compute resource..."; - logger.error(jobSubmissionId, errorMsg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(errorMsg + e.getMessage()); - throw exception; - } + public LOCALSubmission getLocalJobSubmission(String jobSubmissionId) throws RegistryServiceException { + return registryService.getLocalJobSubmission(jobSubmissionId); } /** @@ -1929,18 +900,8 @@ public LOCALSubmission getLocalJobSubmission(String jobSubmissionId) throws Regi * @param jobSubmissionId@return SSHJobSubmission instance */ @Override - public SSHJobSubmission getSSHJobSubmission(String jobSubmissionId) throws RegistryServiceException, TException { - try { - SSHJobSubmission sshJobSubmission = new ComputeResourceRepository().getSSHJobSubmission(jobSubmissionId); - logger.debug("Airavata retrieved SSH job submission for job submission interface id: " + jobSubmissionId); - return sshJobSubmission; - } catch (AppCatalogException e) { - String errorMsg = "Error while retrieving SSH job submission interface to resource compute resource..."; - logger.error(jobSubmissionId, errorMsg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(errorMsg + e.getMessage()); - throw exception; - } + public SSHJobSubmission getSSHJobSubmission(String jobSubmissionId) throws RegistryServiceException { + return registryService.getSSHJobSubmission(jobSubmissionId); } /** @@ -1956,21 +917,8 @@ public SSHJobSubmission getSSHJobSubmission(String jobSubmissionId) throws Regis * @param jobSubmissionId */ @Override - public UnicoreJobSubmission getUnicoreJobSubmission(String jobSubmissionId) - throws RegistryServiceException, TException { - try { - UnicoreJobSubmission unicoreJobSubmission = - new ComputeResourceRepository().getUNICOREJobSubmission(jobSubmissionId); - logger.debug( - "Airavata retrieved UNICORE job submission for job submission interface id: " + jobSubmissionId); - return unicoreJobSubmission; - } catch (AppCatalogException e) { - String errorMsg = "Error while retrieving Unicore job submission interface to resource compute resource..."; - logger.error(jobSubmissionId, errorMsg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(errorMsg + e.getMessage()); - throw exception; - } + public UnicoreJobSubmission getUnicoreJobSubmission(String jobSubmissionId) throws RegistryServiceException { + return registryService.getUnicoreJobSubmission(jobSubmissionId); } /** @@ -1984,20 +932,8 @@ public UnicoreJobSubmission getUnicoreJobSubmission(String jobSubmissionId) * @param jobSubmissionId */ @Override - public CloudJobSubmission getCloudJobSubmission(String jobSubmissionId) - throws RegistryServiceException, TException { - try { - CloudJobSubmission cloudJobSubmission = - new ComputeResourceRepository().getCloudJobSubmission(jobSubmissionId); - logger.debug("Airavata retrieved cloud job submission for job submission interface id: " + jobSubmissionId); - return cloudJobSubmission; - } catch (AppCatalogException e) { - String errorMsg = "Error while retrieving Cloud job submission interface to resource compute resource..."; - logger.error(jobSubmissionId, errorMsg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(errorMsg + e.getMessage()); - throw exception; - } + public CloudJobSubmission getCloudJobSubmission(String jobSubmissionId) throws RegistryServiceException { + return registryService.getCloudJobSubmission(jobSubmissionId); } /** @@ -2007,18 +943,8 @@ public CloudJobSubmission getCloudJobSubmission(String jobSubmissionId) * @return LOCALDataMovement instance */ @Override - public LOCALDataMovement getLocalDataMovement(String dataMovementId) throws RegistryServiceException, TException { - try { - LOCALDataMovement localDataMovement = new ComputeResourceRepository().getLocalDataMovement(dataMovementId); - logger.debug("Airavata retrieved local data movement with data movement id: " + dataMovementId); - return localDataMovement; - } catch (AppCatalogException e) { - String errorMsg = "Error while retrieving local data movement interface to resource compute resource..."; - logger.error(dataMovementId, errorMsg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(errorMsg + e.getMessage()); - throw exception; - } + public LOCALDataMovement getLocalDataMovement(String dataMovementId) throws RegistryServiceException { + return registryService.getLocalDataMovement(dataMovementId); } /** @@ -2028,18 +954,8 @@ public LOCALDataMovement getLocalDataMovement(String dataMovementId) throws Regi * @return SCPDataMovement instance */ @Override - public SCPDataMovement getSCPDataMovement(String dataMovementId) throws RegistryServiceException, TException { - try { - SCPDataMovement scpDataMovement = new ComputeResourceRepository().getSCPDataMovement(dataMovementId); - logger.debug("Airavata retrieved SCP data movement with data movement id: " + dataMovementId); - return scpDataMovement; - } catch (AppCatalogException e) { - String errorMsg = "Error while retrieving SCP data movement interface to resource compute resource..."; - logger.error(dataMovementId, errorMsg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(errorMsg + e.getMessage()); - throw exception; - } + public SCPDataMovement getSCPDataMovement(String dataMovementId) throws RegistryServiceException { + return registryService.getSCPDataMovement(dataMovementId); } /** @@ -2049,20 +965,8 @@ public SCPDataMovement getSCPDataMovement(String dataMovementId) throws Registry * @return UnicoreDataMovement instance */ @Override - public UnicoreDataMovement getUnicoreDataMovement(String dataMovementId) - throws RegistryServiceException, TException { - try { - UnicoreDataMovement unicoreDataMovement = - new ComputeResourceRepository().getUNICOREDataMovement(dataMovementId); - logger.debug("Airavata retrieved UNICORE data movement with data movement id: " + dataMovementId); - return unicoreDataMovement; - } catch (AppCatalogException e) { - String errorMsg = "Error while retrieving UNICORE data movement interface..."; - logger.error(dataMovementId, errorMsg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(errorMsg + e.getMessage()); - throw exception; - } + public UnicoreDataMovement getUnicoreDataMovement(String dataMovementId) throws RegistryServiceException { + return registryService.getUnicoreDataMovement(dataMovementId); } /** @@ -2072,20 +976,8 @@ public UnicoreDataMovement getUnicoreDataMovement(String dataMovementId) * @return GridFTPDataMovement instance */ @Override - public GridFTPDataMovement getGridFTPDataMovement(String dataMovementId) - throws RegistryServiceException, TException { - try { - GridFTPDataMovement gridFTPDataMovement = - new ComputeResourceRepository().getGridFTPDataMovement(dataMovementId); - logger.debug("Airavata retrieved GRIDFTP data movement with data movement id: " + dataMovementId); - return gridFTPDataMovement; - } catch (AppCatalogException e) { - String errorMsg = "Error while retrieving GridFTP data movement interface to resource compute resource..."; - logger.error(dataMovementId, errorMsg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(errorMsg + e.getMessage()); - throw exception; - } + public GridFTPDataMovement getGridFTPDataMovement(String dataMovementId) throws RegistryServiceException { + return registryService.getGridFTPDataMovement(dataMovementId); } /** @@ -2098,7 +990,7 @@ public GridFTPDataMovement getGridFTPDataMovement(String dataMovementId) */ @Override public boolean changeJobSubmissionPriority(String jobSubmissionInterfaceId, int newPriorityOrder) - throws RegistryServiceException, TException { + throws RegistryServiceException { return false; } @@ -2112,7 +1004,7 @@ public boolean changeJobSubmissionPriority(String jobSubmissionInterfaceId, int */ @Override public boolean changeDataMovementPriority(String dataMovementInterfaceId, int newPriorityOrder) - throws RegistryServiceException, TException { + throws RegistryServiceException { return false; } @@ -2125,7 +1017,7 @@ public boolean changeDataMovementPriority(String dataMovementInterfaceId, int ne */ @Override public boolean changeJobSubmissionPriorities(Map jobSubmissionPriorityMap) - throws RegistryServiceException, TException { + throws RegistryServiceException { return false; } @@ -2138,7 +1030,7 @@ public boolean changeJobSubmissionPriorities(Map jobSubmissionP */ @Override public boolean changeDataMovementPriorities(Map dataMovementPriorityMap) - throws RegistryServiceException, TException { + throws RegistryServiceException { return false; } @@ -2152,43 +1044,18 @@ public boolean changeDataMovementPriorities(Map dataMovementPri */ @Override public boolean deleteJobSubmissionInterface(String computeResourceId, String jobSubmissionInterfaceId) - throws RegistryServiceException, TException { - try { - new ComputeResourceRepository().removeJobSubmissionInterface(computeResourceId, jobSubmissionInterfaceId); - logger.debug("Airavata deleted job submission interface with interface id : " + jobSubmissionInterfaceId); - return true; - } catch (AppCatalogException e) { - logger.error(jobSubmissionInterfaceId, "Error while deleting job submission interface...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting job submission interface. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.deleteJobSubmissionInterface(computeResourceId, jobSubmissionInterfaceId); } @Override - public ResourceJobManager getResourceJobManager(String resourceJobManagerId) - throws RegistryServiceException, TException { - try { - return new ComputeResourceRepository().getResourceJobManager(resourceJobManagerId); - } catch (AppCatalogException e) { - logger.error(resourceJobManagerId, "Error while retrieving resource job manager...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving resource job manager. More info : " + e.getMessage()); - throw exception; - } + public ResourceJobManager getResourceJobManager(String resourceJobManagerId) throws RegistryServiceException { + return registryService.getResourceJobManager(resourceJobManagerId); } @Override - public boolean deleteResourceJobManager(String resourceJobManagerId) throws RegistryServiceException, TException { - try { - new ComputeResourceRepository().deleteResourceJobManager(resourceJobManagerId); - return true; - } catch (AppCatalogException e) { - logger.error(resourceJobManagerId, "Error while deleting resource job manager...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting resource job manager. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteResourceJobManager(String resourceJobManagerId) throws RegistryServiceException { + return registryService.deleteResourceJobManager(resourceJobManagerId); } /** @@ -2200,17 +1067,8 @@ public boolean deleteResourceJobManager(String resourceJobManagerId) throws Regi * Returns a success/failure of the deletion. */ @Override - public boolean deleteBatchQueue(String computeResourceId, String queueName) - throws RegistryServiceException, TException { - try { - new ComputeResourceRepository().removeBatchQueue(computeResourceId, queueName); - return true; - } catch (AppCatalogException e) { - logger.error(computeResourceId, "Error while deleting batch queue...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting batch queue. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteBatchQueue(String computeResourceId, String queueName) throws RegistryServiceException { + return registryService.deleteBatchQueue(computeResourceId, queueName); } /** @@ -2221,23 +1079,8 @@ public boolean deleteBatchQueue(String computeResourceId, String queueName) * Gateway Resource Profile Object. */ @Override - public GatewayResourceProfile getGatewayResourceProfile(String gatewayID) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - GatewayResourceProfile gatewayResourceProfile = gwyResourceProfileRepository.getGatewayProfile(gatewayID); - logger.debug("Airavata retrieved gateway profile with gateway id : " + gatewayID); - return gatewayResourceProfile; - } catch (Exception e) { - logger.error(gatewayID, "Error while retrieving gateway resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving gateway resource profile. More info : " + e.getMessage()); - throw exception; - } + public GatewayResourceProfile getGatewayResourceProfile(String gatewayID) throws RegistryServiceException { + return registryService.getGatewayResourceProfile(gatewayID); } /** @@ -2248,22 +1091,8 @@ public GatewayResourceProfile getGatewayResourceProfile(String gatewayID) * Returns a success/failure of the deletion. */ @Override - public boolean deleteGatewayResourceProfile(String gatewayID) throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - gwyResourceProfileRepository.delete(gatewayID); - logger.debug("Airavata deleted gateway profile with gateway id : " + gatewayID); - return true; - } catch (Exception e) { - logger.error(gatewayID, "Error while removing gateway resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while removing gateway resource profile. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteGatewayResourceProfile(String gatewayID) throws RegistryServiceException { + return registryService.deleteGatewayResourceProfile(gatewayID); } /** @@ -2276,44 +1105,8 @@ public boolean deleteGatewayResourceProfile(String gatewayID) throws RegistrySer */ @Override public ComputeResourcePreference getGatewayComputeResourcePreference(String gatewayID, String computeResourceId) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - if (!gwyResourceProfileRepository.isGatewayResourceProfileExists(gatewayID)) { - logger.error( - gatewayID, - "Given gateway profile does not exist in the system. Please provide a valid gateway id..."); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Given gateway profile does not exist in the system. Please provide a valid gateway id..."); - throw exception; - } - if (!computeResourceRepository.isComputeResourceExists(computeResourceId)) { - logger.error( - computeResourceId, - "Given compute resource does not exist in the system. Please provide a valid compute resource id..."); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Given compute resource does not exist in the system. Please provide a valid compute resource id..."); - throw exception; - } - ComputeResourcePreference computeResourcePreference = - gwyResourceProfileRepository.getComputeResourcePreference(gatewayID, computeResourceId); - logger.debug("Airavata retrieved gateway compute resource preference with gateway id : " + gatewayID - + " and for compute resoruce id : " + computeResourceId); - return computeResourcePreference; - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while reading gateway compute resource preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while reading gateway compute resource preference. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getGatewayComputeResourcePreference(gatewayID, computeResourceId); } /** @@ -2326,34 +1119,8 @@ public ComputeResourcePreference getGatewayComputeResourcePreference(String gate */ @Override public StoragePreference getGatewayStoragePreference(String gatewayID, String storageId) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - if (!gwyResourceProfileRepository.isGatewayResourceProfileExists(gatewayID)) { - logger.error( - gatewayID, - "Given gateway profile does not exist in the system. Please provide a valid gateway id..."); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Given gateway profile does not exist in the system. Please provide a valid gateway id..."); - throw exception; - } - - StoragePreference storagePreference = - gwyResourceProfileRepository.getStoragePreference(gatewayID, storageId); - logger.debug("Airavata retrieved storage resource preference with gateway id : " + gatewayID - + " and for storage resource id : " + storageId); - return storagePreference; - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while reading gateway data storage preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while reading gateway data storage preference. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getGatewayStoragePreference(gatewayID, storageId); } /** @@ -2365,21 +1132,8 @@ public StoragePreference getGatewayStoragePreference(String gatewayID, String st */ @Override public List getAllGatewayComputeResourcePreferences(String gatewayID) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - return gwyResourceProfileRepository.getGatewayProfile(gatewayID).getComputeResourcePreferences(); - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway compute resource preferences...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while reading gateway compute resource preferences. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getAllGatewayComputeResourcePreferences(gatewayID); } /** @@ -2390,21 +1144,8 @@ public List getAllGatewayComputeResourcePreferences(S * Returns the StoragePreference object. */ @Override - public List getAllGatewayStoragePreferences(String gatewayID) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - return gwyResourceProfileRepository.getGatewayProfile(gatewayID).getStoragePreferences(); - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway data storage preferences...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while reading gateway data storage preferences. More info : " + e.getMessage()); - throw exception; - } + public List getAllGatewayStoragePreferences(String gatewayID) throws RegistryServiceException { + return registryService.getAllGatewayStoragePreferences(gatewayID); } /** @@ -2414,15 +1155,8 @@ public List getAllGatewayStoragePreferences(String gatewayID) * Returns all the GatewayResourcePrifle list object. */ @Override - public List getAllGatewayResourceProfiles() throws RegistryServiceException, TException { - try { - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - return gwyResourceProfileRepository.getAllGatewayProfiles(); - } catch (Exception e) { - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while reading retrieving all gateway profiles. More info : " + e.getMessage()); - throw exception; - } + public List getAllGatewayResourceProfiles() throws RegistryServiceException { + return registryService.getAllGatewayResourceProfiles(); } /** @@ -2435,23 +1169,8 @@ public List getAllGatewayResourceProfiles() throws Regis */ @Override public boolean deleteGatewayComputeResourcePreference(String gatewayID, String computeResourceId) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - - return gwyResourceProfileRepository.removeComputeResourcePreferenceFromGateway( - gatewayID, computeResourceId); - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway compute resource preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while updating gateway compute resource preference. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.deleteGatewayComputeResourcePreference(gatewayID, computeResourceId); } /** @@ -2463,395 +1182,130 @@ public boolean deleteGatewayComputeResourcePreference(String gatewayID, String c * Returns a success/failure of the deletion. */ @Override - public boolean deleteGatewayStoragePreference(String gatewayID, String storageId) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - return gwyResourceProfileRepository.removeDataStoragePreferenceFromGateway(gatewayID, storageId); - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway data storage preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating gateway data storage preference. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteGatewayStoragePreference(String gatewayID, String storageId) throws RegistryServiceException { + return registryService.deleteGatewayStoragePreference(gatewayID, storageId); } @Override - public DataProductModel getDataProduct(String productUri) throws RegistryServiceException, TException { - try { - DataProductModel dataProductModel = dataProductRepository.getDataProduct(productUri); - return dataProductModel; - } catch (RegistryException e) { - String msg = "Error in retreiving the data product " + productUri + "."; - logger.error(msg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + public DataProductModel getDataProduct(String productUri) throws RegistryServiceException { + return registryService.getDataProduct(productUri); } @Override - public DataProductModel getParentDataProduct(String productUri) throws RegistryServiceException, TException { - try { - DataProductModel dataProductModel = dataProductRepository.getParentDataProduct(productUri); - return dataProductModel; - } catch (RegistryException e) { - String msg = "Error in retreiving the parent data product for " + productUri + "."; - logger.error(msg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + public DataProductModel getParentDataProduct(String productUri) throws RegistryServiceException { + return registryService.getParentDataProduct(productUri); } @Override - public List getChildDataProducts(String productUri) throws RegistryServiceException, TException { - try { - List dataProductModels = dataProductRepository.getChildDataProducts(productUri); - return dataProductModels; - } catch (RegistryException e) { - String msg = "Error in retreiving the child products for " + productUri + "."; - logger.error(msg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + public List getChildDataProducts(String productUri) throws RegistryServiceException { + return registryService.getChildDataProducts(productUri); } @Override public List searchDataProductsByName( String gatewayId, String userId, String productName, int limit, int offset) - throws RegistryServiceException, TException { - try { - List dataProductModels = - dataProductRepository.searchDataProductsByName(gatewayId, userId, productName, limit, offset); - return dataProductModels; - } catch (RegistryException e) { - String msg = "Error in searching the data products for name " + productName + "."; - logger.error(msg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.searchDataProductsByName(gatewayId, userId, productName, limit, offset); } @Override public String createGroupResourceProfile(GroupResourceProfile groupResourceProfile) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(groupResourceProfile.getGatewayId())) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - String groupResourceProfileId = - groupResourceProfileRepository.addGroupResourceProfile(groupResourceProfile); - logger.debug("New Group Resource Profile Created: " + groupResourceProfileId); - return groupResourceProfileId; - } catch (Exception e) { - logger.error("Error while creating group resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while creating group resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.createGroupResourceProfile(groupResourceProfile); } @Override - public void updateGroupResourceProfile(GroupResourceProfile groupResourceProfile) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - if (!groupResourceProfileRepository.isGroupResourceProfileExists( - groupResourceProfile.getGroupResourceProfileId())) { - logger.error( - "Cannot update. No group resource profile found with matching gatewayId and groupResourceProfileId"); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Cannot update. No group resource profile found with matching gatewayId and groupResourceProfileId"); - throw exception; - } - String groupResourceProfileId = - groupResourceProfileRepository.updateGroupResourceProfile(groupResourceProfile); - logger.debug(" Group Resource Profile updated: " + groupResourceProfileId); - } catch (Exception e) { - logger.error("Error while updating group resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating group resource profile. More info : " + e.getMessage()); - throw exception; - } + public void updateGroupResourceProfile(GroupResourceProfile groupResourceProfile) throws RegistryServiceException { + registryService.updateGroupResourceProfile(groupResourceProfile); } @Override - public GroupResourceProfile getGroupResourceProfile(String groupResourceProfileId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - if (!groupResourceProfileRepository.isGroupResourceProfileExists(groupResourceProfileId)) { - logger.error("No group resource profile found with matching gatewayId and groupResourceProfileId"); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "No group resource profile found with matching gatewayId and groupResourceProfileId"); - throw exception; - } - - return groupResourceProfileRepository.getGroupResourceProfile(groupResourceProfileId); - } catch (Exception e) { - logger.error("Error while retrieving group resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving group resource profile. More info : " + e.getMessage()); - throw exception; - } + public GroupResourceProfile getGroupResourceProfile(String groupResourceProfileId) throws RegistryServiceException { + return registryService.getGroupResourceProfile(groupResourceProfileId); } @Override - public boolean isGroupResourceProfileExists(String groupResourceProfileId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - return groupResourceProfileRepository.isGroupResourceProfileExists(groupResourceProfileId); - } catch (Exception e) { - logger.error("Error while retrieving group resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving group resource profile. More info : " + e.getMessage()); - throw exception; - } + public boolean isGroupResourceProfileExists(String groupResourceProfileId) throws RegistryServiceException { + return registryService.isGroupResourceProfileExists(groupResourceProfileId); } @Override - public boolean removeGroupResourceProfile(String groupResourceProfileId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - if (!groupResourceProfileRepository.isGroupResourceProfileExists(groupResourceProfileId)) { - logger.error( - "Cannot Remove. No group resource profile found with matching gatewayId and groupResourceProfileId"); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Cannot Remove. No group resource profile found with matching gatewayId and groupResourceProfileId"); - throw exception; - } - return groupResourceProfileRepository.removeGroupResourceProfile(groupResourceProfileId); - } catch (Exception e) { - logger.error("Error while removing group resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while removing group resource profile. More info : " + e.getMessage()); - throw exception; - } + public boolean removeGroupResourceProfile(String groupResourceProfileId) throws RegistryServiceException { + return registryService.removeGroupResourceProfile(groupResourceProfileId); } @Override public List getGroupResourceList(String gatewayId, List accessibleGroupResProfileIds) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - return groupResourceProfileRepository.getAllGroupResourceProfiles(gatewayId, accessibleGroupResProfileIds); - } catch (Exception e) { - logger.error("Error while retrieving group resource list ", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving group resource list. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getGroupResourceList(gatewayId, accessibleGroupResProfileIds); } @Override public boolean removeGroupComputePrefs(String computeResourceId, String groupResourceProfileId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - groupResourceProfileRepository.removeGroupComputeResourcePreference( - computeResourceId, groupResourceProfileId); - logger.debug("Removed compute resource preferences with compute resource ID: " + computeResourceId); - return true; - } catch (Exception e) { - logger.error("Error while removing group compute preference", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while removing group compute preference. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.removeGroupComputePrefs(computeResourceId, groupResourceProfileId); } @Override - public boolean removeGroupComputeResourcePolicy(String resourcePolicyId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - groupResourceProfileRepository.removeComputeResourcePolicy(resourcePolicyId); - logger.debug("Removed compute resource policy with resource policy ID: " + resourcePolicyId); - return true; - } catch (Exception e) { - logger.error("Error while removing group compute resource policy", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while removing group compute resource policy. More info : " + e.getMessage()); - throw exception; - } + public boolean removeGroupComputeResourcePolicy(String resourcePolicyId) throws RegistryServiceException { + return registryService.removeGroupComputeResourcePolicy(resourcePolicyId); } @Override - public boolean removeGroupBatchQueueResourcePolicy(String resourcePolicyId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - groupResourceProfileRepository.removeBatchQueueResourcePolicy(resourcePolicyId); - logger.debug("Removed batch resource policy with resource policy ID: " + resourcePolicyId); - return true; - } catch (Exception e) { - logger.error("Error while removing group batch queue resource policy", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while removing group batch queue resource policy. More info : " + e.getMessage()); - throw exception; - } + public boolean removeGroupBatchQueueResourcePolicy(String resourcePolicyId) throws RegistryServiceException { + return registryService.removeGroupBatchQueueResourcePolicy(resourcePolicyId); } @Override public GroupComputeResourcePreference getGroupComputeResourcePreference( - String computeResourceId, String groupResourceProfileId) throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - GroupComputeResourcePreference groupComputeResourcePreference = - groupResourceProfileRepository.getGroupComputeResourcePreference( - computeResourceId, groupResourceProfileId); - if (!(groupComputeResourcePreference != null)) { - logger.error("GroupComputeResourcePreference not found"); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("GroupComputeResourcePreference not found "); - throw exception; - } - return groupComputeResourcePreference; - - } catch (Exception e) { - logger.error("Error while retrieving group compute resource preference", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while retrieving group compute resource preference. More info : " + e.getMessage()); - throw exception; - } + String computeResourceId, String groupResourceProfileId) throws RegistryServiceException { + return registryService.getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId); } @Override public boolean isGroupComputeResourcePreferenceExists(String computeResourceId, String groupResourceProfileId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - return groupResourceProfileRepository.isGroupComputeResourcePreferenceExists( - computeResourceId, groupResourceProfileId); - } catch (Exception e) { - logger.error("Error while retrieving group compute resource preference", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while retrieving group compute resource preference. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.isGroupComputeResourcePreferenceExists(computeResourceId, groupResourceProfileId); } @Override public ComputeResourcePolicy getGroupComputeResourcePolicy(String resourcePolicyId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - ComputeResourcePolicy computeResourcePolicy = - groupResourceProfileRepository.getComputeResourcePolicy(resourcePolicyId); - if (!(computeResourcePolicy != null)) { - logger.error("Group Compute Resource policy not found"); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Group Compute Resource policy not found "); - throw exception; - } - return computeResourcePolicy; - } catch (Exception e) { - logger.error("Error while retrieving group compute resource policy", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving group compute resource policy. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getGroupComputeResourcePolicy(resourcePolicyId); } @Override public BatchQueueResourcePolicy getBatchQueueResourcePolicy(String resourcePolicyId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - BatchQueueResourcePolicy batchQueueResourcePolicy = - groupResourceProfileRepository.getBatchQueueResourcePolicy(resourcePolicyId); - if (!(batchQueueResourcePolicy != null)) { - logger.error("Group Batch Queue Resource policy not found"); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Group Batch Queue Resource policy not found "); - throw exception; - } - return batchQueueResourcePolicy; - } catch (Exception e) { - logger.error("Error while retrieving Batch Queue resource policy", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving Batch Queue resource policy. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getBatchQueueResourcePolicy(resourcePolicyId); } @Override public List getGroupComputeResourcePrefList(String groupResourceProfileId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - return groupResourceProfileRepository.getAllGroupComputeResourcePreferences(groupResourceProfileId); - } catch (Exception e) { - logger.error("Error while retrieving retrieving Group Compute Resource Preference list", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while retrieving retrieving Group Compute Resource Preference list. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getGroupComputeResourcePrefList(groupResourceProfileId); } @Override public List getGroupBatchQueueResourcePolicyList(String groupResourceProfileId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - return groupResourceProfileRepository.getAllGroupBatchQueueResourcePolicies(groupResourceProfileId); - } catch (Exception e) { - logger.error("Error while retrieving retrieving Group Batch Queue Resource policy list", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while retrieving retrieving Group Batch Queue Resource policy list. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getGroupBatchQueueResourcePolicyList(groupResourceProfileId); } @Override public List getGroupComputeResourcePolicyList(String groupResourceProfileId) - throws RegistryServiceException, TException { - try { - GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); - return groupResourceProfileRepository.getAllGroupComputeResourcePolicies(groupResourceProfileId); - } catch (Exception e) { - logger.error("Error while retrieving retrieving Group Compute Resource policy list", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving retrieving Group Compute Resource policy list. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getGroupComputeResourcePolicyList(groupResourceProfileId); } @Override public String registerReplicaLocation(DataReplicaLocationModel replicaLocationModel) - throws RegistryServiceException, TException { + throws RegistryServiceException { try { - String replicaId = dataReplicaLocationRepository.registerReplicaLocation(replicaLocationModel); - return replicaId; - } catch (RegistryException e) { - String msg = "Error in retreiving the replica " + replicaLocationModel.getReplicaName() + "."; - logger.error(msg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; + return registryService.registerReplicaLocation(replicaLocationModel); + } catch (Throwable e) { + throw convertToRegistryServiceException( + e, "Error in retreiving the replica " + replicaLocationModel.getReplicaName()); } } @@ -2861,16 +1315,12 @@ public String registerReplicaLocation(DataReplicaLocationModel replicaLocationMo * @param dataProductModel */ @Override - public String registerDataProduct(DataProductModel dataProductModel) throws RegistryServiceException, TException { + public String registerDataProduct(DataProductModel dataProductModel) throws RegistryServiceException { try { - String productUrl = dataProductRepository.registerDataProduct(dataProductModel); - return productUrl; - } catch (RegistryException e) { - String msg = "Error in registering the data resource" + dataProductModel.getProductName() + "."; - logger.error(msg, e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; + return registryService.registerDataProduct(dataProductModel); + } catch (Throwable e) { + throw convertToRegistryServiceException( + e, "Error in registering the data resource" + dataProductModel.getProductName()); } } @@ -2885,37 +1335,8 @@ public String registerDataProduct(DataProductModel dataProductModel) throws Regi */ @Override public boolean updateGatewayStoragePreference( - String gatewayID, String storageId, StoragePreference storagePreference) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - GatewayResourceProfile profile = gwyResourceProfileRepository.getGatewayProfile(gatewayID); - List dataStoragePreferences = profile.getStoragePreferences(); - StoragePreference preferenceToRemove = null; - for (StoragePreference preference : dataStoragePreferences) { - if (preference.getStorageResourceId().equals(storageId)) { - preferenceToRemove = preference; - break; - } - } - if (preferenceToRemove != null) { - profile.getStoragePreferences().remove(preferenceToRemove); - } - profile.getStoragePreferences().add(storagePreference); - gwyResourceProfileRepository.updateGatewayResourceProfile(profile); - logger.debug("Airavata updated storage resource preference with gateway id : " + gatewayID - + " and for storage resource id : " + storageId); - return true; - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway data storage preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating gateway data storage preference. More info : " + e.getMessage()); - throw exception; - } + String gatewayID, String storageId, StoragePreference storagePreference) throws RegistryServiceException { + return registryService.updateGatewayStoragePreference(gatewayID, storageId, storagePreference); } /** @@ -2930,37 +1351,9 @@ public boolean updateGatewayStoragePreference( @Override public boolean updateGatewayComputeResourcePreference( String gatewayID, String computeResourceId, ComputeResourcePreference computeResourcePreference) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - GatewayResourceProfile profile = gwyResourceProfileRepository.getGatewayProfile(gatewayID); - List computeResourcePreferences = profile.getComputeResourcePreferences(); - ComputeResourcePreference preferenceToRemove = null; - for (ComputeResourcePreference preference : computeResourcePreferences) { - if (preference.getComputeResourceId().equals(computeResourceId)) { - preferenceToRemove = preference; - break; - } - } - if (preferenceToRemove != null) { - profile.getComputeResourcePreferences().remove(preferenceToRemove); - } - profile.getComputeResourcePreferences().add(computeResourcePreference); - gwyResourceProfileRepository.updateGatewayResourceProfile(profile); - logger.debug("Airavata updated compute resource preference with gateway id : " + gatewayID - + " and for compute resource id : " + computeResourceId); - return true; - } catch (Exception e) { - logger.error(gatewayID, "Error while reading gateway compute resource preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while updating gateway compute resource preference. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateGatewayComputeResourcePreference( + gatewayID, computeResourceId, computeResourcePreference); } /** @@ -2976,32 +1369,8 @@ public boolean updateGatewayComputeResourcePreference( @Override public boolean addGatewayStoragePreference( String gatewayID, String storageResourceId, StoragePreference dataStoragePreference) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - if (!(gwyResourceProfileRepository.isExists(gatewayID))) { - throw new RegistryServiceException("Gateway resource profile '" + gatewayID + "' does not exist!!!"); - } - GatewayResourceProfile profile = gwyResourceProfileRepository.getGatewayProfile(gatewayID); - - dataStoragePreference.setStorageResourceId(storageResourceId); - profile.addToStoragePreferences(dataStoragePreference); - gwyResourceProfileRepository.updateGatewayResourceProfile(profile); - logger.debug("Airavata added storage resource preference with gateway id : " + gatewayID - + " and for storage resource id : " + storageResourceId); - return true; - } catch (Exception e) { - logger.error(gatewayID, "Error while registering gateway resource profile preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while registering gateway resource profile preference. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addGatewayStoragePreference(gatewayID, storageResourceId, dataStoragePreference); } /** @@ -3017,29 +1386,9 @@ public boolean addGatewayStoragePreference( @Override public boolean addGatewayComputeResourcePreference( String gatewayID, String computeResourceId, ComputeResourcePreference computeResourcePreference) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - if (!(gwyResourceProfileRepository.isExists(gatewayID))) { - throw new RegistryServiceException("Gateway resource profile '" + gatewayID + "' does not exist!!!"); - } - GatewayResourceProfile profile = gwyResourceProfileRepository.getGatewayProfile(gatewayID); - profile.addToComputeResourcePreferences(computeResourcePreference); - gwyResourceProfileRepository.updateGatewayResourceProfile(profile); - logger.debug("Airavata added gateway compute resource preference with gateway id : " + gatewayID - + " and for compute resource id : " + computeResourceId); - return true; - } catch (Exception e) { - logger.error(gatewayID, "Error while registering gateway resource profile preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while registering gateway resource profile preference. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addGatewayComputeResourcePreference( + gatewayID, computeResourceId, computeResourcePreference); } /** @@ -3052,22 +1401,8 @@ public boolean addGatewayComputeResourcePreference( */ @Override public boolean updateGatewayResourceProfile(String gatewayID, GatewayResourceProfile gatewayResourceProfile) - throws RegistryServiceException, TException { - try { - if (!isGatewayExistInternal(gatewayID)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - gwyResourceProfileRepository.updateGatewayResourceProfile(gatewayResourceProfile); - logger.debug("Airavata updated gateway profile with gateway id : " + gatewayID); - return true; - } catch (Exception e) { - logger.error(gatewayID, "Error while updating gateway resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating gateway resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateGatewayResourceProfile(gatewayID, gatewayResourceProfile); } /** @@ -3081,56 +1416,19 @@ public boolean updateGatewayResourceProfile(String gatewayID, GatewayResourcePro */ @Override public String registerGatewayResourceProfile(GatewayResourceProfile gatewayResourceProfile) - throws RegistryServiceException, TException { - try { - if (!validateString(gatewayResourceProfile.getGatewayID())) { - logger.error("Cannot create gateway profile with empty gateway id"); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Cannot create gateway profile with empty gateway id"); - throw exception; - } - if (!isGatewayExistInternal(gatewayResourceProfile.getGatewayID())) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); - String resourceProfile = gwyResourceProfileRepository.addGatewayResourceProfile(gatewayResourceProfile); - logger.debug( - "Airavata registered gateway profile with gateway id : " + gatewayResourceProfile.getGatewayID()); - return resourceProfile; - } catch (Exception e) { - logger.error("Error while registering gateway resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while registering gateway resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.registerGatewayResourceProfile(gatewayResourceProfile); } @Override public boolean updateResourceJobManager(String resourceJobManagerId, ResourceJobManager updatedResourceJobManager) - throws RegistryServiceException, TException { - try { - new ComputeResourceRepository().updateResourceJobManager(resourceJobManagerId, updatedResourceJobManager); - return true; - } catch (AppCatalogException e) { - logger.error(resourceJobManagerId, "Error while updating resource job manager...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating resource job manager. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateResourceJobManager(resourceJobManagerId, updatedResourceJobManager); } @Override - public String registerResourceJobManager(ResourceJobManager resourceJobManager) - throws RegistryServiceException, TException { - try { - return new ComputeResourceRepository().addResourceJobManager(resourceJobManager); - } catch (AppCatalogException e) { - logger.error(resourceJobManager.getResourceJobManagerId(), "Error while adding resource job manager...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while adding resource job manager. More info : " + e.getMessage()); - throw exception; - } + public String registerResourceJobManager(ResourceJobManager resourceJobManager) throws RegistryServiceException { + return registryService.registerResourceJobManager(resourceJobManager); } /** @@ -3143,30 +1441,8 @@ public String registerResourceJobManager(ResourceJobManager resourceJobManager) */ @Override public boolean deleteDataMovementInterface(String resourceId, String dataMovementInterfaceId, DMType dmType) - throws RegistryServiceException, TException { - try { - switch (dmType) { - case COMPUTE_RESOURCE: - new ComputeResourceRepository().removeDataMovementInterface(resourceId, dataMovementInterfaceId); - logger.debug( - "Airavata deleted data movement interface with interface id : " + dataMovementInterfaceId); - return true; - case STORAGE_RESOURCE: - storageResourceRepository.removeDataMovementInterface(resourceId, dataMovementInterfaceId); - logger.debug( - "Airavata deleted data movement interface with interface id : " + dataMovementInterfaceId); - return true; - default: - logger.error( - "Unsupported data movement type specifies.. Please provide the correct data movement type... "); - return false; - } - } catch (AppCatalogException e) { - logger.error(dataMovementInterfaceId, "Error while deleting data movement interface...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while deleting data movement interface. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.deleteDataMovementInterface(resourceId, dataMovementInterfaceId, dmType); } /** @@ -3180,8 +1456,7 @@ public boolean deleteDataMovementInterface(String resourceId, String dataMovemen */ @Override public boolean updateGridFTPDataMovementDetails( - String dataMovementInterfaceId, GridFTPDataMovement gridFTPDataMovement) - throws RegistryServiceException, TException { + String dataMovementInterfaceId, GridFTPDataMovement gridFTPDataMovement) throws RegistryServiceException { throw new RegistryServiceException("updateGridFTPDataMovementDetails is not yet implemented"); } @@ -3200,27 +1475,9 @@ public boolean updateGridFTPDataMovementDetails( @Override public String addGridFTPDataMovementDetails( String computeResourceId, DMType dmType, int priorityOrder, GridFTPDataMovement gridFTPDataMovement) - throws RegistryServiceException, TException { - try { - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - String addDataMovementInterface = addDataMovementInterface( - computeResourceRepository, - computeResourceId, - dmType, - computeResourceRepository.addGridFTPDataMovement(gridFTPDataMovement), - DataMovementProtocol.GridFTP, - priorityOrder); - logger.debug("Airavata registered GridFTP data movement for resource Id: " + computeResourceId); - return addDataMovementInterface; - } catch (AppCatalogException e) { - logger.error( - computeResourceId, "Error while adding data movement interface to resource compute resource...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addGridFTPDataMovementDetails( + computeResourceId, dmType, priorityOrder, gridFTPDataMovement); } /** @@ -3234,8 +1491,7 @@ public String addGridFTPDataMovementDetails( */ @Override public boolean updateUnicoreDataMovementDetails( - String dataMovementInterfaceId, UnicoreDataMovement unicoreDataMovement) - throws RegistryServiceException, TException { + String dataMovementInterfaceId, UnicoreDataMovement unicoreDataMovement) throws RegistryServiceException { throw new RegistryServiceException("updateUnicoreDataMovementDetails is not yet implemented"); } @@ -3254,25 +1510,8 @@ public boolean updateUnicoreDataMovementDetails( @Override public String addUnicoreDataMovementDetails( String resourceId, DMType dmType, int priorityOrder, UnicoreDataMovement unicoreDataMovement) - throws RegistryServiceException, TException { - try { - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - String movementInterface = addDataMovementInterface( - computeResourceRepository, - resourceId, - dmType, - computeResourceRepository.addUnicoreDataMovement(unicoreDataMovement), - DataMovementProtocol.UNICORE_STORAGE_SERVICE, - priorityOrder); - logger.debug("Airavata registered UNICORE data movement for resource Id: " + resourceId); - return movementInterface; - } catch (AppCatalogException e) { - logger.error(resourceId, "Error while adding data movement interface to resource compute resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addUnicoreDataMovementDetails(resourceId, dmType, priorityOrder, unicoreDataMovement); } /** @@ -3286,22 +1525,8 @@ public String addUnicoreDataMovementDetails( */ @Override public boolean updateSCPDataMovementDetails(String dataMovementInterfaceId, SCPDataMovement scpDataMovement) - throws RegistryServiceException, TException { - try { - computeResourceRepository.updateScpDataMovement(scpDataMovement); - logger.debug("Airavata updated SCP data movement with data movement id: " + dataMovementInterfaceId); - return true; - } catch (Exception e) { - logger.error( - dataMovementInterfaceId, - "Error while adding job submission interface to resource compute resource...", - e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateSCPDataMovementDetails(dataMovementInterfaceId, scpDataMovement); } /** @@ -3319,25 +1544,8 @@ public boolean updateSCPDataMovementDetails(String dataMovementInterfaceId, SCPD @Override public String addSCPDataMovementDetails( String resourceId, DMType dmType, int priorityOrder, SCPDataMovement scpDataMovement) - throws RegistryServiceException, TException { - try { - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - String movementInterface = addDataMovementInterface( - computeResourceRepository, - resourceId, - dmType, - computeResourceRepository.addScpDataMovement(scpDataMovement), - DataMovementProtocol.SCP, - priorityOrder); - logger.debug("Airavata registered SCP data movement for resource Id: " + resourceId); - return movementInterface; - } catch (AppCatalogException e) { - logger.error(resourceId, "Error while adding data movement interface to resource compute resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while adding data movement interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addSCPDataMovementDetails(resourceId, dmType, priorityOrder, scpDataMovement); } /** @@ -3350,17 +1558,8 @@ public String addSCPDataMovementDetails( */ @Override public boolean updateLocalDataMovementDetails(String dataMovementInterfaceId, LOCALDataMovement localDataMovement) - throws RegistryServiceException, TException { - try { - computeResourceRepository.updateLocalDataMovement(localDataMovement); - logger.debug("Airavata updated local data movement with data movement id: " + dataMovementInterfaceId); - return true; - } catch (Exception e) { - logger.error(dataMovementInterfaceId, "Error while updating local data movement interface..", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating local data movement interface. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateLocalDataMovementDetails(dataMovementInterfaceId, localDataMovement); } /** @@ -3378,25 +1577,8 @@ public boolean updateLocalDataMovementDetails(String dataMovementInterfaceId, LO @Override public String addLocalDataMovementDetails( String resourceId, DMType dataMoveType, int priorityOrder, LOCALDataMovement localDataMovement) - throws RegistryServiceException, TException { - try { - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - String movementInterface = addDataMovementInterface( - computeResourceRepository, - resourceId, - dataMoveType, - computeResourceRepository.addLocalDataMovement(localDataMovement), - DataMovementProtocol.LOCAL, - priorityOrder); - logger.debug("Airavata registered local data movement for resource Id: " + resourceId); - return movementInterface; - } catch (AppCatalogException e) { - logger.error(resourceId, "Error while adding data movement interface to resource resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while adding data movement interface to resource. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addLocalDataMovementDetails(resourceId, dataMoveType, priorityOrder, localDataMovement); } /** @@ -3410,7 +1592,7 @@ public String addLocalDataMovementDetails( @Override public boolean updateUnicoreJobSubmissionDetails( String jobSubmissionInterfaceId, UnicoreJobSubmission unicoreJobSubmission) - throws RegistryServiceException, TException { + throws RegistryServiceException { throw new RegistryServiceException("updateUnicoreJobSubmissionDetails is not yet implemented"); } @@ -3424,23 +1606,8 @@ public boolean updateUnicoreJobSubmissionDetails( */ @Override public boolean updateCloudJobSubmissionDetails(String jobSubmissionInterfaceId, CloudJobSubmission sshJobSubmission) - throws RegistryServiceException, TException { - try { - computeResourceRepository.updateCloudJobSubmission(sshJobSubmission); - logger.debug("Airavata updated Cloud job submission for job submission interface id: " - + jobSubmissionInterfaceId); - return true; - } catch (Exception e) { - logger.error( - jobSubmissionInterfaceId, - "Error while adding job submission interface to resource compute resource...", - e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateCloudJobSubmissionDetails(jobSubmissionInterfaceId, sshJobSubmission); } /** @@ -3453,23 +1620,8 @@ public boolean updateCloudJobSubmissionDetails(String jobSubmissionInterfaceId, */ @Override public boolean updateSSHJobSubmissionDetails(String jobSubmissionInterfaceId, SSHJobSubmission sshJobSubmission) - throws RegistryServiceException, TException { - try { - computeResourceRepository.updateSSHJobSubmission(sshJobSubmission); - logger.debug( - "Airavata updated SSH job submission for job submission interface id: " + jobSubmissionInterfaceId); - return true; - } catch (Exception e) { - logger.error( - jobSubmissionInterfaceId, - "Error while adding job submission interface to resource compute resource...", - e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateSSHJobSubmissionDetails(jobSubmissionInterfaceId, sshJobSubmission); } /** @@ -3498,28 +1650,8 @@ public boolean updateSSHJobSubmissionDetails(String jobSubmissionInterfaceId, SS @Override public String addCloudJobSubmissionDetails( String computeResourceId, int priorityOrder, CloudJobSubmission cloudSubmission) - throws RegistryServiceException, TException { - try { - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - String submissionInterface = addJobSubmissionInterface( - computeResourceRepository, - computeResourceId, - computeResourceRepository.addCloudJobSubmission(cloudSubmission), - JobSubmissionProtocol.CLOUD, - priorityOrder); - logger.debug("Airavata registered Cloud job submission for compute resource id: " + computeResourceId); - return submissionInterface; - } catch (AppCatalogException e) { - logger.error( - computeResourceId, - "Error while adding job submission interface to resource compute resource...", - e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addCloudJobSubmissionDetails(computeResourceId, priorityOrder, cloudSubmission); } /** @@ -3535,25 +1667,8 @@ public String addCloudJobSubmissionDetails( @Override public String addUNICOREJobSubmissionDetails( String computeResourceId, int priorityOrder, UnicoreJobSubmission unicoreJobSubmission) - throws RegistryServiceException, TException { - try { - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - String submissionInterface = addJobSubmissionInterface( - computeResourceRepository, - computeResourceId, - computeResourceRepository.addUNICOREJobSubmission(unicoreJobSubmission), - JobSubmissionProtocol.UNICORE, - priorityOrder); - logger.debug("Airavata registered UNICORE job submission for compute resource id: " + computeResourceId); - return submissionInterface; - } catch (AppCatalogException e) { - logger.error("Error while adding job submission interface to resource compute resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addUNICOREJobSubmissionDetails(computeResourceId, priorityOrder, unicoreJobSubmission); } /** @@ -3569,28 +1684,8 @@ public String addUNICOREJobSubmissionDetails( @Override public String addSSHForkJobSubmissionDetails( String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission) - throws RegistryServiceException, TException { - try { - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - String submissionDetails = addJobSubmissionInterface( - computeResourceRepository, - computeResourceId, - computeResourceRepository.addSSHJobSubmission(sshJobSubmission), - JobSubmissionProtocol.SSH_FORK, - priorityOrder); - logger.debug("Airavata registered Fork job submission for compute resource id: " + computeResourceId); - return submissionDetails; - } catch (AppCatalogException e) { - logger.error( - computeResourceId, - "Error while adding job submission interface to resource compute resource...", - e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addSSHForkJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission); } /** @@ -3606,28 +1701,8 @@ public String addSSHForkJobSubmissionDetails( @Override public String addSSHJobSubmissionDetails( String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission) - throws RegistryServiceException, TException { - try { - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - String submissionInterface = addJobSubmissionInterface( - computeResourceRepository, - computeResourceId, - computeResourceRepository.addSSHJobSubmission(sshJobSubmission), - JobSubmissionProtocol.SSH, - priorityOrder); - logger.debug("Airavata registered SSH job submission for compute resource id: " + computeResourceId); - return submissionInterface; - } catch (AppCatalogException e) { - logger.error( - computeResourceId, - "Error while adding job submission interface to resource compute resource...", - e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addSSHJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission); } /** @@ -3640,23 +1715,8 @@ public String addSSHJobSubmissionDetails( */ @Override public boolean updateLocalSubmissionDetails(String jobSubmissionInterfaceId, LOCALSubmission localSubmission) - throws RegistryServiceException, TException { - try { - computeResourceRepository.updateLocalJobSubmission(localSubmission); - logger.debug("Airavata updated local job submission for job submission interface id: " - + jobSubmissionInterfaceId); - return true; - } catch (Exception e) { - logger.error( - jobSubmissionInterfaceId, - "Error while adding job submission interface to resource compute resource...", - e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateLocalSubmissionDetails(jobSubmissionInterfaceId, localSubmission); } /** @@ -3672,28 +1732,8 @@ public boolean updateLocalSubmissionDetails(String jobSubmissionInterfaceId, LOC @Override public String addLocalSubmissionDetails( String computeResourceId, int priorityOrder, LOCALSubmission localSubmission) - throws RegistryServiceException, TException { - try { - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - String submissionInterface = addJobSubmissionInterface( - computeResourceRepository, - computeResourceId, - computeResourceRepository.addLocalJobSubmission(localSubmission), - JobSubmissionProtocol.LOCAL, - priorityOrder); - logger.debug("Airavata added local job submission for compute resource id: " + computeResourceId); - return submissionInterface; - } catch (AppCatalogException e) { - logger.error( - computeResourceId, - "Error while adding job submission interface to resource compute resource...", - e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while adding job submission interface to resource compute resource. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addLocalSubmissionDetails(computeResourceId, priorityOrder, localSubmission); } /** @@ -3707,17 +1747,8 @@ public String addLocalSubmissionDetails( @Override public boolean updateStorageResource( String storageResourceId, StorageResourceDescription storageResourceDescription) - throws RegistryServiceException, TException { - try { - storageResourceRepository.updateStorageResource(storageResourceId, storageResourceDescription); - logger.debug("Airavata updated storage resource with storage resource Id : " + storageResourceId); - return true; - } catch (AppCatalogException e) { - logger.error(storageResourceId, "Error while updating storage resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updaing storage resource. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateStorageResource(storageResourceId, storageResourceDescription); } /** @@ -3729,17 +1760,8 @@ public boolean updateStorageResource( */ @Override public String registerStorageResource(StorageResourceDescription storageResourceDescription) - throws RegistryServiceException, TException { - try { - String storageResource = storageResourceRepository.addStorageResource(storageResourceDescription); - logger.debug("Airavata registered storage resource with storage resource Id : " + storageResource); - return storageResource; - } catch (AppCatalogException e) { - logger.error("Error while saving storage resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while saving storage resource. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.registerStorageResource(storageResourceDescription); } /** @@ -3753,17 +1775,8 @@ public String registerStorageResource(StorageResourceDescription storageResource @Override public boolean updateComputeResource( String computeResourceId, ComputeResourceDescription computeResourceDescription) - throws RegistryServiceException, TException { - try { - new ComputeResourceRepository().updateComputeResource(computeResourceId, computeResourceDescription); - logger.debug("Airavata updated compute resource with compute resource Id : " + computeResourceId); - return true; - } catch (AppCatalogException e) { - logger.error(computeResourceId, "Error while updating compute resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updaing compute resource. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateComputeResource(computeResourceId, computeResourceDescription); } /** @@ -3775,17 +1788,8 @@ public boolean updateComputeResource( */ @Override public String registerComputeResource(ComputeResourceDescription computeResourceDescription) - throws RegistryServiceException, TException { - try { - String computeResource = new ComputeResourceRepository().addComputeResource(computeResourceDescription); - logger.debug("Airavata registered compute resource with compute resource Id : " + computeResource); - return computeResource; - } catch (AppCatalogException e) { - logger.error("Error while saving compute resource...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while saving compute resource. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.registerComputeResource(computeResourceDescription); } /** @@ -3799,17 +1803,8 @@ public String registerComputeResource(ComputeResourceDescription computeResource @Override public boolean updateApplicationInterface( String appInterfaceId, ApplicationInterfaceDescription applicationInterface) - throws RegistryServiceException, TException { - try { - applicationInterfaceRepository.updateApplicationInterface(appInterfaceId, applicationInterface); - logger.debug("Airavata updated application interface with interface id : " + appInterfaceId); - return true; - } catch (AppCatalogException e) { - logger.error(appInterfaceId, "Error while updating application interface...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating application interface. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateApplicationInterface(appInterfaceId, applicationInterface); } /** @@ -3822,22 +1817,8 @@ public boolean updateApplicationInterface( */ @Override public String registerApplicationInterface(String gatewayId, ApplicationInterfaceDescription applicationInterface) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - try { - String interfaceId = - applicationInterfaceRepository.addApplicationInterface(applicationInterface, gatewayId); - logger.debug("Airavata registered application interface for gateway id : " + gatewayId); - return interfaceId; - } catch (AppCatalogException e) { - logger.error("Error while adding application interface...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while adding application interface. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.registerApplicationInterface(gatewayId, applicationInterface); } /** @@ -3851,17 +1832,8 @@ public String registerApplicationInterface(String gatewayId, ApplicationInterfac @Override public boolean updateApplicationDeployment( String appDeploymentId, ApplicationDeploymentDescription applicationDeployment) - throws RegistryServiceException, TException { - try { - applicationDeploymentRepository.updateApplicationDeployment(appDeploymentId, applicationDeployment); - logger.debug("Airavata updated application deployment for deployment id : " + appDeploymentId); - return true; - } catch (AppCatalogException e) { - logger.error(appDeploymentId, "Error while updating application deployment...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating application deployment. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateApplicationDeployment(appDeploymentId, applicationDeployment); } /** @@ -3874,23 +1846,8 @@ public boolean updateApplicationDeployment( */ @Override public String registerApplicationDeployment( - String gatewayId, ApplicationDeploymentDescription applicationDeployment) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - try { - String deployment = - applicationDeploymentRepository.addApplicationDeployment(applicationDeployment, gatewayId); - logger.debug("Airavata registered application deployment for gateway id : " + gatewayId); - return deployment; - } catch (AppCatalogException e) { - logger.error("Error while adding application deployment...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while adding application deployment. More info : " + e.getMessage()); - throw exception; - } + String gatewayId, ApplicationDeploymentDescription applicationDeployment) throws RegistryServiceException { + return registryService.registerApplicationDeployment(gatewayId, applicationDeployment); } /** @@ -3903,17 +1860,8 @@ public String registerApplicationDeployment( */ @Override public boolean updateApplicationModule(String appModuleId, ApplicationModule applicationModule) - throws RegistryServiceException, TException { - try { - applicationInterfaceRepository.updateApplicationModule(appModuleId, applicationModule); - logger.debug("Airavata updated application module with module id: " + appModuleId); - return true; - } catch (AppCatalogException e) { - logger.error(appModuleId, "Error while updating application module...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating application module. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateApplicationModule(appModuleId, applicationModule); } /** @@ -3927,129 +1875,21 @@ public boolean updateApplicationModule(String appModuleId, ApplicationModule app */ @Override public String registerApplicationModule(String gatewayId, ApplicationModule applicationModule) - throws RegistryServiceException, TException { - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - try { - String module = applicationInterfaceRepository.addApplicationModule(applicationModule, gatewayId); - logger.debug("Airavata registered application module for gateway id : " + gatewayId); - return module; - } catch (AppCatalogException e) { - logger.error("Error while adding application module...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while adding application module. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.registerApplicationModule(gatewayId, applicationModule); } @Override public void updateResourceScheduleing( String airavataExperimentId, ComputationalResourceSchedulingModel resourceScheduling) - throws RegistryServiceException, TException { - try { - if (!experimentRepository.isExperimentExist(airavataExperimentId)) { - logger.debug( - airavataExperimentId, - "Update resource scheduling failed, experiment {} doesn't exist.", - airavataExperimentId); - throw new ExperimentNotFoundException( - "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); - } - ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); - if (experimentStatus != null) { - ExperimentState experimentState = experimentStatus.getState(); - switch (experimentState) { - case CREATED: - case VALIDATED: - case CANCELED: - case FAILED: - processRepository.addProcessResourceSchedule(resourceScheduling, airavataExperimentId); - logger.debug( - airavataExperimentId, - "Successfully updated resource scheduling for the experiment {}.", - airavataExperimentId); - break; - default: - logger.error( - airavataExperimentId, - "Error while updating scheduling info. Update experiment is only valid for experiments " - + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " - + "experiment is in one of above statuses... "); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while updating experiment. Update experiment is only valid for experiments " - + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " - + "experiment is in one of above statuses... "); - throw exception; - } - } - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while updating scheduling info", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while updating scheduling info. " + "Update experiment is only valid for experiments " - + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " - + "experiment is in one of above statuses... " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + registryService.updateResourceScheduleing(airavataExperimentId, resourceScheduling); } @Override public void updateExperimentConfiguration(String airavataExperimentId, UserConfigurationDataModel userConfiguration) - throws RegistryServiceException, TException { - try { - if (!experimentRepository.isExperimentExist(airavataExperimentId)) { - logger.error( - airavataExperimentId, - "Update experiment configuration failed, experiment {} doesn't exist.", - airavataExperimentId); - throw new ExperimentNotFoundException( - "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); - } - ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); - if (experimentStatus != null) { - ExperimentState experimentState = experimentStatus.getState(); - switch (experimentState) { - case CREATED: - case VALIDATED: - case CANCELED: - case FAILED: - experimentRepository.addUserConfigurationData(userConfiguration, airavataExperimentId); - logger.debug( - airavataExperimentId, - "Successfully updated experiment configuration for experiment {}.", - airavataExperimentId); - break; - default: - logger.error( - airavataExperimentId, - "Error while updating experiment {}. Update experiment is only valid for experiments " - + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " - + "experiment is in one of above statuses... ", - airavataExperimentId); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while updating experiment. Update experiment is only valid for experiments " - + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " - + "experiment is in one of above statuses... "); - throw exception; - } - } - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while updating user configuration", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while updating user configuration. " + "Update experiment is only valid for experiments " - + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " - + "experiment is in one of above statuses... " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + registryService.updateExperimentConfiguration(airavataExperimentId, userConfiguration); } /** @@ -4078,77 +1918,8 @@ public void updateExperimentConfiguration(String airavataExperimentId, UserConfi */ @Override public void updateExperiment(String airavataExperimentId, ExperimentModel experiment) - throws RegistryServiceException, TException { - try { - if (!experimentRepository.isExperimentExist(airavataExperimentId)) { - logger.error( - airavataExperimentId, - "Update request failed, Experiment {} doesn't exist.", - airavataExperimentId); - throw new RegistryServiceException( - "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); - } - - ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); - if (experimentStatus != null) { - ExperimentState experimentState = experimentStatus.getState(); - switch (experimentState) { - case CREATED: - case SCHEDULED: - case VALIDATED: - if (experiment.getUserConfigurationData() != null - && experiment.getUserConfigurationData().getComputationalResourceScheduling() != null - && experiment - .getUserConfigurationData() - .getComputationalResourceScheduling() - .getResourceHostId() - != null) { - String compResourceId = experiment - .getUserConfigurationData() - .getComputationalResourceScheduling() - .getResourceHostId(); - ComputeResourceDescription computeResourceDescription = - new ComputeResourceRepository().getComputeResource(compResourceId); - if (!computeResourceDescription.isEnabled()) { - logger.error("Compute Resource is not enabled by the Admin!"); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Compute Resource is not enabled by the Admin!"); - throw exception; - } - } - experimentRepository.updateExperiment(experiment, airavataExperimentId); - logger.debug( - airavataExperimentId, - "Successfully updated experiment {} ", - experiment.getExperimentName()); - break; - default: - logger.error( - airavataExperimentId, - "Error while updating experiment. Update experiment is only valid for experiments " - + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " - + "experiment is in one of above statuses... "); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Error while updating experiment. Update experiment is only valid for experiments " - + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " - + "experiment is in one of above statuses... "); - throw exception; - } - } - } catch (RegistryException e) { - logger.error(airavataExperimentId, "Error while updating experiment", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); - throw exception; - } catch (AppCatalogException e) { - logger.error(airavataExperimentId, "Error while updating experiment", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating experiment. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + registryService.updateExperiment(airavataExperimentId, experiment); } /** @@ -4196,78 +1967,8 @@ public void updateExperiment(String airavataExperimentId, ExperimentModel experi * @param experiment */ @Override - public String createExperiment(String gatewayId, ExperimentModel experiment) - throws RegistryServiceException, TException { - try { - if (!validateString(experiment.getExperimentName())) { - logger.error("Cannot create experiments with empty experiment name"); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Cannot create experiments with empty experiment name"); - throw exception; - } - logger.info("Creating experiment with name " + experiment.getExperimentName()); - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - - if (experiment.getUserConfigurationData() != null - && experiment.getUserConfigurationData().getComputationalResourceScheduling() != null - && experiment - .getUserConfigurationData() - .getComputationalResourceScheduling() - .getResourceHostId() - != null) { - - String compResourceId = experiment - .getUserConfigurationData() - .getComputationalResourceScheduling() - .getResourceHostId(); - ComputeResourceDescription computeResourceDescription = - new ComputeResourceRepository().getComputeResource(compResourceId); - if (!computeResourceDescription.isEnabled()) { - logger.error("Compute Resource is not enabled by the Admin!"); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Compute Resource is not enabled by the Admin!"); - throw exception; - } - } else if (!experiment - .getUserConfigurationData() - .getAutoScheduledCompResourceSchedulingList() - .isEmpty()) { - for (ComputationalResourceSchedulingModel computationalResourceScheduling : - experiment.getUserConfigurationData().getAutoScheduledCompResourceSchedulingList()) { - ComputeResourceDescription computeResourceDescription = new ComputeResourceRepository() - .getComputeResource(computationalResourceScheduling.getResourceHostId()); - if (!computeResourceDescription.isEnabled()) { - logger.error("Compute Resource with id" + computationalResourceScheduling.getResourceHostId() - + "" + " is not enabled by the Admin!"); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage( - "Compute Resource with id" + computationalResourceScheduling.getResourceHostId() + "" - + " is not enabled by the Admin!"); - throw exception; - } - } - } - - experiment.setGatewayId(gatewayId); - String experimentId = experimentRepository.addExperiment(experiment); - if (experiment.getExperimentType() == ExperimentType.WORKFLOW) { - workflowRepository.registerWorkflow(experiment.getWorkflow(), experimentId); - } - logger.debug( - experimentId, "Created new experiment with experiment name {}", experiment.getExperimentName()); - return experimentId; - } catch (Exception e) { - logger.error("Error while creating the experiment with experiment name {}", experiment.getExperimentName()); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while creating the experiment. More info : " + e.getMessage()); - throw exception; - } + public String createExperiment(String gatewayId, ExperimentModel experiment) throws RegistryServiceException { + return registryService.createExperiment(gatewayId, experiment); } /** @@ -4290,71 +1991,8 @@ public List searchExperiments( Map filters, int limit, int offset) - throws RegistryServiceException, TException { - if (!validateString(userName)) { - logger.error("Username cannot be empty. Please provide a valid user.."); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Username cannot be empty. Please provide a valid user.."); - throw exception; - } - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - try { - if (!userRepository.isUserExists(gatewayId, userName)) { - logger.error("User does not exist in the system. Please provide a valid user.."); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("User does not exist in the system. Please provide a valid user.."); - throw exception; - } - List summaries = new ArrayList(); - Map regFilters = new HashMap(); - regFilters.put(Constants.FieldConstants.ExperimentConstants.GATEWAY_ID, gatewayId); - for (Map.Entry entry : filters.entrySet()) { - if (entry.getKey().equals(ExperimentSearchFields.EXPERIMENT_NAME)) { - regFilters.put(Constants.FieldConstants.ExperimentConstants.EXPERIMENT_NAME, entry.getValue()); - } else if (entry.getKey().equals(ExperimentSearchFields.EXPERIMENT_DESC)) { - regFilters.put(Constants.FieldConstants.ExperimentConstants.DESCRIPTION, entry.getValue()); - } else if (entry.getKey().equals(ExperimentSearchFields.APPLICATION_ID)) { - regFilters.put(Constants.FieldConstants.ExperimentConstants.EXECUTION_ID, entry.getValue()); - } else if (entry.getKey().equals(ExperimentSearchFields.STATUS)) { - regFilters.put(Constants.FieldConstants.ExperimentConstants.EXPERIMENT_STATUS, entry.getValue()); - } else if (entry.getKey().equals(ExperimentSearchFields.FROM_DATE)) { - regFilters.put(Constants.FieldConstants.ExperimentConstants.FROM_DATE, entry.getValue()); - } else if (entry.getKey().equals(ExperimentSearchFields.TO_DATE)) { - regFilters.put(Constants.FieldConstants.ExperimentConstants.TO_DATE, entry.getValue()); - } else if (entry.getKey().equals(ExperimentSearchFields.PROJECT_ID)) { - regFilters.put(Constants.FieldConstants.ExperimentConstants.PROJECT_ID, entry.getValue()); - } else if (entry.getKey().equals(ExperimentSearchFields.USER_NAME)) { - regFilters.put(Constants.FieldConstants.ExperimentConstants.USER_NAME, entry.getValue()); - } else if (entry.getKey().equals(ExperimentSearchFields.JOB_ID)) { - regFilters.put(Constants.FieldConstants.JobConstants.JOB_ID, entry.getValue()); - } - } - - if (accessibleExpIds.size() == 0 && !ServerSettings.isEnableSharing()) { - if (!regFilters.containsKey(DBConstants.Experiment.USER_NAME)) { - regFilters.put(DBConstants.Experiment.USER_NAME, userName); - } - } - summaries = experimentSummaryRepository.searchAllAccessibleExperiments( - accessibleExpIds, - regFilters, - limit, - offset, - Constants.FieldConstants.ExperimentConstants.CREATION_TIME, - ResultOrderType.DESC); - logger.debug("Airavata retrieved experiments for user : " + userName + " and gateway id : " + gatewayId); - return summaries; - } catch (Exception e) { - logger.error("Error while retrieving experiments", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving experiments. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.searchExperiments(gatewayId, userName, accessibleExpIds, filters, limit, offset); } /** @@ -4376,58 +2014,8 @@ public List searchProjects( Map filters, int limit, int offset) - throws RegistryServiceException, TException { - if (!validateString(userName)) { - logger.error("Username cannot be empty. Please provide a valid user.."); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Username cannot be empty. Please provide a valid user.."); - throw exception; - } - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - try { - if (!userRepository.isUserExists(gatewayId, userName)) { - logger.error("User does not exist in the system. Please provide a valid user.."); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("User does not exist in the system. Please provide a valid user.."); - throw exception; - } - List projects = new ArrayList<>(); - Map regFilters = new HashMap<>(); - regFilters.put(Constants.FieldConstants.ProjectConstants.GATEWAY_ID, gatewayId); - for (Map.Entry entry : filters.entrySet()) { - if (entry.getKey().equals(ProjectSearchFields.PROJECT_NAME)) { - regFilters.put(Constants.FieldConstants.ProjectConstants.PROJECT_NAME, entry.getValue()); - } else if (entry.getKey().equals(ProjectSearchFields.PROJECT_DESCRIPTION)) { - regFilters.put(Constants.FieldConstants.ProjectConstants.DESCRIPTION, entry.getValue()); - } - } - - if (accessibleProjIds.size() == 0 && !ServerSettings.isEnableSharing()) { - if (!regFilters.containsKey(DBConstants.Project.OWNER)) { - regFilters.put(DBConstants.Project.OWNER, userName); - } - } - - projects = projectRepository.searchAllAccessibleProjects( - accessibleProjIds, - regFilters, - limit, - offset, - Constants.FieldConstants.ProjectConstants.CREATION_TIME, - ResultOrderType.DESC); - logger.debug("Airavata retrieved projects for user : " + userName + " and gateway id : " + gatewayId); - return projects; - } catch (Exception e) { - logger.error("Error while retrieving projects", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving projects. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.searchProjects(gatewayId, userName, accessibleProjIds, filters, limit, offset); } /** @@ -4439,30 +2027,8 @@ public List searchProjects( * Currently this does not return any value. */ @Override - public void updateProject(String projectId, Project updatedProject) throws RegistryServiceException, TException { - if (!validateString(projectId) || !validateString(projectId)) { - logger.error("Project id cannot be empty..."); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Project id cannot be empty..."); - throw exception; - } - try { - if (!projectRepository.isProjectExist(projectId)) { - logger.error("Project does not exist in the system. Please provide a valid project ID..."); - ProjectNotFoundException exception = new ProjectNotFoundException(); - exception.setMessage("Project does not exist in the system. Please provide a valid project ID..."); - throw exception; - } - - projectRepository.updateProject(updatedProject, projectId); - logger.debug("Airavata updated project with project Id : " + projectId); - } catch (RegistryException e) { - logger.error("Error while updating the project", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating the project. More info : " + e.getMessage()); - throw exception; - } + public void updateProject(String projectId, Project updatedProject) throws RegistryServiceException { + registryService.updateProject(projectId, updatedProject); } /** @@ -4473,41 +2039,13 @@ public void updateProject(String projectId, Project updatedProject) throws Regis * @param project */ @Override - public String createProject(String gatewayId, Project project) throws RegistryServiceException, TException { - try { - if (!validateString(project.getName()) || !validateString(project.getOwner())) { - logger.error("Project name and owner cannot be empty..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - if (!validateString(gatewayId)) { - logger.error("Gateway ID cannot be empty..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - if (!isGatewayExistInternal(gatewayId)) { - logger.error("Gateway does not exist.Please provide a valid gateway id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - String projectId = projectRepository.addProject(project, gatewayId); - return projectId; - } catch (Exception e) { - logger.error("Error while creating the project", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while creating the project. More info : " + e.getMessage()); - throw exception; - } + public String createProject(String gatewayId, Project project) throws RegistryServiceException { + return registryService.createProject(gatewayId, project); } @Override - public boolean updateNotification(Notification notification) throws RegistryServiceException, TException { - try { - notificationRepository.updateNotification(notification); - return true; - } catch (RegistryException e) { - logger.error("Error while updating notification", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while getting gateway. More info : " + e.getMessage()); - throw exception; - } + public boolean updateNotification(Notification notification) throws RegistryServiceException { + return registryService.updateNotification(notification); } /** @@ -4517,15 +2055,8 @@ public boolean updateNotification(Notification notification) throws RegistryServ * @param notification */ @Override - public String createNotification(Notification notification) throws RegistryServiceException, TException { - try { - return notificationRepository.createNotification(notification); - } catch (RegistryException e) { - logger.error("Error while creating notification", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while creating notification. More info : " + e.getMessage()); - throw exception; - } + public String createNotification(Notification notification) throws RegistryServiceException { + return registryService.createNotification(notification); } /** @@ -4538,41 +2069,8 @@ public String createNotification(Notification notification) throws RegistryServi * @throws AiravataClientException */ @Override - public boolean updateGateway(String gatewayId, Gateway updatedGateway) throws RegistryServiceException, TException { - try { - if (!gatewayRepository.isGatewayExist(gatewayId)) { - logger.error("Gateway does not exist in the system. Please provide a valid gateway ID..."); - AiravataSystemException exception = new AiravataSystemException(); - exception.setMessage("Gateway does not exist in the system. Please provide a valid gateway ID..."); - throw exception; - } - gatewayRepository.updateGateway(gatewayId, updatedGateway); - - // check if gatewayprofile exists and check if the identity server password token equals the admin password - // token, if not update - GatewayResourceProfile existingGwyResourceProfile = - new GwyResourceProfileRepository().getGatewayProfile(gatewayId); - if (existingGwyResourceProfile.getIdentityServerPwdCredToken() == null - || !existingGwyResourceProfile - .getIdentityServerPwdCredToken() - .equals(updatedGateway.getIdentityServerPasswordToken())) { - existingGwyResourceProfile.setIdentityServerPwdCredToken( - updatedGateway.getIdentityServerPasswordToken()); - new GwyResourceProfileRepository().updateGatewayResourceProfile(gatewayId, existingGwyResourceProfile); - } - logger.debug("Airavata update gateway with gateway id : " + gatewayId); - return true; - } catch (RegistryException e) { - logger.error("Error while updating the gateway", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating the gateway. More info : " + e.getMessage()); - throw exception; - } catch (AppCatalogException e) { - logger.error("Error while updating gateway profile", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating gateway profile. More info : " + e.getMessage()); - throw exception; - } + public boolean updateGateway(String gatewayId, Gateway updatedGateway) throws RegistryServiceException { + return registryService.updateGateway(gatewayId, updatedGateway); } /** @@ -4583,81 +2081,26 @@ public boolean updateGateway(String gatewayId, Gateway updatedGateway) throws Re * Th unique identifier of the newly registered gateway. */ @Override - public String addGateway(Gateway gateway) throws RegistryServiceException, DuplicateEntryException, TException { - try { - if (!validateString(gateway.getGatewayId())) { - logger.error("Gateway id cannot be empty..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - // check if gateway exists - if (isGatewayExist(gateway.getGatewayId())) { - throw new DuplicateEntryException( - "Gateway with gatewayId: " + gateway.getGatewayId() + ", already exists in ExperimentCatalog."); - } - // check if gatewayresourceprofile exists - if (new GwyResourceProfileRepository().isGatewayResourceProfileExists(gateway.getGatewayId())) { - throw new DuplicateEntryException("GatewayResourceProfile with gatewayId: " + gateway.getGatewayId() - + ", already exists in AppCatalog."); - } - - // add gateway in experiment catalog - String gatewayId = gatewayRepository.addGateway(gateway); - - // add gatewayresourceprofile in appCatalog - GatewayResourceProfile gatewayResourceProfile = new GatewayResourceProfile(); - gatewayResourceProfile.setGatewayID(gatewayId); - gatewayResourceProfile.setIdentityServerTenant(gatewayId); - gatewayResourceProfile.setIdentityServerPwdCredToken(gateway.getIdentityServerPasswordToken()); - new GwyResourceProfileRepository().addGatewayResourceProfile(gatewayResourceProfile); - logger.debug("Airavata added gateway with gateway id : " + gateway.getGatewayId()); - return gatewayId; - } catch (RegistryException e) { - logger.error("Error while adding gateway", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while adding gateway. More info : " + e.getMessage()); - throw exception; - } catch (AppCatalogException e) { - logger.error("Error while adding gateway profile", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while adding gateway profile. More info : " + e.getMessage()); - throw exception; - } - } - - private boolean validateString(String name) { - boolean valid = true; - if (name == null || name.equals("") || name.trim().length() == 0) { - valid = false; - } - return valid; - } - - /*Following method wraps the logic of isGatewayExist method and this is to be called by any other method of the API as needed.*/ - private boolean isGatewayExistInternal(String gatewayId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, AuthorizationException, - TException { - try { - return gatewayRepository.isGatewayExist(gatewayId); - } catch (RegistryException e) { - logger.error("Error while getting gateway", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while getting gateway. More info : " + e.getMessage()); - throw exception; - } + public String addGateway(Gateway gateway) throws RegistryServiceException, DuplicateEntryException { + return registryService.addGateway(gateway); } /*This private method wraps the logic of getExperiment method as this method is called internally in the API.*/ private ExperimentModel getExperimentInternal(String airavataExperimentId) - throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, TException { + throws RegistryServiceException, ExperimentNotFoundException { try { - if (!experimentRepository.isExperimentExist(airavataExperimentId)) { - throw new ExperimentNotFoundException( - "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + return registryService.getExperiment(airavataExperimentId); + } catch (RegistryServiceException e) { + // Check if this is a "not found" error based on the message + if (e.getMessage() != null && e.getMessage().contains("does not exist")) { + logger.error("Experiment not found: " + airavataExperimentId, e); + ExperimentNotFoundException exception = new ExperimentNotFoundException(); + exception.setMessage( + "Requested experiment id " + airavataExperimentId + " does not exist in the system."); + throw exception; } - return experimentRepository.getExperiment(airavataExperimentId); - } catch (RegistryException e) { + throw e; + } catch (Throwable e) { logger.error("Error while retrieving the experiment", e); RegistryServiceException exception = new RegistryServiceException(); exception.setMessage("Error while retrieving the experiment. More info : " + e.getMessage()); @@ -4665,81 +2108,6 @@ private ExperimentModel getExperimentInternal(String airavataExperimentId) } } - /*Private method wraps the logic of getExperimentStatus method since this method is called internally.*/ - private ExperimentStatus getExperimentStatusInternal(String airavataExperimentId) - throws InvalidRequestException, ExperimentNotFoundException, AiravataClientException, - AiravataSystemException, TException { - try { - if (!experimentRepository.isExperimentExist(airavataExperimentId)) { - logger.error( - airavataExperimentId, - "Error while retrieving experiment status, experiment {} doesn't exist.", - airavataExperimentId); - throw new ExperimentNotFoundException( - "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); - } - return experimentStatusRepository.getExperimentStatus(airavataExperimentId); - } catch (Exception e) { - logger.error(airavataExperimentId, "Error while retrieving the experiment status", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving the experiment status. More info : " + e.getMessage()); - throw exception; - } - } - - /*This private method wraps the logic of getApplicationOutputs method as this method is called internally in the API.*/ - private List getApplicationOutputsInternal(String appInterfaceId) - throws InvalidRequestException, AiravataClientException, AiravataSystemException, TException { - try { - List applicationOutputs = - applicationInterfaceRepository.getApplicationOutputs(appInterfaceId); - logger.debug("Airavata retrieved application outputs for application interface id : " + appInterfaceId); - return applicationOutputs; - } catch (AppCatalogException e) { - logger.error(appInterfaceId, "Error while retrieving application outputs...", e); - AiravataSystemException exception = new AiravataSystemException(); - exception.setAiravataErrorType(AiravataErrorType.INTERNAL_ERROR); - exception.setMessage("Error while retrieving application outputs. More info : " + e.getMessage()); - throw exception; - } - } - - private String addJobSubmissionInterface( - ComputeResourceRepository computeResourceRepository, - String computeResourceId, - String jobSubmissionInterfaceId, - JobSubmissionProtocol protocolType, - int priorityOrder) - throws AppCatalogException { - JobSubmissionInterface jobSubmissionInterface = new JobSubmissionInterface(); - jobSubmissionInterface.setJobSubmissionInterfaceId(jobSubmissionInterfaceId); - jobSubmissionInterface.setPriorityOrder(priorityOrder); - jobSubmissionInterface.setJobSubmissionProtocol(protocolType); - return computeResourceRepository.addJobSubmissionProtocol(computeResourceId, jobSubmissionInterface); - } - - private String addDataMovementInterface( - ComputeResource computeResource, - String computeResourceId, - DMType dmType, - String dataMovementInterfaceId, - DataMovementProtocol protocolType, - int priorityOrder) - throws AppCatalogException { - DataMovementInterface dataMovementInterface = new DataMovementInterface(); - dataMovementInterface.setDataMovementInterfaceId(dataMovementInterfaceId); - dataMovementInterface.setPriorityOrder(priorityOrder); - dataMovementInterface.setDataMovementProtocol(protocolType); - if (dmType.equals(DMType.COMPUTE_RESOURCE)) { - return computeResource.addDataMovementProtocol(computeResourceId, dmType, dataMovementInterface); - } else if (dmType.equals(DMType.STORAGE_RESOURCE)) { - dataMovementInterface.setStorageResourceId(computeResourceId); - return storageResourceRepository.addDataMovementInterface(dataMovementInterface); - } - return null; - } - /** * Register a User Resource Profile. * @@ -4750,65 +2118,13 @@ private String addDataMovementInterface( * Returns a success/failure of the update. */ @Override - public String registerUserResourceProfile(UserResourceProfile userResourceProfile) - throws RegistryServiceException, TException { - try { - if (!validateString(userResourceProfile.getUserId())) { - logger.error("Cannot create user resource profile with empty user id"); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Cannot create user resource profile with empty gateway id"); - throw exception; - } - if (!validateString(userResourceProfile.getGatewayID())) { - logger.error("Cannot create user resource profile with empty gateway id"); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Cannot create user resource profile with empty gateway id"); - throw exception; - } - - if (!userRepository.isUserExists(userResourceProfile.getGatewayID(), userResourceProfile.getUserId())) { - logger.error("User does not exist.Please provide a valid user ID..."); - throw new RegistryServiceException("User does not exist.Please provide a valid user ID..."); - } - String resourceProfile = userResourceProfileRepository.addUserResourceProfile(userResourceProfile); - logger.debug("Airavata registered user resource profile with gateway id : " - + userResourceProfile.getGatewayID() + "and user id : " + userResourceProfile.getUserId()); - return resourceProfile; - } catch (AppCatalogException e) { - logger.error("Error while registering user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while registering user resource profile. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error("Error while registering user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while registering user resource profile. More info : " + e.getMessage()); - throw exception; - } + public String registerUserResourceProfile(UserResourceProfile userResourceProfile) throws RegistryServiceException { + return registryService.registerUserResourceProfile(userResourceProfile); } @Override - public boolean isUserResourceProfileExists(String userId, String gatewayId) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayId, userId)) { - logger.error("user does not exist.Please provide a valid gateway id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - return userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayId); - } catch (AppCatalogException e) { - logger.error("Error while checking existence of user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while checking existence of user resource profile. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error("Error while checking existence of user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while checking existence of user resource profile. More info : " + e.getMessage()); - throw exception; - } + public boolean isUserResourceProfileExists(String userId, String gatewayId) throws RegistryServiceException { + return registryService.isUserResourceProfileExists(userId, gatewayId); } /** @@ -4818,28 +2134,8 @@ public boolean isUserResourceProfileExists(String userId, String gatewayId) * @return UserResourceProfile object */ @Override - public UserResourceProfile getUserResourceProfile(String userId, String gatewayId) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayId, userId)) { - logger.error("user does not exist.Please provide a valid gateway id..."); - throw new AiravataSystemException(AiravataErrorType.INTERNAL_ERROR); - } - UserResourceProfile userResourceProfile = - userResourceProfileRepository.getUserResourceProfile(userId, gatewayId); - logger.debug("Airavata retrieved User resource profile with user id : " + userId); - return userResourceProfile; - } catch (AppCatalogException e) { - logger.error("Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error("Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + public UserResourceProfile getUserResourceProfile(String userId, String gatewayId) throws RegistryServiceException { + return registryService.getUserResourceProfile(userId, gatewayId); } /** @@ -4852,26 +2148,8 @@ public UserResourceProfile getUserResourceProfile(String userId, String gatewayI */ @Override public boolean updateUserResourceProfile(String userId, String gatewayID, UserResourceProfile userResourceProfile) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayID, userId)) { - logger.error("User does not exist.Please provide a valid user id..."); - throw new RegistryServiceException("user does not exist.Please provide a valid user id..."); - } - userResourceProfileRepository.updateUserResourceProfile(userId, gatewayID, userResourceProfile); - logger.debug("Airavata updated gateway profile with gateway id : " + userId); - return true; - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while updating gateway resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating gateway resource profile. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateUserResourceProfile(userId, gatewayID, userResourceProfile); } /** @@ -4883,46 +2161,13 @@ public boolean updateUserResourceProfile(String userId, String gatewayID, UserRe * Returns a success/failure of the deletion. */ @Override - public boolean deleteUserResourceProfile(String userId, String gatewayID) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayID, userId)) { - logger.error("user does not exist.Please provide a valid user id..."); - throw new RegistryServiceException("user does not exist.Please provide a valid user id..."); - } - userResourceProfileRepository.removeUserResourceProfile(userId, gatewayID); - logger.debug("Airavata deleted User profile with gateway id : " + gatewayID + " and user id : " + userId); - return true; - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while removing User resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while removing User resource profile. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + public boolean deleteUserResourceProfile(String userId, String gatewayID) throws RegistryServiceException { + return registryService.deleteUserResourceProfile(userId, gatewayID); } @Override - public String addUser(UserProfile userProfile) - throws RegistryServiceException, DuplicateEntryException, TException { - try { - logger.info("Adding User in Registry: " + userProfile); - if (isUserExists(userProfile.getGatewayId(), userProfile.getUserId())) { - throw new DuplicateEntryException("User already exists, with userId: " + userProfile.getUserId() - + ", and gatewayId: " + userProfile.getGatewayId()); - } - UserProfile savedUser = userRepository.addUser(userProfile); - return savedUser.getUserId(); - } catch (RegistryException ex) { - logger.error("Error while adding user in registry: " + ex, ex); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage("Error while adding user in registry: " + ex.getMessage()); - throw rse; - } + public String addUser(UserProfile userProfile) throws RegistryServiceException, DuplicateEntryException { + return registryService.addUser(userProfile); } /** @@ -4942,35 +2187,9 @@ public boolean addUserComputeResourcePreference( String gatewayID, String computeResourceId, UserComputeResourcePreference userComputeResourcePreference) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayID, userId)) { - logger.error("user does not exist.Please provide a valid user id..."); - throw new RegistryServiceException("user does not exist.Please provide a valid user id..."); - } - if (!userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { - throw new RegistryServiceException("User resource profile with user id'" + userId + " & gateway Id" - + gatewayID + "' does not exist!!!"); - } - UserResourceProfile profile = userResourceProfileRepository.getUserResourceProfile(userId, gatewayID); - // gatewayProfile.removeGatewayResourceProfile(gatewayID); - profile.addToUserComputeResourcePreferences(userComputeResourcePreference); - userResourceProfileRepository.updateUserResourceProfile(userId, gatewayID, profile); - logger.debug("Airavata added User compute resource preference with gateway id : " + gatewayID - + " and for compute resource id : " + computeResourceId); - return true; - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while registering User resource profile preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while registering user resource profile preference. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addUserComputeResourcePreference( + userId, gatewayID, computeResourceId, userComputeResourcePreference); } /** @@ -4984,25 +2203,8 @@ public boolean addUserComputeResourcePreference( */ @Override public boolean isUserComputeResourcePreferenceExists(String userId, String gatewayID, String computeResourceId) - throws RegistryServiceException, TException { - try { - if (userRepository.isUserExists(gatewayID, userId) - && userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { - return userResourceProfileRepository.isUserComputeResourcePreferenceExists( - userId, gatewayID, computeResourceId); - } - return false; - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while fetching compute resource preference", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while fetching compute resource preference. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while fetching compute resource preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while fetching compute resource preference. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.isUserComputeResourcePreferenceExists(userId, gatewayID, computeResourceId); } /** @@ -5018,36 +2220,8 @@ public boolean isUserComputeResourcePreferenceExists(String userId, String gatew @Override public boolean addUserStoragePreference( String userId, String gatewayID, String storageResourceId, UserStoragePreference dataStoragePreference) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayID, userId)) { - logger.error("user does not exist.Please provide a valid user id..."); - throw new RegistryServiceException("user does not exist.Please provide a valid user id..."); - } - if (!userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { - throw new RegistryServiceException("User resource profile with user id'" + userId + " & gateway Id" - + gatewayID + "' does not exist!!!"); - } - UserResourceProfile profile = userResourceProfileRepository.getUserResourceProfile(userId, gatewayID); - // gatewayProfile.removeGatewayResourceProfile(gatewayID); - dataStoragePreference.setStorageResourceId(storageResourceId); - profile.addToUserStoragePreferences(dataStoragePreference); - userResourceProfileRepository.updateUserResourceProfile(userId, gatewayID, profile); - logger.debug("Airavata added storage resource preference with gateway id : " + gatewayID - + " and for storage resource id : " + storageResourceId); - return true; - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while registering user resource profile preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while registering user resource profile preference. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.addUserStoragePreference(userId, gatewayID, storageResourceId, dataStoragePreference); } /** @@ -5061,43 +2235,8 @@ public boolean addUserStoragePreference( */ @Override public UserComputeResourcePreference getUserComputeResourcePreference( - String userId, String gatewayID, String userComputeResourceId) throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayID, userId)) { - logger.error("user does not exist.Please provide a valid user id..."); - throw new RegistryServiceException("user does not exist.Please provide a valid user id..."); - } - if (!userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { - throw new RegistryServiceException("User resource profile with user id'" + userId + " & gateway Id" - + gatewayID + "' does not exist!!!"); - } - ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); - if (!computeResourceRepository.isComputeResourceExists(userComputeResourceId)) { - logger.error( - userComputeResourceId, - "Given compute resource does not exist in the system. Please provide a valid compute resource id..."); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Given compute resource does not exist in the system. Please provide a valid compute resource id..."); - throw exception; - } - UserComputeResourcePreference userComputeResourcePreference = - userResourceProfileRepository.getUserComputeResourcePreference( - userId, gatewayID, userComputeResourceId); - logger.debug("Airavata retrieved user compute resource preference with gateway id : " + gatewayID - + " and for compute resoruce id : " + userComputeResourceId); - return userComputeResourcePreference; - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while reading user compute resource preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while reading user compute resource preference. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + String userId, String gatewayID, String userComputeResourceId) throws RegistryServiceException { + return registryService.getUserComputeResourcePreference(userId, gatewayID, userComputeResourceId); } /** @@ -5111,33 +2250,8 @@ public UserComputeResourcePreference getUserComputeResourcePreference( */ @Override public UserStoragePreference getUserStoragePreference(String userId, String gatewayID, String storageId) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayID, userId)) { - logger.error("user does not exist.Please provide a valid user id..."); - throw new RegistryServiceException("user does not exist.Please provide a valid user id..."); - } - if (!userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { - throw new RegistryServiceException("User resource profile with user id'" + userId + " & gateway Id" - + gatewayID + "' does not exist!!!"); - } - - UserStoragePreference storagePreference = - userResourceProfileRepository.getUserStoragePreference(userId, gatewayID, storageId); - logger.debug("Airavata retrieved user storage resource preference with gateway id : " + gatewayID - + " and for storage resource id : " + storageId); - return storagePreference; - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while reading gateway data storage preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while reading gateway data storage preference. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getUserStoragePreference(userId, gatewayID, storageId); } /** @@ -5147,14 +2261,8 @@ public UserStoragePreference getUserStoragePreference(String userId, String gate * Returns all the UserResourceProfile list object. */ @Override - public List getAllUserResourceProfiles() throws RegistryServiceException, TException { - try { - return userResourceProfileRepository.getAllUserResourceProfiles(); - } catch (AppCatalogException e) { - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while reading retrieving all gateway profiles. More info : " + e.getMessage()); - throw exception; - } + public List getAllUserResourceProfiles() throws RegistryServiceException { + return registryService.getAllUserResourceProfiles(); } /** @@ -5173,42 +2281,9 @@ public boolean updateUserComputeResourcePreference( String gatewayID, String computeResourceId, UserComputeResourcePreference userComputeResourcePreference) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayID, userId)) { - logger.error("user does not exist.Please provide a valid user id..."); - throw new RegistryServiceException("user does not exist.Please provide a valid user id..."); - } - UserResourceProfile profile = userResourceProfileRepository.getUserResourceProfile(userId, gatewayID); - List userComputeResourcePreferences = - profile.getUserComputeResourcePreferences(); - UserComputeResourcePreference preferenceToRemove = null; - for (UserComputeResourcePreference preference : userComputeResourcePreferences) { - if (preference.getComputeResourceId().equals(computeResourceId)) { - preferenceToRemove = preference; - break; - } - } - if (preferenceToRemove != null) { - profile.getUserComputeResourcePreferences().remove(preferenceToRemove); - } - profile.getUserComputeResourcePreferences().add(userComputeResourcePreference); - userResourceProfileRepository.updateUserResourceProfile(userId, gatewayID, profile); - logger.debug("Airavata updated compute resource preference with gateway id : " + gatewayID - + " and for compute resource id : " + computeResourceId); - return true; - } catch (AppCatalogException e) { - logger.error(userId, "Error while reading user compute resource preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while updating user compute resource preference. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateUserComputeResourcePreference( + userId, gatewayID, computeResourceId, userComputeResourcePreference); } /** @@ -5224,40 +2299,8 @@ public boolean updateUserComputeResourcePreference( @Override public boolean updateUserStoragePreference( String userId, String gatewayID, String storageId, UserStoragePreference userStoragePreference) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayID, userId)) { - logger.error("user does not exist.Please provide a valid user id..."); - throw new RegistryServiceException("user does not exist.Please provide a valid user id..."); - } - UserResourceProfile profile = userResourceProfileRepository.getUserResourceProfile(userId, gatewayID); - List dataStoragePreferences = profile.getUserStoragePreferences(); - UserStoragePreference preferenceToRemove = null; - for (UserStoragePreference preference : dataStoragePreferences) { - if (preference.getStorageResourceId().equals(storageId)) { - preferenceToRemove = preference; - break; - } - } - if (preferenceToRemove != null) { - profile.getUserStoragePreferences().remove(preferenceToRemove); - } - profile.getUserStoragePreferences().add(userStoragePreference); - userResourceProfileRepository.updateUserResourceProfile(userId, gatewayID, profile); - logger.debug("Airavata updated user storage resource preference with gateway id : " + gatewayID - + " and for storage resource id : " + storageId); - return true; - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while reading user data storage preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating user data storage preference. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.updateUserStoragePreference(userId, gatewayID, storageId, userStoragePreference); } /** @@ -5271,26 +2314,8 @@ public boolean updateUserStoragePreference( */ @Override public boolean deleteUserComputeResourcePreference(String userId, String gatewayID, String computeResourceId) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayID, userId)) { - logger.error("user does not exist.Please provide a valid user id..."); - throw new RegistryServiceException("user does not exist.Please provide a valid user id..."); - } - return userResourceProfileRepository.removeUserComputeResourcePreferenceFromGateway( - userId, gatewayID, computeResourceId); - } catch (AppCatalogException e) { - logger.error(userId, "Error while reading user compute resource preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage( - "Error while updating user compute resource preference. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.deleteUserComputeResourcePreference(userId, gatewayID, computeResourceId); } /** @@ -5304,25 +2329,8 @@ public boolean deleteUserComputeResourcePreference(String userId, String gateway */ @Override public boolean deleteUserStoragePreference(String userId, String gatewayID, String storageId) - throws RegistryServiceException, TException { - try { - if (!userRepository.isUserExists(gatewayID, userId)) { - logger.error("user does not exist.Please provide a valid user id..."); - throw new RegistryServiceException("user does not exist.Please provide a valid user id..."); - } - return userResourceProfileRepository.removeUserDataStoragePreferenceFromGateway( - userId, gatewayID, storageId); - } catch (AppCatalogException e) { - logger.error(gatewayID, "Error while reading user data storage preference...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while updating user data storage preference. More info : " + e.getMessage()); - throw exception; - } catch (RegistryException e) { - logger.error(userId, "Error while retrieving user resource profile...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while retrieving user resource profile. More info : " + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.deleteUserStoragePreference(userId, gatewayID, storageId); } /** @@ -5330,56 +2338,18 @@ public boolean deleteUserStoragePreference(String userId, String gatewayID, Stri * * */ @Override - public List getLatestQueueStatuses() throws RegistryServiceException, TException { - try { - List queueStatusModels = queueStatusRepository.getLatestQueueStatuses(); - return queueStatusModels; - } catch (RegistryException e) { - logger.error("Error while reading queue status models....", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while reading queue status models.... : " + e.getMessage()); - throw exception; - } + public List getLatestQueueStatuses() throws RegistryServiceException { + return registryService.getLatestQueueStatuses(); } @Override - public void registerQueueStatuses(List queueStatuses) - throws RegistryServiceException, TException { - try { - queueStatusRepository.createQueueStatuses(queueStatuses); - } catch (RegistryException e) { - logger.error("Error while storing queue status models....", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while storing queue status models.... : " + e.getMessage()); - throw exception; - } + public void registerQueueStatuses(List queueStatuses) throws RegistryServiceException { + registryService.registerQueueStatuses(queueStatuses); } @Override - public QueueStatusModel getQueueStatus(String hostName, String queueName) - throws RegistryServiceException, TException { - try { - Optional optionalQueueStatusModel = - queueStatusRepository.getQueueStatus(hostName, queueName); - logger.info("Executed and present " + optionalQueueStatusModel.isPresent()); - if (optionalQueueStatusModel.isPresent()) { - return optionalQueueStatusModel.get(); - } else { - QueueStatusModel queueStatusModel = new QueueStatusModel(); - queueStatusModel.setHostName(hostName); - queueStatusModel.setQueueName(queueName); - queueStatusModel.setQueueUp(false); - queueStatusModel.setRunningJobs(0); - queueStatusModel.setQueuedJobs(0); - queueStatusModel.setTime(0); - return queueStatusModel; - } - } catch (RegistryException e) { - logger.error("Error while storing queue status models....", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while storing queue status models.... : " + e.getMessage()); - throw exception; - } + public QueueStatusModel getQueueStatus(String hostName, String queueName) throws RegistryServiceException { + return registryService.getQueueStatus(hostName, queueName); } /** @@ -5392,23 +2362,8 @@ public QueueStatusModel getQueueStatus(String hostName, String queueName) */ @Override public List getAllUserComputeResourcePreferences(String userId, String gatewayID) - throws RegistryServiceException, TException { - try { - if (!isUserExists(gatewayID, userId)) { - logger.error("User Resource Profile does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException( - "User Resource Profile does not exist.Please provide a valid gateway id..."); - } - return userResourceProfileRepository - .getUserResourceProfile(userId, gatewayID) - .getUserComputeResourcePreferences(); - } catch (AppCatalogException e) { - logger.error(userId, "Error while reading User Resource Profile compute resource preferences...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while reading User Resource Profile compute resource preferences. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getAllUserComputeResourcePreferences(userId, gatewayID); } /** @@ -5421,379 +2376,114 @@ public List getAllUserComputeResourcePreferences( */ @Override public List getAllUserStoragePreferences(String userId, String gatewayID) - throws RegistryServiceException, TException { - try { - if (!isUserExists(gatewayID, userId)) { - logger.error("User does not exist.Please provide a valid gateway id..."); - throw new RegistryServiceException("Gateway does not exist.Please provide a valid gateway id..."); - } - return userResourceProfileRepository - .getUserResourceProfile(userId, gatewayID) - .getUserStoragePreferences(); - } catch (AppCatalogException e) { - logger.error(userId, "Error while reading user resource Profile data storage preferences...", e); - RegistryServiceException exception = new RegistryServiceException(); - exception.setMessage("Error while reading user resource Profile data storage preferences. More info : " - + e.getMessage()); - throw exception; - } + throws RegistryServiceException { + return registryService.getAllUserStoragePreferences(userId, gatewayID); } @Override public void createGatewayGroups(GatewayGroups gatewayGroups) - throws RegistryServiceException, DuplicateEntryException, TException { + throws RegistryServiceException, DuplicateEntryException { try { - if (gatewayGroupsRepository.isExists(gatewayGroups.getGatewayId())) { - logger.error("GatewayGroups already exists for " + gatewayGroups.getGatewayId()); - throw new DuplicateEntryException( - "GatewayGroups for gatewayId: " + gatewayGroups.getGatewayId() + " already exists."); + registryService.createGatewayGroups(gatewayGroups); + } catch (Throwable e) { + if (e.getMessage() != null && e.getMessage().contains("already exists")) { + throw new DuplicateEntryException(e.getMessage()); } - gatewayGroupsRepository.create(gatewayGroups); - } catch (DuplicateEntryException e) { - throw e; // re-throw - } catch (Exception e) { - - final String message = - "Error while creating a GatewayGroups entry for gateway " + gatewayGroups.getGatewayId() + "."; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; + throw convertToRegistryServiceException(e, "Error while creating GatewayGroups"); } } @Override - public void updateGatewayGroups(GatewayGroups gatewayGroups) throws RegistryServiceException, TException { - try { - if (!gatewayGroupsRepository.isExists(gatewayGroups.getGatewayId())) { - final String message = "No GatewayGroups entry exists for " + gatewayGroups.getGatewayId(); - logger.error(message); - throw new RegistryServiceException(message); - } - gatewayGroupsRepository.update(gatewayGroups); - } catch (RegistryServiceException e) { - throw e; // re-throw - } catch (Exception e) { - - final String message = - "Error while updating the GatewayGroups entry for gateway " + gatewayGroups.getGatewayId() + "."; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public void updateGatewayGroups(GatewayGroups gatewayGroups) throws RegistryServiceException { + registryService.updateGatewayGroups(gatewayGroups); } @Override - public boolean isGatewayGroupsExists(String gatewayId) throws RegistryServiceException, TException { - try { - return gatewayGroupsRepository.isExists(gatewayId); - } catch (Exception e) { - final String message = "Error checking existence of the GatewayGroups entry for gateway " + gatewayId + "."; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public boolean isGatewayGroupsExists(String gatewayId) throws RegistryServiceException { + return registryService.isGatewayGroupsExists(gatewayId); } @Override - public GatewayGroups getGatewayGroups(String gatewayId) throws RegistryServiceException, TException { - try { - if (!gatewayGroupsRepository.isExists(gatewayId)) { - final String message = "No GatewayGroups entry exists for " + gatewayId; - logger.error(message); - throw new RegistryServiceException(message); - } - return gatewayGroupsRepository.get(gatewayId); - } catch (RegistryServiceException e) { - throw e; // re-throw - } catch (Exception e) { - - final String message = "Error while retrieving the GatewayGroups entry for gateway " + gatewayId + "."; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public GatewayGroups getGatewayGroups(String gatewayId) throws RegistryServiceException { + return registryService.getGatewayGroups(gatewayId); } @Override - public Parser getParser(String parserId, String gatewayId) throws RegistryServiceException, TException { - - try { - if (!parserRepository.isExists(parserId)) { - final String message = "No Parser Info entry exists for " + parserId; - logger.error(message); - throw new RegistryServiceException(message); - } - return parserRepository.get(parserId); - - } catch (RegistryServiceException e) { - throw e; // re-throw - - } catch (Exception e) { - final String message = "Error while retrieving parser with id " + parserId + "."; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public Parser getParser(String parserId, String gatewayId) throws RegistryServiceException { + return registryService.getParser(parserId, gatewayId); } @Override - public String saveParser(Parser parser) throws RegistryServiceException, TException { - - try { - Parser created = parserRepository.saveParser(parser); - return created.getId(); - - } catch (Exception e) { - final String message = "Error while saving parser with id " + parser.getId(); - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public String saveParser(Parser parser) throws RegistryServiceException { + return registryService.saveParser(parser); } @Override - public List listAllParsers(String gatewayId) throws RegistryServiceException, TException { - - try { - return parserRepository.getAllParsers(gatewayId); - - } catch (Exception e) { - final String message = "Error while listing parsers for gateway " + gatewayId; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public List listAllParsers(String gatewayId) throws RegistryServiceException { + return registryService.listAllParsers(gatewayId); } @Override - public void removeParser(String parserId, String gatewayId) throws RegistryServiceException, TException { - - try { - boolean exists = parserRepository.isExists(parserId); - - if (exists && !gatewayId.equals(parserRepository.get(parserId).getGatewayId())) { - parserRepository.delete(parserId); - } else { - throw new RegistryServiceException("Parser " + parserId + " does not exist"); - } - } catch (RegistryServiceException e) { - throw e; // re-throw - - } catch (Exception e) { - final String message = "Error while removing parser with id " + parserId + "."; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public void removeParser(String parserId, String gatewayId) throws RegistryServiceException { + registryService.removeParser(parserId, gatewayId); } @Override - public ParserInput getParserInput(String parserInputId, String gatewayId) - throws RegistryServiceException, TException { - try { - ParserInput parserInput = parserInputRepository.getParserInput(parserInputId); - // TODO check the gateway - - return parserInput; - } catch (Exception e) { - logger.error("Failed to fetch parser input " + parserInputId + " for gateway " + gatewayId, e); - throw new RegistryServiceException("Failed to fetch parser input " + parserInputId + " for gateway " - + gatewayId + " More info: " + e.getMessage()); - } + public ParserInput getParserInput(String parserInputId, String gatewayId) throws RegistryServiceException { + return registryService.getParserInput(parserInputId, gatewayId); } @Override - public ParserOutput getParserOutput(String parserOutputId, String gatewayId) - throws RegistryServiceException, TException { - try { - ParserOutput parserOutput = parserOutputRepository.getParserOutput(parserOutputId); - // TODO check the gateway - - return parserOutput; - } catch (Exception e) { - logger.error("Failed to fetch parser output " + parserOutputId + " for gateway " + gatewayId, e); - throw new RegistryServiceException("Failed to fetch parser output " + parserOutputId + " for gateway " - + gatewayId + " More info: " + e.getMessage()); - } + public ParserOutput getParserOutput(String parserOutputId, String gatewayId) throws RegistryServiceException { + return registryService.getParserOutput(parserOutputId, gatewayId); } @Override - public ParsingTemplate getParsingTemplate(String templateId, String gatewayId) - throws RegistryServiceException, TException { - - try { - if (!parsingTemplateRepository.isExists(templateId)) { - final String message = "No Parsing Template entry exists for " + templateId; - logger.error(message); - throw new RegistryServiceException(message); - } - return parsingTemplateRepository.get(templateId); - - } catch (RegistryServiceException e) { - throw e; // re-throw - - } catch (Exception e) { - final String message = "Error while retrieving Parsing Template for id " + templateId + "."; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public ParsingTemplate getParsingTemplate(String templateId, String gatewayId) throws RegistryServiceException { + return registryService.getParsingTemplate(templateId, gatewayId); } @Override public List getParsingTemplatesForExperiment(String experimentId, String gatewayId) - throws RegistryServiceException, TException { - - try { - List processes = getExperiment(experimentId).getProcesses(); - if (processes.size() > 0) { - return parsingTemplateRepository.getParsingTemplatesForApplication( - processes.get(processes.size() - 1).getApplicationInterfaceId()); - } - return Collections.emptyList(); - - } catch (Exception e) { - final String message = "Error while retrieving parsing templates for experiment id " + experimentId; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + throws RegistryServiceException { + return registryService.getParsingTemplatesForExperiment(experimentId, gatewayId); } @Override - public String saveParsingTemplate(ParsingTemplate parsingTemplate) throws RegistryServiceException, TException { - - try { - ParsingTemplate saved = parsingTemplateRepository.create(parsingTemplate); - return saved.getId(); - - } catch (Exception e) { - final String message = "Error while saving parsing template with id " + parsingTemplate.getId(); - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public String saveParsingTemplate(ParsingTemplate parsingTemplate) throws RegistryServiceException { + return registryService.saveParsingTemplate(parsingTemplate); } @Override - public List listAllParsingTemplates(String gatewayId) throws RegistryServiceException, TException { - - try { - return parsingTemplateRepository.getAllParsingTemplates(gatewayId); - - } catch (Exception e) { - final String message = "Error while listing parsing templates for gateway " + gatewayId; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public List listAllParsingTemplates(String gatewayId) throws RegistryServiceException { + return registryService.listAllParsingTemplates(gatewayId); } @Override - public void removeParsingTemplate(String templateId, String gatewayId) throws RegistryServiceException, TException { - - try { - boolean exists = parsingTemplateRepository.isExists(templateId); - - if (exists - && !gatewayId.equals( - parsingTemplateRepository.get(templateId).getGatewayId())) { - parsingTemplateRepository.delete(templateId); - } else { - throw new RegistryServiceException("Parsing tempolate " + templateId + " does not exist"); - } - } catch (RegistryServiceException e) { - throw e; // re-throw - - } catch (Exception e) { - - final String message = "Error while removing parsing template with id " + templateId; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + " More info: " + e.getMessage()); - throw rse; - } + public void removeParsingTemplate(String templateId, String gatewayId) throws RegistryServiceException { + registryService.removeParsingTemplate(templateId, gatewayId); } @Override public boolean isGatewayUsageReportingAvailable(String gatewayId, String computeResourceId) - throws RegistryServiceException, TException { - try { - return usageReportingCommandRepository.isGatewayUsageReportingCommandExists(gatewayId, computeResourceId); - } catch (Exception e) { - String message = "Failed to check the availability to find the reporting information for the gateway " - + gatewayId + " and compute resource " + computeResourceId; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + ". More info " + e.getMessage()); - throw rse; - } + throws RegistryServiceException { + return registryService.isGatewayUsageReportingAvailable(gatewayId, computeResourceId); } @Override public GatewayUsageReportingCommand getGatewayReportingCommand(String gatewayId, String computeResourceId) - throws RegistryServiceException, TException { - try { - if (usageReportingCommandRepository.isGatewayUsageReportingCommandExists(gatewayId, computeResourceId)) { - return usageReportingCommandRepository.getGatewayUsageReportingCommand(gatewayId, computeResourceId); - } else { - String message = "No usage reporting information for the gateway " + gatewayId - + " and compute resource " + computeResourceId; - logger.error(message); - throw new RegistryServiceException(message); - } - } catch (RegistryServiceException e) { - throw e; // re-throw - - } catch (Exception e) { - String message = "Failed to check the availability to find the reporting information for the gateway " - + gatewayId + " and compute resource " + computeResourceId; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + ". More info " + e.getMessage()); - throw rse; - } + throws RegistryServiceException { + return registryService.getGatewayReportingCommand(gatewayId, computeResourceId); } @Override - public void addGatewayUsageReportingCommand(GatewayUsageReportingCommand command) - throws RegistryServiceException, TException { - try { - usageReportingCommandRepository.addGatewayUsageReportingCommand(command); - } catch (Exception e) { - String message = "Failed to add the reporting information for the gateway " + command.getGatewayId() - + " and compute resource " + command.getComputeResourceId(); - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + ". More info " + e.getMessage()); - throw rse; - } + public void addGatewayUsageReportingCommand(GatewayUsageReportingCommand command) throws RegistryServiceException { + registryService.addGatewayUsageReportingCommand(command); } @Override public void removeGatewayUsageReportingCommand(String gatewayId, String computeResourceId) - throws RegistryServiceException, TException { - try { - usageReportingCommandRepository.removeGatewayUsageReportingCommand(gatewayId, computeResourceId); - } catch (Exception e) { - String message = "Failed to add the reporting information for the gateway " + gatewayId - + " and compute resource " + computeResourceId; - logger.error(message, e); - RegistryServiceException rse = new RegistryServiceException(); - rse.setMessage(message + ". More info " + e.getMessage()); - throw rse; - } + throws RegistryServiceException { + registryService.removeGatewayUsageReportingCommand(gatewayId, computeResourceId); } } diff --git a/airavata-api/src/main/java/org/apache/airavata/registry/core/repositories/appcatalog/ComputeResourceRepository.java b/airavata-api/src/main/java/org/apache/airavata/registry/core/repositories/appcatalog/ComputeResourceRepository.java index a56cca9f4a..a75ce4488f 100644 --- a/airavata-api/src/main/java/org/apache/airavata/registry/core/repositories/appcatalog/ComputeResourceRepository.java +++ b/airavata-api/src/main/java/org/apache/airavata/registry/core/repositories/appcatalog/ComputeResourceRepository.java @@ -408,6 +408,16 @@ public String addUNICOREJobSubmission(UnicoreJobSubmission unicoreJobSubmission) return unicoreJobSubmission.getJobSubmissionInterfaceId(); } + public void updateUNICOREJobSubmission(UnicoreJobSubmission unicoreJobSubmission) throws AppCatalogException { + Mapper mapper = ObjectMapperSingleton.getInstance(); + UnicoreSubmissionEntity unicoreSubmissionEntity = + mapper.map(unicoreJobSubmission, UnicoreSubmissionEntity.class); + if (unicoreJobSubmission.getSecurityProtocol() != null) { + unicoreSubmissionEntity.setSecurityProtocol(unicoreJobSubmission.getSecurityProtocol()); + } + execute(entityManager -> entityManager.merge(unicoreSubmissionEntity)); + } + @Override public String addLocalDataMovement(LOCALDataMovement localDataMovement) throws AppCatalogException { localDataMovement.setDataMovementInterfaceId(AppCatalogUtils.getID("LOCAL")); diff --git a/airavata-api/src/main/java/org/apache/airavata/service/AiravataService.java b/airavata-api/src/main/java/org/apache/airavata/service/AiravataService.java new file mode 100644 index 0000000000..09a065a4ab --- /dev/null +++ b/airavata-api/src/main/java/org/apache/airavata/service/AiravataService.java @@ -0,0 +1,4960 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.airavata.service; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.function.BiFunction; +import java.util.stream.Collectors; +import org.apache.airavata.accountprovisioning.SSHAccountManager; +import org.apache.airavata.agents.api.AgentAdaptor; +import org.apache.airavata.agents.api.AgentException; +import org.apache.airavata.common.exception.AiravataException; +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.AiravataUtils; +import org.apache.airavata.common.utils.Constants; +import org.apache.airavata.common.utils.ServerSettings; +import org.apache.airavata.credential.store.exception.CredentialStoreException; +import org.apache.airavata.helix.core.support.adaptor.AdaptorSupportImpl; +import org.apache.airavata.messaging.core.MessageContext; +import org.apache.airavata.messaging.core.MessagingFactory; +import org.apache.airavata.messaging.core.Publisher; +import org.apache.airavata.messaging.core.Type; +import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription; +import org.apache.airavata.model.appcatalog.appdeployment.ApplicationModule; +import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription; +import org.apache.airavata.model.appcatalog.computeresource.CloudJobSubmission; +import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription; +import org.apache.airavata.model.appcatalog.computeresource.LOCALSubmission; +import org.apache.airavata.model.appcatalog.computeresource.ResourceJobManager; +import org.apache.airavata.model.appcatalog.computeresource.SSHJobSubmission; +import org.apache.airavata.model.appcatalog.computeresource.UnicoreJobSubmission; +import org.apache.airavata.model.appcatalog.gatewaygroups.GatewayGroups; +import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference; +import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile; +import org.apache.airavata.model.appcatalog.gatewayprofile.StoragePreference; +import org.apache.airavata.model.appcatalog.groupresourceprofile.BatchQueueResourcePolicy; +import org.apache.airavata.model.appcatalog.groupresourceprofile.ComputeResourcePolicy; +import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference; +import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile; +import org.apache.airavata.model.appcatalog.parser.Parser; +import org.apache.airavata.model.appcatalog.parser.ParsingTemplate; +import org.apache.airavata.model.appcatalog.storageresource.StorageDirectoryInfo; +import org.apache.airavata.model.appcatalog.storageresource.StorageResourceDescription; +import org.apache.airavata.model.appcatalog.storageresource.StorageVolumeInfo; +import org.apache.airavata.model.appcatalog.userresourceprofile.UserComputeResourcePreference; +import org.apache.airavata.model.appcatalog.userresourceprofile.UserResourceProfile; +import org.apache.airavata.model.appcatalog.userresourceprofile.UserStoragePreference; +import org.apache.airavata.model.application.io.InputDataObjectType; +import org.apache.airavata.model.application.io.OutputDataObjectType; +import org.apache.airavata.model.commons.airavata_commonsConstants; +import org.apache.airavata.model.credential.store.CredentialSummary; +import org.apache.airavata.model.credential.store.PasswordCredential; +import org.apache.airavata.model.credential.store.SSHCredential; +import org.apache.airavata.model.credential.store.SummaryType; +import org.apache.airavata.model.data.movement.DMType; +import org.apache.airavata.model.data.movement.GridFTPDataMovement; +import org.apache.airavata.model.data.movement.LOCALDataMovement; +import org.apache.airavata.model.data.movement.SCPDataMovement; +import org.apache.airavata.model.data.movement.UnicoreDataMovement; +import org.apache.airavata.model.data.replica.DataProductModel; +import org.apache.airavata.model.data.replica.DataReplicaLocationModel; +import org.apache.airavata.model.error.AiravataErrorType; +import org.apache.airavata.model.error.AiravataSystemException; +import org.apache.airavata.model.error.AuthorizationException; +import org.apache.airavata.model.error.ExperimentNotFoundException; +import org.apache.airavata.model.error.InvalidRequestException; +import org.apache.airavata.model.error.ProjectNotFoundException; +import org.apache.airavata.model.experiment.ExperimentModel; +import org.apache.airavata.model.experiment.ExperimentSearchFields; +import org.apache.airavata.model.experiment.ExperimentStatistics; +import org.apache.airavata.model.experiment.ExperimentSummaryModel; +import org.apache.airavata.model.experiment.ProjectSearchFields; +import org.apache.airavata.model.experiment.UserConfigurationDataModel; +import org.apache.airavata.model.group.ResourcePermissionType; +import org.apache.airavata.model.group.ResourceType; +import org.apache.airavata.model.job.JobModel; +import org.apache.airavata.model.messaging.event.ExperimentIntermediateOutputsEvent; +import org.apache.airavata.model.messaging.event.ExperimentStatusChangeEvent; +import org.apache.airavata.model.messaging.event.ExperimentSubmitEvent; +import org.apache.airavata.model.messaging.event.MessageType; +import org.apache.airavata.model.process.ProcessModel; +import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel; +import org.apache.airavata.model.security.AuthzToken; +import org.apache.airavata.model.status.ExperimentState; +import org.apache.airavata.model.status.ExperimentStatus; +import org.apache.airavata.model.status.JobState; +import org.apache.airavata.model.status.JobStatus; +import org.apache.airavata.model.status.ProcessState; +import org.apache.airavata.model.status.ProcessStatus; +import org.apache.airavata.model.status.QueueStatusModel; +import org.apache.airavata.model.task.TaskTypes; +import org.apache.airavata.model.workspace.Gateway; +import org.apache.airavata.model.workspace.Notification; +import org.apache.airavata.model.workspace.Project; +import org.apache.airavata.registry.api.exception.RegistryServiceException; +import org.apache.airavata.service.security.GatewayGroupsInitializer; +import org.apache.airavata.sharing.registry.models.Domain; +import org.apache.airavata.sharing.registry.models.DuplicateEntryException; +import org.apache.airavata.sharing.registry.models.Entity; +import org.apache.airavata.sharing.registry.models.EntitySearchField; +import org.apache.airavata.sharing.registry.models.EntityType; +import org.apache.airavata.sharing.registry.models.PermissionType; +import org.apache.airavata.sharing.registry.models.SearchCondition; +import org.apache.airavata.sharing.registry.models.SearchCriteria; +import org.apache.airavata.sharing.registry.models.SharingRegistryException; +import org.apache.airavata.sharing.registry.models.User; +import org.apache.airavata.sharing.registry.models.UserGroup; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class AiravataService { + private static final Logger logger = LoggerFactory.getLogger(AiravataService.class); + + private record StorageInfoContext(String loginUserName, String credentialToken, AgentAdaptor adaptor) {} + + // Record aliases for sharing registry models to avoid name clashes + private record SharingEntity(org.apache.airavata.sharing.registry.models.Entity delegate) {} + + private boolean validateString(String name) { + boolean valid = true; + if (name == null || name.equals("") || name.trim().length() == 0) { + valid = false; + } + return valid; + } + + private AiravataSystemException airavataSystemException( + AiravataErrorType errorType, String message, Throwable cause) { + var exception = new AiravataSystemException(errorType); + exception.setMessage(message); + if (cause != null) { + exception.initCause(cause); + } + return exception; + } + + private boolean safeIsUserResourceProfileExists(AuthzToken authzToken, String userId, String gatewayId) { + try { + return isUserResourceProfileExists(userId, gatewayId); + } catch (Throwable e) { + logger.error("Error checking if user resource profile exists", e); + return false; + } + } + + private boolean isGatewayResourceProfileExists(String gatewayId) { + try { + var profile = getGatewayResourceProfile(gatewayId); + return profile != null; + } catch (Throwable e) { + logger.error("Error while checking if gateway resource profile exists", e); + return false; + } + } + + private RegistryService registryService; + private SharingRegistryService sharingRegistryService; + private CredentialStoreService credentialStoreService; + private Publisher statusPublisher; + private Publisher experimentPublisher; + + public AiravataService() { + try { + registryService = new RegistryService(); + logger.info("Initialized RegistryService"); + sharingRegistryService = new SharingRegistryService(); + logger.info("Initialized SharingRegistryService"); + credentialStoreService = new CredentialStoreService(); + logger.info("Initialized CredentialStoreService"); + statusPublisher = MessagingFactory.getPublisher(Type.STATUS); + logger.info("Initialized StatusPublisher"); + experimentPublisher = MessagingFactory.getPublisher(Type.EXPERIMENT_LAUNCH); + logger.info("Initialized ExperimentPublisher"); + } catch (Exception e) { + logger.error("Error initializing AiravataService", e); + throw new RuntimeException("Error initializing AiravataService", e); + } + } + + public void init() { + try { + initSharingRegistry(); + postInitDefaultGateway(); + } catch (Exception e) { + logger.error("Error occurred while initializing Airavata Service", e); + throw new RuntimeException("Error occurred while initializing Airavata Service", e); + } + } + + private void postInitDefaultGateway() { + try { + var gatewayResourceProfile = getGatewayResourceProfile(ServerSettings.getDefaultUserGateway()); + if (gatewayResourceProfile != null && gatewayResourceProfile.getIdentityServerPwdCredToken() == null) { + + logger.debug("Starting to add the password credential for default gateway : " + + ServerSettings.getDefaultUserGateway()); + + var passwordCredential = new PasswordCredential(); + passwordCredential.setPortalUserName(ServerSettings.getDefaultUser()); + passwordCredential.setGatewayId(ServerSettings.getDefaultUserGateway()); + passwordCredential.setLoginUserName(ServerSettings.getDefaultUser()); + passwordCredential.setPassword(ServerSettings.getDefaultUserPassword()); + passwordCredential.setDescription("Credentials for default gateway"); + String token = null; + try { + logger.info("Creating password credential for default gateway"); + token = addPasswordCredential(passwordCredential); + } catch (Throwable ex) { + logger.error( + "Failed to create the password credential for the default gateway : " + + ServerSettings.getDefaultUserGateway(), + ex); + } + + if (token != null) { + logger.debug("Adding password credential token " + token + " to the default gateway : " + + ServerSettings.getDefaultUserGateway()); + gatewayResourceProfile.setIdentityServerPwdCredToken(token); + gatewayResourceProfile.setIdentityServerTenant(ServerSettings.getDefaultUserGateway()); + updateGatewayResourceProfile(ServerSettings.getDefaultUserGateway(), gatewayResourceProfile); + } + } + } catch (Throwable e) { + logger.error("Failed to add the password credentials for the default gateway", e); + } + } + + private void initSharingRegistry() + throws ApplicationSettingsException, SharingRegistryException, DuplicateEntryException { + try { + if (!isDomainExists(ServerSettings.getDefaultUserGateway())) { + var domain = new Domain(); + domain.setDomainId(ServerSettings.getDefaultUserGateway()); + domain.setName(ServerSettings.getDefaultUserGateway()); + domain.setDescription("Domain entry for " + domain.getName()); + createDomain(domain); + + var user = new User(); + user.setDomainId(domain.getDomainId()); + user.setUserId(ServerSettings.getDefaultUser() + "@" + ServerSettings.getDefaultUserGateway()); + user.setUserName(ServerSettings.getDefaultUser()); + createUser(user); + + // Creating Entity Types for each domain + var entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":PROJECT"); + entityType.setDomainId(domain.getDomainId()); + entityType.setName("PROJECT"); + entityType.setDescription("Project entity type"); + createEntityType(entityType); + + entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":EXPERIMENT"); + entityType.setDomainId(domain.getDomainId()); + entityType.setName("EXPERIMENT"); + entityType.setDescription("Experiment entity type"); + createEntityType(entityType); + + entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":FILE"); + entityType.setDomainId(domain.getDomainId()); + entityType.setName("FILE"); + entityType.setDescription("File entity type"); + createEntityType(entityType); + + entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); + entityType.setDomainId(domain.getDomainId()); + entityType.setName("APPLICATION-DEPLOYMENT"); + entityType.setDescription("Application Deployment entity type"); + createEntityType(entityType); + + entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":" + ResourceType.GROUP_RESOURCE_PROFILE.name()); + entityType.setDomainId(domain.getDomainId()); + entityType.setName(ResourceType.GROUP_RESOURCE_PROFILE.name()); + entityType.setDescription("Group Resource Profile entity type"); + createEntityType(entityType); + + entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":" + ResourceType.CREDENTIAL_TOKEN.name()); + entityType.setDomainId(domain.getDomainId()); + entityType.setName(ResourceType.CREDENTIAL_TOKEN.name()); + entityType.setDescription("Credential Store Token entity type"); + createEntityType(entityType); + + // Creating Permission Types for each domain + var permissionType = new PermissionType(); + permissionType.setPermissionTypeId(domain.getDomainId() + ":READ"); + permissionType.setDomainId(domain.getDomainId()); + permissionType.setName("READ"); + permissionType.setDescription("Read permission type"); + createPermissionType(permissionType); + + permissionType = new PermissionType(); + permissionType.setPermissionTypeId(domain.getDomainId() + ":WRITE"); + permissionType.setDomainId(domain.getDomainId()); + permissionType.setName("WRITE"); + permissionType.setDescription("Write permission type"); + createPermissionType(permissionType); + + permissionType = new PermissionType(); + permissionType.setPermissionTypeId(domain.getDomainId() + ":MANAGE_SHARING"); + permissionType.setDomainId(domain.getDomainId()); + permissionType.setName("MANAGE_SHARING"); + permissionType.setDescription("Sharing permission type"); + createPermissionType(permissionType); + } + } catch (Throwable ex) { + throw ex; + } + } + + public List getAllUsersInGateway(String gatewayId) throws AiravataSystemException { + try { + return registryService.getAllUsersInGateway(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving users: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateGateway(String gatewayId, Gateway updatedGateway) throws AiravataSystemException { + try { + return registryService.updateGateway(gatewayId, updatedGateway); + } catch (RegistryServiceException e) { + String msg = "Error while updating gateway: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public Gateway getGateway(String gatewayId) throws AiravataSystemException { + try { + var result = registryService.getGateway(gatewayId); + logger.debug("Airavata found the gateway with " + gatewayId); + return result; + } catch (RegistryServiceException e) { + String msg = "Error while getting the gateway: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteGateway(String gatewayId) throws AiravataSystemException { + try { + return registryService.deleteGateway(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting the gateway: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllGateways() throws AiravataSystemException { + try { + logger.debug("Airavata searching for all gateways"); + return registryService.getAllGateways(); + } catch (RegistryServiceException e) { + String msg = "Error while getting all the gateways: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean isGatewayExist(String gatewayId) throws AiravataSystemException { + try { + logger.debug("Airavata verifying if the gateway with " + gatewayId + "exits"); + return registryService.isGatewayExist(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while getting gateway: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String createNotification(Notification notification) throws AiravataSystemException { + try { + return registryService.createNotification(notification); + } catch (RegistryServiceException e) { + String msg = "Error while creating notification: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateNotification(Notification notification) throws AiravataSystemException { + try { + return registryService.updateNotification(notification); + } catch (RegistryServiceException e) { + String msg = "Error while updating notification: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteNotification(String gatewayId, String notificationId) throws AiravataSystemException { + try { + return registryService.deleteNotification(gatewayId, notificationId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting notification: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public Notification getNotification(String gatewayId, String notificationId) throws AiravataSystemException { + try { + return registryService.getNotification(gatewayId, notificationId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving notification: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllNotifications(String gatewayId) throws AiravataSystemException { + try { + return registryService.getAllNotifications(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while getting all notifications: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerDataProduct(DataProductModel dataProductModel) throws AiravataSystemException { + try { + return registryService.registerDataProduct(dataProductModel); + } catch (Throwable e) { + var msg = "Error in registering the data resource" + dataProductModel.getProductName() + "."; + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public DataProductModel getDataProduct(String productUri) throws AiravataSystemException { + try { + return registryService.getDataProduct(productUri); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving data product: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerReplicaLocation(DataReplicaLocationModel replicaLocationModel) + throws AiravataSystemException { + try { + return registryService.registerReplicaLocation(replicaLocationModel); + } catch (Throwable e) { + var msg = "Error in retreiving the replica " + replicaLocationModel.getReplicaName() + "." + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public DataProductModel getParentDataProduct(String productUri) throws AiravataSystemException { + try { + return registryService.getParentDataProduct(productUri); + } catch (Throwable e) { + var msg = "Error in retreiving the parent data product for " + productUri + "." + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getChildDataProducts(String productUri) throws AiravataSystemException { + try { + return registryService.getChildDataProducts(productUri); + } catch (Throwable e) { + var msg = "Error in retreiving the child products for " + productUri + "." + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean isUserExists(String gatewayId, String userName) throws AiravataSystemException { + try { + logger.debug("Checking if the user" + userName + "exists in the gateway" + gatewayId); + return registryService.isUserExists(gatewayId, userName); + } catch (RegistryServiceException e) { + String msg = "Error while verifying user: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public Project getProject(String projectId) throws AiravataSystemException, ProjectNotFoundException { + try { + return registryService.getProject(projectId); + } catch (ProjectNotFoundException e) { + throw e; + } catch (RegistryServiceException e) { + String msg = "Error while retrieving the project: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void updateProject(String projectId, Project updatedProject) throws AiravataSystemException { + try { + registryService.updateProject(projectId, updatedProject); + } catch (RegistryServiceException e) { + String msg = "Error while updating project: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteProject(String projectId) throws AiravataSystemException, ProjectNotFoundException { + try { + return registryService.deleteProject(projectId); + } catch (ProjectNotFoundException e) { + throw e; + } catch (RegistryServiceException e) { + String msg = "Error while removing the project: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List searchProjects( + AuthzToken authzToken, + String gatewayId, + String userName, + Map filters, + int limit, + int offset) + throws AiravataSystemException { + try { + var accessibleProjIds = new ArrayList(); + List result; + if (ServerSettings.isEnableSharing()) { + var sharingFilters = new ArrayList(); + var searchCriteria = new SearchCriteria(); + searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); + searchCriteria.setSearchCondition(SearchCondition.EQUAL); + searchCriteria.setValue(gatewayId + ":PROJECT"); + sharingFilters.add(searchCriteria); + sharingRegistryService + .searchEntities( + authzToken.getClaimsMap().get(Constants.GATEWAY_ID), + userName + "@" + gatewayId, + sharingFilters, + 0, + Integer.MAX_VALUE) + .stream() + .forEach(e -> accessibleProjIds.add(e.getEntityId())); + if (accessibleProjIds.isEmpty()) { + result = Collections.emptyList(); + } else { + result = registryService.searchProjects( + gatewayId, userName, accessibleProjIds, filters, limit, offset); + } + } else { + result = registryService.searchProjects(gatewayId, userName, accessibleProjIds, filters, limit, offset); + } + return result; + } catch (Throwable e) { + String msg = "Error while retrieving projects: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List searchProjects( + String gatewayId, + String userName, + List accessibleProjectIds, + Map filters, + int limit, + int offset) + throws RegistryServiceException { + return registryService.searchProjects(gatewayId, userName, accessibleProjectIds, filters, limit, offset); + } + + public List getUserExperiments(String gatewayId, String userName, int limit, int offset) + throws AiravataSystemException { + try { + return registryService.getUserExperiments(gatewayId, userName, limit, offset); + } catch (RegistryServiceException e) { + String msg = "Error occurred while getting user experiments: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getExperimentsInProject(String gatewayId, String projectId, int limit, int offset) + throws AiravataSystemException { + try { + return registryService.getExperimentsInProject(gatewayId, projectId, limit, offset); + } catch (RegistryServiceException e) { + String msg = "Error occurred while getting experiments in project: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getExperimentsInProject(AuthzToken authzToken, String projectId, int limit, int offset) + throws AuthorizationException, AiravataSystemException, ProjectNotFoundException { + try { + var project = getProject(projectId); + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + if (ServerSettings.isEnableSharing() + && (!authzToken.getClaimsMap().get(Constants.USER_NAME).equals(project.getOwner()) + || !authzToken + .getClaimsMap() + .get(Constants.GATEWAY_ID) + .equals(project.getGatewayId()))) { + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess(gatewayId, userId + "@" + gatewayId, projectId, gatewayId + ":READ")) { + throw new AuthorizationException("User does not have permission to access this resource"); + } + } + return registryService.getExperimentsInProject(gatewayId, projectId, limit, offset); + } catch (AuthorizationException | ProjectNotFoundException | AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException | SharingRegistryException | RegistryServiceException e) { + String msg = "Error while retrieving the experiments: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ExperimentStatistics getExperimentStatistics( + String gatewayId, + long fromTime, + long toTime, + String userName, + String applicationName, + String resourceHostName, + List accessibleExpIds, + int limit, + int offset) + throws AiravataSystemException { + try { + return registryService.getExperimentStatistics( + gatewayId, + fromTime, + toTime, + userName, + applicationName, + resourceHostName, + accessibleExpIds, + limit, + offset); + } catch (RegistryServiceException e) { + String msg = "Error while getting experiment statistics: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ExperimentModel getExperiment(String airavataExperimentId) throws AiravataSystemException { + try { + return registryService.getExperiment(airavataExperimentId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving experiment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + private String createExperimentInternal(String gatewayId, ExperimentModel experiment) + throws AiravataSystemException { + try { + var experimentId = registryService.createExperiment(gatewayId, experiment); + if (statusPublisher != null) { + var event = new ExperimentStatusChangeEvent(ExperimentState.CREATED, experimentId, gatewayId); + var messageId = AiravataUtils.getId("EXPERIMENT"); + var messageContext = new MessageContext(event, MessageType.EXPERIMENT, messageId, gatewayId); + messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); + statusPublisher.publish(messageContext); + } + return experimentId; + } catch (RegistryServiceException | AiravataException e) { + String msg = "Error while creating experiment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ExperimentModel getExperiment(AuthzToken authzToken, String airavataExperimentId) + throws AuthorizationException, InvalidRequestException, AiravataSystemException { + try { + var existingExperiment = getExperiment(airavataExperimentId); + if (authzToken.getClaimsMap().get(Constants.USER_NAME).equals(existingExperiment.getUserName()) + && authzToken.getClaimsMap().get(Constants.GATEWAY_ID).equals(existingExperiment.getGatewayId())) { + return existingExperiment; + } else if (ServerSettings.isEnableSharing()) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess(gatewayId, userId + "@" + gatewayId, airavataExperimentId, gatewayId + ":READ")) { + throw new AuthorizationException("User does not have permission to access this resource"); + } + return existingExperiment; + } else { + throw new AuthorizationException("User does not have permission to access this resource"); + } + } catch (AuthorizationException | AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException | SharingRegistryException e) { + String msg = "Error while getting the experiment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ExperimentModel getExperimentByAdmin(AuthzToken authzToken, String airavataExperimentId) + throws AuthorizationException, AiravataSystemException { + try { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var existingExperiment = getExperiment(airavataExperimentId); + if (gatewayId.equals(existingExperiment.getGatewayId())) { + return existingExperiment; + } else { + throw new AuthorizationException("User does not have permission to access this resource"); + } + } catch (AuthorizationException | AiravataSystemException e) { + throw e; + } + } + + public void updateExperiment(AuthzToken authzToken, String airavataExperimentId, ExperimentModel experiment) + throws AuthorizationException, AiravataSystemException { + try { + var existingExperiment = getExperiment(airavataExperimentId); + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + if (ServerSettings.isEnableSharing() + && (!authzToken.getClaimsMap().get(Constants.USER_NAME).equals(existingExperiment.getUserName()) + || !authzToken + .getClaimsMap() + .get(Constants.GATEWAY_ID) + .equals(existingExperiment.getGatewayId()))) { + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess(gatewayId, userId + "@" + gatewayId, airavataExperimentId, gatewayId + ":WRITE")) { + throw new AuthorizationException("User does not have permission to access this resource"); + } + } + + // Update name, description and parent on Entity + // TODO: update the experiment via a DB event + var entity = getEntity(gatewayId, airavataExperimentId); + entity.delegate().setName(experiment.getExperimentName()); + entity.delegate().setDescription(experiment.getDescription()); + entity.delegate().setParentEntityId(experiment.getProjectId()); + updateEntity(entity); + + updateExperiment(airavataExperimentId, experiment); + } catch (AuthorizationException | AiravataSystemException e) { + throw e; + } catch (Throwable e) { + String msg = "Error while updating experiment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void updateExperiment(String airavataExperimentId, ExperimentModel experiment) + throws AiravataSystemException { + try { + registryService.updateExperiment(airavataExperimentId, experiment); + } catch (RegistryServiceException e) { + String msg = "Error while updating experiment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteExperiment(String experimentId) throws AiravataSystemException { + try { + return registryService.deleteExperiment(experimentId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting experiment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String cloneExperiment( + AuthzToken authzToken, + String existingExperimentID, + String newExperimentName, + String newExperimentProjectId, + ExperimentModel existingExperiment) + throws ExperimentNotFoundException, ProjectNotFoundException, AuthorizationException, + AiravataSystemException, InvalidRequestException { + try { + if (existingExperiment == null) { + logger.error( + existingExperimentID, + "Error while cloning experiment {}, experiment doesn't exist.", + existingExperimentID); + throw new ExperimentNotFoundException( + "Requested experiment id " + existingExperimentID + " does not exist in the system.."); + } + if (newExperimentProjectId != null) { + // getProject will apply sharing permissions + var project = getProject(authzToken, newExperimentProjectId); + if (project == null) { + logger.error( + "Error while cloning experiment {}, project {} doesn't exist.", + existingExperimentID, + newExperimentProjectId); + throw new ProjectNotFoundException( + "Requested project id " + newExperimentProjectId + " does not exist in the system.."); + } + existingExperiment.setProjectId(project.getProjectID()); + } + + // make sure user has write access to the project + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess( + gatewayId, userId + "@" + gatewayId, existingExperiment.getProjectId(), gatewayId + ":WRITE")) { + logger.error( + "Error while cloning experiment {}, user doesn't have write access to project {}", + existingExperimentID, + existingExperiment.getProjectId()); + throw new AuthorizationException( + "User does not have permission to clone an experiment in this project"); + } + + existingExperiment.setCreationTime( + AiravataUtils.getCurrentTimestamp().getTime()); + if (existingExperiment.getExecutionId() != null) { + try { + var applicationOutputs = getApplicationOutputs(existingExperiment.getExecutionId()); + existingExperiment.setExperimentOutputs(applicationOutputs); + } catch (Throwable e) { + logger.warn("Error getting application outputs for experiment clone: " + e.getMessage()); + } + } + if (validateString(newExperimentName)) { + existingExperiment.setExperimentName(newExperimentName); + } + existingExperiment.unsetErrors(); + existingExperiment.unsetProcesses(); + existingExperiment.unsetExperimentStatus(); + if (existingExperiment.getUserConfigurationData() != null + && existingExperiment.getUserConfigurationData().getComputationalResourceScheduling() != null + && existingExperiment + .getUserConfigurationData() + .getComputationalResourceScheduling() + .getResourceHostId() + != null) { + var compResourceId = existingExperiment + .getUserConfigurationData() + .getComputationalResourceScheduling() + .getResourceHostId(); + + try { + var computeResource = getComputeResource(compResourceId); + if (!computeResource.isEnabled()) { + existingExperiment.getUserConfigurationData().setComputationalResourceScheduling(null); + } + } catch (Throwable e) { + logger.warn("Error getting compute resource for experiment clone: " + e.getMessage()); + } + } + logger.debug("Airavata cloned experiment with experiment id : " + existingExperimentID); + existingExperiment.setUserName(userId); + + var expId = createExperimentInternal(gatewayId, existingExperiment); + if (ServerSettings.isEnableSharing()) { + try { + var entity = new Entity(); + entity.setEntityId(expId); + final String domainId = existingExperiment.getGatewayId(); + entity.setDomainId(domainId); + entity.setEntityTypeId(domainId + ":" + "EXPERIMENT"); + entity.setOwnerId(existingExperiment.getUserName() + "@" + domainId); + entity.setName(existingExperiment.getExperimentName()); + entity.setDescription(existingExperiment.getDescription()); + createEntity(new SharingEntity(entity)); + shareEntityWithAdminGatewayGroups(entity); + } catch (Throwable ex) { + logger.error(ex.getMessage(), ex); + logger.error("rolling back experiment creation Exp ID : " + expId); + try { + deleteExperiment(expId); + } catch (Throwable e) { + logger.error("Error deleting experiment during rollback: " + e.getMessage()); + } + logger.error("Error while creating entity for cloned experiment", ex); + throw airavataSystemException( + AiravataErrorType.INTERNAL_ERROR, + "Error while creating entity for cloned experiment. More info : " + ex.getMessage(), + ex); + } + } + + return expId; + } catch (ExperimentNotFoundException + | ProjectNotFoundException + | AuthorizationException + | AiravataSystemException e) { + throw e; + } catch (SharingRegistryException | ApplicationSettingsException e) { + String msg = "Error while cloning experiment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void terminateExperiment(String airavataExperimentId, String gatewayId) + throws ExperimentNotFoundException, AiravataSystemException { + try { + var existingExperiment = getExperiment(airavataExperimentId); + var experimentLastStatus = getExperimentStatus(airavataExperimentId); + if (existingExperiment == null) { + logger.error( + airavataExperimentId, + "Error while cancelling experiment {}, experiment doesn't exist.", + airavataExperimentId); + throw new ExperimentNotFoundException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + switch (experimentLastStatus.getState()) { + case COMPLETED: + case CANCELED: + case FAILED: + case CANCELING: + logger.warn( + "Can't terminate already {} experiment", + existingExperiment + .getExperimentStatus() + .get(0) + .getState() + .name()); + break; + case CREATED: + logger.warn("Experiment termination is only allowed for launched experiments."); + break; + default: + publishExperimentCancelEvent(experimentPublisher, gatewayId, airavataExperimentId); + logger.debug("Airavata cancelled experiment with experiment id : " + airavataExperimentId); + break; + } + } catch (ExperimentNotFoundException e) { + throw e; + } catch (Throwable e) { + String msg = "Error occurred while cancelling the experiment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List searchExperiments( + String gatewayId, + String userName, + List accessibleExpIds, + Map filters, + int limit, + int offset) + throws RegistryServiceException { + return registryService.searchExperiments(gatewayId, userName, accessibleExpIds, filters, limit, offset); + } + + /** + * Search experiments with sharing registry integration - processes filters and + * builds search criteria + */ + public List searchExperiments( + AuthzToken authzToken, + String gatewayId, + String userName, + Map filters, + int limit, + int offset) + throws AiravataSystemException { + try { + var accessibleExpIds = new ArrayList(); + var filtersCopy = new HashMap(filters); + var sharingFilters = new ArrayList(); + var searchCriteria = new SearchCriteria(); + searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); + searchCriteria.setSearchCondition(SearchCondition.EQUAL); + searchCriteria.setValue(gatewayId + ":EXPERIMENT"); + sharingFilters.add(searchCriteria); + + // Apply as much of the filters in the sharing API as possible, + // removing each filter that can be filtered via the sharing API + if (filtersCopy.containsKey(ExperimentSearchFields.FROM_DATE)) { + var fromTime = filtersCopy.remove(ExperimentSearchFields.FROM_DATE); + var fromCreatedTimeCriteria = new SearchCriteria(); + fromCreatedTimeCriteria.setSearchField(EntitySearchField.CREATED_TIME); + fromCreatedTimeCriteria.setSearchCondition(SearchCondition.GTE); + fromCreatedTimeCriteria.setValue(fromTime); + sharingFilters.add(fromCreatedTimeCriteria); + } + if (filtersCopy.containsKey(ExperimentSearchFields.TO_DATE)) { + var toTime = filtersCopy.remove(ExperimentSearchFields.TO_DATE); + var toCreatedTimeCriteria = new SearchCriteria(); + toCreatedTimeCriteria.setSearchField(EntitySearchField.CREATED_TIME); + toCreatedTimeCriteria.setSearchCondition(SearchCondition.LTE); + toCreatedTimeCriteria.setValue(toTime); + sharingFilters.add(toCreatedTimeCriteria); + } + if (filtersCopy.containsKey(ExperimentSearchFields.PROJECT_ID)) { + var projectId = filtersCopy.remove(ExperimentSearchFields.PROJECT_ID); + var projectParentEntityCriteria = new SearchCriteria(); + projectParentEntityCriteria.setSearchField(EntitySearchField.PARRENT_ENTITY_ID); + projectParentEntityCriteria.setSearchCondition(SearchCondition.EQUAL); + projectParentEntityCriteria.setValue(projectId); + sharingFilters.add(projectParentEntityCriteria); + } + if (filtersCopy.containsKey(ExperimentSearchFields.USER_NAME)) { + var username = filtersCopy.remove(ExperimentSearchFields.USER_NAME); + var usernameOwnerCriteria = new SearchCriteria(); + usernameOwnerCriteria.setSearchField(EntitySearchField.OWNER_ID); + usernameOwnerCriteria.setSearchCondition(SearchCondition.EQUAL); + usernameOwnerCriteria.setValue(username + "@" + gatewayId); + sharingFilters.add(usernameOwnerCriteria); + } + if (filtersCopy.containsKey(ExperimentSearchFields.EXPERIMENT_NAME)) { + var experimentName = filtersCopy.remove(ExperimentSearchFields.EXPERIMENT_NAME); + var experimentNameCriteria = new SearchCriteria(); + experimentNameCriteria.setSearchField(EntitySearchField.NAME); + experimentNameCriteria.setSearchCondition(SearchCondition.LIKE); + experimentNameCriteria.setValue(experimentName); + sharingFilters.add(experimentNameCriteria); + } + if (filtersCopy.containsKey(ExperimentSearchFields.EXPERIMENT_DESC)) { + var experimentDescription = filtersCopy.remove(ExperimentSearchFields.EXPERIMENT_DESC); + var experimentDescriptionCriteria = new SearchCriteria(); + experimentDescriptionCriteria.setSearchField(EntitySearchField.DESCRIPTION); + experimentDescriptionCriteria.setSearchCondition(SearchCondition.LIKE); + experimentDescriptionCriteria.setValue(experimentDescription); + sharingFilters.add(experimentDescriptionCriteria); + } + // Grab all of the matching experiments in the sharing registry + // unless all of the filtering can be done through the sharing API + int searchOffset = 0; + int searchLimit = Integer.MAX_VALUE; + boolean filteredInSharing = filtersCopy.isEmpty(); + if (filteredInSharing) { + searchOffset = offset; + searchLimit = limit; + } + sharingRegistryService + .searchEntities( + authzToken.getClaimsMap().get(Constants.GATEWAY_ID), + userName + "@" + gatewayId, + sharingFilters, + searchOffset, + searchLimit) + .forEach(e -> accessibleExpIds.add(e.getEntityId())); + int finalOffset = offset; + // If no more filtering to be done (either empty or all done through sharing + // API), set the offset to 0 + if (filteredInSharing) { + finalOffset = 0; + } + return searchExperiments(gatewayId, userName, accessibleExpIds, filtersCopy, limit, finalOffset); + } catch (RegistryServiceException | SharingRegistryException e) { + String msg = "Error while retrieving experiments: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ExperimentStatus getExperimentStatus(String airavataExperimentId) throws AiravataSystemException { + try { + return registryService.getExperimentStatus(airavataExperimentId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving experiment status: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getExperimentOutputs(String airavataExperimentId) throws AiravataSystemException { + try { + return registryService.getExperimentOutputs(airavataExperimentId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving experiment outputs: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ExperimentModel getDetailedExperimentTree(String airavataExperimentId) throws AiravataSystemException { + try { + return registryService.getDetailedExperimentTree(airavataExperimentId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving detailed experiment tree: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getApplicationOutputs(String appInterfaceId) throws AiravataSystemException { + try { + return registryService.getApplicationOutputs(appInterfaceId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving application outputs: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ComputeResourceDescription getComputeResource(String computeResourceId) throws AiravataSystemException { + try { + return registryService.getComputeResource(computeResourceId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving compute resource: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerComputeResource(ComputeResourceDescription computeResourceDescription) + throws AiravataSystemException { + try { + return registryService.registerComputeResource(computeResourceDescription); + } catch (RegistryServiceException e) { + String msg = "Error while saving compute resource: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateComputeResource( + String computeResourceId, ComputeResourceDescription computeResourceDescription) + throws AiravataSystemException { + try { + return registryService.updateComputeResource(computeResourceId, computeResourceDescription); + } catch (RegistryServiceException e) { + String msg = "Error while updating compute resource: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteComputeResource(String computeResourceId) throws AiravataSystemException { + try { + return registryService.deleteComputeResource(computeResourceId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting compute resource: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public Map getAllComputeResourceNames() throws AiravataSystemException { + try { + return registryService.getAllComputeResourceNames(); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving compute resource names: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerStorageResource(StorageResourceDescription storageResourceDescription) + throws AiravataSystemException { + try { + return registryService.registerStorageResource(storageResourceDescription); + } catch (RegistryServiceException e) { + String msg = "Error while saving storage resource: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public StorageResourceDescription getStorageResource(String storageResourceId) throws AiravataSystemException { + try { + return registryService.getStorageResource(storageResourceId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving storage resource: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateStorageResource( + String storageResourceId, StorageResourceDescription storageResourceDescription) + throws AiravataSystemException { + try { + return registryService.updateStorageResource(storageResourceId, storageResourceDescription); + } catch (RegistryServiceException e) { + String msg = "Error while updating storage resource: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteStorageResource(String storageResourceId) throws AiravataSystemException { + try { + return registryService.deleteStorageResource(storageResourceId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting storage resource: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public Map getAllStorageResourceNames() throws AiravataSystemException { + try { + return registryService.getAllStorageResourceNames(); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving storage resource names: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerGatewayResourceProfile(GatewayResourceProfile gatewayResourceProfile) + throws AiravataSystemException { + try { + return registryService.registerGatewayResourceProfile(gatewayResourceProfile); + } catch (RegistryServiceException e) { + String msg = "Error while registering gateway resource profile: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public GatewayResourceProfile getGatewayResourceProfile(String gatewayID) throws AiravataSystemException { + try { + return registryService.getGatewayResourceProfile(gatewayID); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving gateway resource profile: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateGatewayResourceProfile(String gatewayID, GatewayResourceProfile gatewayResourceProfile) + throws AiravataSystemException { + try { + return registryService.updateGatewayResourceProfile(gatewayID, gatewayResourceProfile); + } catch (RegistryServiceException e) { + String msg = "Error while updating gateway resource profile: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteGatewayResourceProfile(String gatewayID) throws AiravataSystemException { + try { + return registryService.deleteGatewayResourceProfile(gatewayID); + } catch (RegistryServiceException e) { + String msg = "Error while removing gateway resource profile: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public UserResourceProfile getUserResourceProfile(String userId, String gatewayId) throws AiravataSystemException { + try { + return registryService.getUserResourceProfile(userId, gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving user resource profile: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateUserResourceProfile(String userId, String gatewayID, UserResourceProfile userResourceProfile) + throws AiravataSystemException { + try { + return registryService.updateUserResourceProfile(userId, gatewayID, userResourceProfile); + } catch (RegistryServiceException e) { + String msg = "Error while updating user resource profile: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteUserResourceProfile(String userId, String gatewayID) throws AiravataSystemException { + try { + return registryService.deleteUserResourceProfile(userId, gatewayID); + } catch (RegistryServiceException e) { + String msg = "Error while removing user resource profile: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public GroupResourceProfile getGroupResourceProfile(String groupResourceProfileId) throws AiravataSystemException { + try { + return registryService.getGroupResourceProfile(groupResourceProfileId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving group resource profile: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void updateGroupResourceProfile(GroupResourceProfile groupResourceProfile) throws AiravataSystemException { + try { + registryService.updateGroupResourceProfile(groupResourceProfile); + } catch (RegistryServiceException e) { + String msg = "Error while updating group resource profile: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getGroupResourceList(String gatewayId, List accessibleGroupResProfileIds) + throws AiravataSystemException { + try { + return registryService.getGroupResourceList(gatewayId, accessibleGroupResProfileIds); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving group resource list: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public GatewayGroups getGatewayGroups(String gatewayId) throws AiravataSystemException { + try { + return registryService.getGatewayGroups(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving gateway groups: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean isGatewayGroupsExists(String gatewayId) throws AiravataSystemException { + try { + return registryService.isGatewayGroupsExists(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while checking if gateway groups exist: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void updateExperimentConfiguration(String airavataExperimentId, UserConfigurationDataModel userConfiguration) + throws AiravataSystemException { + try { + registryService.updateExperimentConfiguration(airavataExperimentId, userConfiguration); + } catch (RegistryServiceException e) { + String msg = "Error while updating experiment configuration: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void updateResourceScheduleing( + String airavataExperimentId, ComputationalResourceSchedulingModel resourceScheduling) + throws AiravataSystemException { + try { + registryService.updateResourceScheduleing(airavataExperimentId, resourceScheduling); + } catch (RegistryServiceException e) { + String msg = "Error while updating resource scheduling: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerApplicationDeployment( + String gatewayId, ApplicationDeploymentDescription applicationDeployment) throws AiravataSystemException { + try { + return registryService.registerApplicationDeployment(gatewayId, applicationDeployment); + } catch (RegistryServiceException e) { + String msg = "Error while registering application deployment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerApplicationDeployment( + AuthzToken authzToken, String gatewayId, ApplicationDeploymentDescription applicationDeployment) + throws AiravataSystemException, InvalidRequestException, AuthorizationException { + try { + String result = registerApplicationDeployment(gatewayId, applicationDeployment); + if (ServerSettings.isEnableSharing()) { + var entity = new Entity(); + entity.setEntityId(result); + final String domainId = gatewayId; + entity.setDomainId(domainId); + entity.setEntityTypeId(domainId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); + var userName = authzToken.getClaimsMap().get(Constants.USER_NAME); + entity.setOwnerId(userName + "@" + domainId); + entity.setName(result); + entity.setDescription(applicationDeployment.getAppDeploymentDescription()); + createEntity(new SharingEntity(entity)); + shareEntityWithAdminGatewayGroups(entity); + } + return result; + } catch (InvalidRequestException | AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error while registering application deployment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ApplicationDeploymentDescription getApplicationDeployment(String appDeploymentId) + throws AiravataSystemException { + try { + return registryService.getApplicationDeployment(appDeploymentId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving application deployment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ApplicationDeploymentDescription getApplicationDeployment(AuthzToken authzToken, String appDeploymentId) + throws AuthorizationException, AiravataSystemException, InvalidRequestException { + try { + if (ServerSettings.isEnableSharing()) { + final boolean hasAccess = userHasAccess(authzToken, appDeploymentId, ResourcePermissionType.READ); + if (!hasAccess) { + throw new AuthorizationException( + "User does not have access to application deployment " + appDeploymentId); + } + } + return getApplicationDeployment(appDeploymentId); + } catch (AuthorizationException | AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException e) { + String msg = "Error occurred while getting application deployment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateApplicationDeployment( + String appDeploymentId, ApplicationDeploymentDescription applicationDeployment) + throws AiravataSystemException { + try { + return registryService.updateApplicationDeployment(appDeploymentId, applicationDeployment); + } catch (RegistryServiceException e) { + String msg = "Error while updating application deployment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateApplicationDeployment( + AuthzToken authzToken, String appDeploymentId, ApplicationDeploymentDescription applicationDeployment) + throws AuthorizationException, AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + final boolean hasAccess = userHasAccess(authzToken, appDeploymentId, ResourcePermissionType.WRITE); + if (!hasAccess) { + throw new AuthorizationException( + "User does not have WRITE access to application deployment " + appDeploymentId); + } + } + return updateApplicationDeployment(appDeploymentId, applicationDeployment); + } catch (AuthorizationException | AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException e) { + String msg = "Error occurred while updating application deployment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteApplicationDeployment(String appDeploymentId) throws AiravataSystemException { + try { + return registryService.deleteApplicationDeployment(appDeploymentId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting application deployment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteApplicationDeployment(AuthzToken authzToken, String appDeploymentId) + throws AuthorizationException, AiravataSystemException, InvalidRequestException { + try { + if (ServerSettings.isEnableSharing()) { + final boolean hasAccess = userHasAccess(authzToken, appDeploymentId, ResourcePermissionType.WRITE); + if (!hasAccess) { + throw new AuthorizationException( + "User does not have WRITE access to application deployment " + appDeploymentId); + } + } + return deleteApplicationDeployment(appDeploymentId); + } catch (AuthorizationException | AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException e) { + String msg = "Error occurred while deleting application deployment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ApplicationInterfaceDescription getApplicationInterface(String appInterfaceId) + throws AiravataSystemException { + try { + return registryService.getApplicationInterface(appInterfaceId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving application interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getApplicationDeployments(String appModuleId) + throws AiravataSystemException { + try { + return registryService.getApplicationDeployments(appModuleId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving application deployments: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerApplicationInterface(String gatewayId, ApplicationInterfaceDescription applicationInterface) + throws AiravataSystemException { + try { + return registryService.registerApplicationInterface(gatewayId, applicationInterface); + } catch (RegistryServiceException e) { + String msg = "Error while adding application interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String cloneApplicationInterface(String existingAppInterfaceID, String newApplicationName, String gatewayId) + throws AiravataSystemException, InvalidRequestException, AuthorizationException { + try { + var existingInterface = getApplicationInterface(existingAppInterfaceID); + if (existingInterface == null) { + String msg = + "Provided application interface does not exist.Please provide a valid application interface id..."; + logger.error(msg); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, null); + } + + existingInterface.setApplicationName(newApplicationName); + existingInterface.setApplicationInterfaceId(airavata_commonsConstants.DEFAULT_ID); + var interfaceId = registerApplicationInterface(gatewayId, existingInterface); + logger.debug("Airavata cloned application interface : " + existingAppInterfaceID + " for gateway id : " + + gatewayId); + return interfaceId; + } catch (AiravataSystemException e) { + throw e; + } + } + + public boolean updateApplicationInterface( + String appInterfaceId, ApplicationInterfaceDescription applicationInterface) + throws AiravataSystemException { + try { + return registryService.updateApplicationInterface(appInterfaceId, applicationInterface); + } catch (RegistryServiceException e) { + String msg = "Error while updating application interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteApplicationInterface(String appInterfaceId) throws AiravataSystemException { + try { + return registryService.deleteApplicationInterface(appInterfaceId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting application interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public Map getAllApplicationInterfaceNames(String gatewayId) throws AiravataSystemException { + try { + return registryService.getAllApplicationInterfaceNames(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving application interfaces: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllApplicationInterfaces(String gatewayId) + throws AiravataSystemException { + try { + return registryService.getAllApplicationInterfaces(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving application interfaces: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getApplicationInputs(String appInterfaceId) throws AiravataSystemException { + try { + return registryService.getApplicationInputs(appInterfaceId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving application inputs: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerApplicationModule(String gatewayId, ApplicationModule applicationModule) + throws AiravataSystemException { + try { + return registryService.registerApplicationModule(gatewayId, applicationModule); + } catch (RegistryServiceException e) { + String msg = "Error while adding application module: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ApplicationModule getApplicationModule(String appModuleId) throws AiravataSystemException { + try { + return registryService.getApplicationModule(appModuleId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving application module: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateApplicationModule(String appModuleId, ApplicationModule applicationModule) + throws AiravataSystemException { + try { + return registryService.updateApplicationModule(appModuleId, applicationModule); + } catch (RegistryServiceException e) { + String msg = "Error while updating application module: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllAppModules(String gatewayId) throws AiravataSystemException { + try { + return registryService.getAllAppModules(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving all application modules: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteApplicationModule(String appModuleId) throws AiravataSystemException { + try { + return registryService.deleteApplicationModule(appModuleId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting application module: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAccessibleAppModules( + String gatewayId, List accessibleAppIds, List accessibleComputeResourceIds) + throws RegistryServiceException { + return registryService.getAccessibleAppModules(gatewayId, accessibleAppIds, accessibleComputeResourceIds); + } + + /** + * Get accessible app modules with sharing registry integration + */ + public List getAccessibleAppModules(AuthzToken authzToken, String gatewayId) + throws InvalidRequestException, AiravataSystemException, AuthorizationException { + try { + var userName = authzToken.getClaimsMap().get(Constants.USER_NAME); + var accessibleAppDeploymentIds = new ArrayList(); + if (ServerSettings.isEnableSharing()) { + List sharingFilters = new ArrayList<>(); + var entityTypeFilter = new SearchCriteria(); + entityTypeFilter.setSearchField(EntitySearchField.ENTITY_TYPE_ID); + entityTypeFilter.setSearchCondition(SearchCondition.EQUAL); + entityTypeFilter.setValue(gatewayId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); + sharingFilters.add(entityTypeFilter); + var permissionTypeFilter = new SearchCriteria(); + permissionTypeFilter.setSearchField(EntitySearchField.PERMISSION_TYPE_ID); + permissionTypeFilter.setSearchCondition(SearchCondition.EQUAL); + permissionTypeFilter.setValue(gatewayId + ":" + ResourcePermissionType.READ); + sharingFilters.add(permissionTypeFilter); + sharingRegistryService + .searchEntities( + authzToken.getClaimsMap().get(Constants.GATEWAY_ID), + userName + "@" + gatewayId, + sharingFilters, + 0, + -1) + .forEach(a -> accessibleAppDeploymentIds.add(a.getEntityId())); + } + var accessibleComputeResourceIds = new ArrayList(); + List groupResourceProfileList = getGroupResourceList(authzToken, gatewayId); + for (GroupResourceProfile groupResourceProfile : groupResourceProfileList) { + List groupComputeResourcePreferenceList = + groupResourceProfile.getComputePreferences(); + for (GroupComputeResourcePreference groupComputeResourcePreference : + groupComputeResourcePreferenceList) { + accessibleComputeResourceIds.add(groupComputeResourcePreference.getComputeResourceId()); + } + } + return getAccessibleAppModules(gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds); + } catch (AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException | RegistryServiceException | SharingRegistryException e) { + String msg = "Error occurred while getting accessible app modules: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public Map getJobStatuses(String airavataExperimentId) throws AiravataSystemException { + try { + return registryService.getJobStatuses(airavataExperimentId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving job statuses: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getJobDetails(String airavataExperimentId) throws AiravataSystemException { + try { + return registryService.getJobDetails(airavataExperimentId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving job details: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String addLocalSubmissionDetails( + String computeResourceId, int priorityOrder, LOCALSubmission localSubmission) + throws AiravataSystemException { + try { + return registryService.addLocalSubmissionDetails(computeResourceId, priorityOrder, localSubmission); + } catch (RegistryServiceException e) { + String msg = "Error while adding local job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String addSSHJobSubmissionDetails( + String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission) + throws AiravataSystemException { + try { + return registryService.addSSHJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission); + } catch (RegistryServiceException e) { + String msg = "Error while adding SSH job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String addSSHForkJobSubmissionDetails( + String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission) + throws AiravataSystemException { + try { + return registryService.addSSHForkJobSubmissionDetails(computeResourceId, priorityOrder, sshJobSubmission); + } catch (RegistryServiceException e) { + String msg = "Error while adding SSH fork job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String addCloudJobSubmissionDetails( + String computeResourceId, int priorityOrder, CloudJobSubmission cloudJobSubmission) + throws AiravataSystemException { + try { + return registryService.addCloudJobSubmissionDetails(computeResourceId, priorityOrder, cloudJobSubmission); + } catch (RegistryServiceException e) { + String msg = "Error while adding cloud job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String addUNICOREJobSubmissionDetails( + String computeResourceId, int priorityOrder, UnicoreJobSubmission unicoreJobSubmission) + throws AiravataSystemException { + try { + return registryService.addUNICOREJobSubmissionDetails( + computeResourceId, priorityOrder, unicoreJobSubmission); + } catch (RegistryServiceException e) { + String msg = "Error while adding UNICORE job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateLocalSubmissionDetails(String jobSubmissionInterfaceId, LOCALSubmission localSubmission) + throws AiravataSystemException { + try { + return registryService.updateLocalSubmissionDetails(jobSubmissionInterfaceId, localSubmission); + } catch (Throwable e) { + String msg = "Error while updating local job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public LOCALSubmission getLocalJobSubmission(String jobSubmissionId) throws AiravataSystemException { + try { + return registryService.getLocalJobSubmission(jobSubmissionId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving local job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public SSHJobSubmission getSSHJobSubmission(String jobSubmissionId) throws AiravataSystemException { + try { + return registryService.getSSHJobSubmission(jobSubmissionId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving SSH job submission: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public CloudJobSubmission getCloudJobSubmission(String jobSubmissionId) throws AiravataSystemException { + try { + return registryService.getCloudJobSubmission(jobSubmissionId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving cloud job submission: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public UnicoreJobSubmission getUnicoreJobSubmission(String jobSubmissionId) throws AiravataSystemException { + try { + return registryService.getUnicoreJobSubmission(jobSubmissionId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving UNICORE job submission: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateSSHJobSubmissionDetails(String jobSubmissionInterfaceId, SSHJobSubmission sshJobSubmission) + throws AiravataSystemException { + try { + return registryService.updateSSHJobSubmissionDetails(jobSubmissionInterfaceId, sshJobSubmission); + } catch (RegistryServiceException e) { + String msg = "Error while updating job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateCloudJobSubmissionDetails( + String jobSubmissionInterfaceId, CloudJobSubmission cloudJobSubmission) throws AiravataSystemException { + try { + return registryService.updateCloudJobSubmissionDetails(jobSubmissionInterfaceId, cloudJobSubmission); + } catch (RegistryServiceException e) { + String msg = "Error while updating job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateUnicoreJobSubmissionDetails( + String jobSubmissionInterfaceId, UnicoreJobSubmission unicoreJobSubmission) throws AiravataSystemException { + try { + return registryService.updateUnicoreJobSubmissionDetails(jobSubmissionInterfaceId, unicoreJobSubmission); + } catch (RegistryServiceException e) { + String msg = "Error while updating job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteJobSubmissionInterface(String computeResourceId, String jobSubmissionInterfaceId) + throws AiravataSystemException { + try { + return registryService.deleteJobSubmissionInterface(computeResourceId, jobSubmissionInterfaceId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting job submission interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerResourceJobManager(ResourceJobManager resourceJobManager) throws AiravataSystemException { + try { + return registryService.registerResourceJobManager(resourceJobManager); + } catch (RegistryServiceException e) { + String msg = "Error while adding resource job manager: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateResourceJobManager(String resourceJobManagerId, ResourceJobManager updatedResourceJobManager) + throws AiravataSystemException { + try { + return registryService.updateResourceJobManager(resourceJobManagerId, updatedResourceJobManager); + } catch (RegistryServiceException e) { + String msg = "Error while updating resource job manager: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ResourceJobManager getResourceJobManager(String resourceJobManagerId) throws AiravataSystemException { + try { + return registryService.getResourceJobManager(resourceJobManagerId); + } catch (Throwable e) { + String msg = "Error while retrieving resource job manager: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteResourceJobManager(String resourceJobManagerId) throws AiravataSystemException { + try { + return registryService.deleteResourceJobManager(resourceJobManagerId); + } catch (Throwable e) { + String msg = "Error while deleting resource job manager: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String addPasswordCredential(PasswordCredential passwordCredential) throws CredentialStoreException { + return credentialStoreService.addPasswordCredential(passwordCredential); + } + + public void deletePWDCredential(String tokenId, String gatewayId) throws CredentialStoreException { + credentialStoreService.deletePWDCredential(tokenId, gatewayId); + } + + public boolean deleteSSHCredential(String tokenId, String gatewayId) throws CredentialStoreException { + return credentialStoreService.deleteSSHCredential(tokenId, gatewayId); + } + + public CredentialSummary getCredentialSummary(String tokenId, String gatewayId) throws CredentialStoreException { + return credentialStoreService.getCredentialSummary(tokenId, gatewayId); + } + + public List getAllCredentialSummaries( + SummaryType type, List accessibleTokenIds, String gatewayId) throws CredentialStoreException { + return credentialStoreService.getAllCredentialSummaries(type, accessibleTokenIds, gatewayId); + } + + public String addLocalDataMovementDetails( + String resourceId, DMType dmType, int priorityOrder, LOCALDataMovement localDataMovement) + throws AiravataSystemException { + try { + return registryService.addLocalDataMovementDetails(resourceId, dmType, priorityOrder, localDataMovement); + } catch (RegistryServiceException e) { + String msg = "Error while adding data movement interface to resource: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateLocalDataMovementDetails(String dataMovementInterfaceId, LOCALDataMovement localDataMovement) + throws AiravataSystemException { + try { + return registryService.updateLocalDataMovementDetails(dataMovementInterfaceId, localDataMovement); + } catch (RegistryServiceException e) { + String msg = "Error while updating local data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public LOCALDataMovement getLocalDataMovement(String dataMovementId) throws AiravataSystemException { + try { + return registryService.getLocalDataMovement(dataMovementId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving local data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String addSCPDataMovementDetails( + String resourceId, DMType dmType, int priorityOrder, SCPDataMovement scpDataMovement) + throws AiravataSystemException { + try { + return registryService.addSCPDataMovementDetails(resourceId, dmType, priorityOrder, scpDataMovement); + } catch (RegistryServiceException e) { + String msg = "Error while adding SCP data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateSCPDataMovementDetails(String dataMovementInterfaceId, SCPDataMovement scpDataMovement) + throws AiravataSystemException { + try { + return registryService.updateSCPDataMovementDetails(dataMovementInterfaceId, scpDataMovement); + } catch (RegistryServiceException e) { + String msg = "Error while updating SCP data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getUserProjects(String gatewayId, String userName, int limit, int offset) + throws RegistryServiceException { + return registryService.getUserProjects(gatewayId, userName, limit, offset); + } + + /** + * Get user projects with sharing registry integration + */ + public List getUserProjects( + AuthzToken authzToken, String gatewayId, String userName, int limit, int offset) + throws AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + // user projects + user accessible projects + var accessibleProjectIds = new ArrayList(); + var filters = new ArrayList(); + var searchCriteria = new SearchCriteria(); + searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); + searchCriteria.setSearchCondition(SearchCondition.EQUAL); + searchCriteria.setValue(gatewayId + ":PROJECT"); + filters.add(searchCriteria); + sharingRegistryService + .searchEntities( + authzToken.getClaimsMap().get(Constants.GATEWAY_ID), + userName + "@" + gatewayId, + filters, + 0, + -1) + .stream() + .forEach(p -> accessibleProjectIds.add(p.getEntityId())); + List result; + if (accessibleProjectIds.isEmpty()) { + result = Collections.emptyList(); + } else { + result = searchProjects(gatewayId, userName, accessibleProjectIds, new HashMap<>(), limit, offset); + } + return result; + } else { + return getUserProjects(gatewayId, userName, limit, offset); + } + } catch (ApplicationSettingsException | RegistryServiceException | SharingRegistryException e) { + String msg = "Error while retrieving user projects: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAccessibleApplicationDeployments( + String gatewayId, List accessibleAppDeploymentIds, List accessibleComputeResourceIds) + throws RegistryServiceException { + return registryService.getAccessibleApplicationDeployments( + gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds); + } + + /** + * Get accessible application deployments with sharing registry integration + */ + public List getAccessibleApplicationDeployments( + AuthzToken authzToken, String gatewayId, ResourcePermissionType permissionType) + throws InvalidRequestException, AiravataSystemException, AuthorizationException { + try { + String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); + List accessibleAppDeploymentIds = new ArrayList<>(); + if (ServerSettings.isEnableSharing()) { + List sharingFilters = new ArrayList<>(); + var entityTypeFilter = new SearchCriteria(); + entityTypeFilter.setSearchField(EntitySearchField.ENTITY_TYPE_ID); + entityTypeFilter.setSearchCondition(SearchCondition.EQUAL); + entityTypeFilter.setValue(gatewayId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); + sharingFilters.add(entityTypeFilter); + var permissionTypeFilter = new SearchCriteria(); + permissionTypeFilter.setSearchField(EntitySearchField.PERMISSION_TYPE_ID); + permissionTypeFilter.setSearchCondition(SearchCondition.EQUAL); + permissionTypeFilter.setValue(gatewayId + ":" + permissionType.name()); + sharingFilters.add(permissionTypeFilter); + sharingRegistryService + .searchEntities( + authzToken.getClaimsMap().get(Constants.GATEWAY_ID), + userName + "@" + gatewayId, + sharingFilters, + 0, + -1) + .forEach(a -> accessibleAppDeploymentIds.add(a.getEntityId())); + } + var accessibleComputeResourceIds = new ArrayList(); + List groupResourceProfileList = getGroupResourceList(authzToken, gatewayId); + for (GroupResourceProfile groupResourceProfile : groupResourceProfileList) { + List groupComputeResourcePreferenceList = + groupResourceProfile.getComputePreferences(); + for (GroupComputeResourcePreference groupComputeResourcePreference : + groupComputeResourcePreferenceList) { + accessibleComputeResourceIds.add(groupComputeResourcePreference.getComputeResourceId()); + } + } + return getAccessibleApplicationDeployments( + gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds); + } catch (ApplicationSettingsException | RegistryServiceException | SharingRegistryException e) { + String msg = "Error occurred while getting accessible application deployments: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAppModuleDeployedResources(String appModuleId) throws AiravataSystemException { + try { + return registryService.getAppModuleDeployedResources(appModuleId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving application deployment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAccessibleApplicationDeploymentsForAppModule( + String appModuleId, + String gatewayId, + List accessibleAppDeploymentIds, + List accessibleComputeResourceIds) + throws AiravataSystemException { + try { + return registryService.getAccessibleApplicationDeploymentsForAppModule( + gatewayId, appModuleId, accessibleAppDeploymentIds, accessibleComputeResourceIds); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving accessible application deployments: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getApplicationDeploymentsForAppModuleAndGroupResourceProfile( + AuthzToken authzToken, String appModuleId, String groupResourceProfileId) + throws AuthorizationException, InvalidRequestException, AiravataSystemException { + try { + var userName = authzToken.getClaimsMap().get(Constants.USER_NAME); + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + + // Get list of compute resources for this Group Resource Profile + if (!userHasAccess(authzToken, groupResourceProfileId, ResourcePermissionType.READ)) { + throw new AuthorizationException( + "User is not authorized to access Group Resource Profile " + groupResourceProfileId); + } + var groupResourceProfile = getGroupResourceProfile(groupResourceProfileId); + var accessibleComputeResourceIds = groupResourceProfile.getComputePreferences().stream() + .map(compPref -> compPref.getComputeResourceId()) + .collect(Collectors.toList()); + + // Get list of accessible Application Deployments + var accessibleAppDeploymentIds = new ArrayList(); + var sharingFilters = new ArrayList(); + var entityTypeFilter = new SearchCriteria(); + entityTypeFilter.setSearchField(EntitySearchField.ENTITY_TYPE_ID); + entityTypeFilter.setSearchCondition(SearchCondition.EQUAL); + entityTypeFilter.setValue(gatewayId + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); + sharingFilters.add(entityTypeFilter); + var permissionTypeFilter = new SearchCriteria(); + permissionTypeFilter.setSearchField(EntitySearchField.PERMISSION_TYPE_ID); + permissionTypeFilter.setSearchCondition(SearchCondition.EQUAL); + permissionTypeFilter.setValue(gatewayId + ":" + ResourcePermissionType.READ); + sharingFilters.add(permissionTypeFilter); + searchEntities(gatewayId, userName + "@" + gatewayId, sharingFilters, 0, -1) + .forEach(a -> accessibleAppDeploymentIds.add(a.delegate().getEntityId())); + + return getAccessibleApplicationDeploymentsForAppModule( + appModuleId, gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds); + } catch (AiravataSystemException e) { + throw e; + } catch (SharingRegistryException e) { + String msg = "Error while retrieving application deployments: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public Map getAvailableAppInterfaceComputeResources(String appInterfaceId) + throws AiravataSystemException { + try { + return registryService.getAvailableAppInterfaceComputeResources(appInterfaceId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving available compute resources: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public SCPDataMovement getSCPDataMovement(String dataMovementId) throws AiravataSystemException { + try { + return registryService.getSCPDataMovement(dataMovementId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving SCP data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String addUnicoreDataMovementDetails( + String resourceId, DMType dmType, int priorityOrder, UnicoreDataMovement unicoreDataMovement) + throws AiravataSystemException { + try { + return registryService.addUnicoreDataMovementDetails( + resourceId, dmType, priorityOrder, unicoreDataMovement); + } catch (RegistryServiceException e) { + String msg = "Error while adding UNICORE data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateUnicoreDataMovementDetails( + String dataMovementInterfaceId, UnicoreDataMovement unicoreDataMovement) throws AiravataSystemException { + try { + return registryService.updateUnicoreDataMovementDetails(dataMovementInterfaceId, unicoreDataMovement); + } catch (RegistryServiceException e) { + String msg = "Error while updating unicore data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public UnicoreDataMovement getUnicoreDataMovement(String dataMovementId) throws AiravataSystemException { + try { + return registryService.getUnicoreDataMovement(dataMovementId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving UNICORE data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String addGridFTPDataMovementDetails( + String resourceId, DMType dmType, int priorityOrder, GridFTPDataMovement gridFTPDataMovement) + throws AiravataSystemException { + try { + return registryService.addGridFTPDataMovementDetails( + resourceId, dmType, priorityOrder, gridFTPDataMovement); + } catch (RegistryServiceException e) { + String msg = "Error while adding GridFTP data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateGridFTPDataMovementDetails( + String dataMovementInterfaceId, GridFTPDataMovement gridFTPDataMovement) throws AiravataSystemException { + try { + return registryService.updateGridFTPDataMovementDetails(dataMovementInterfaceId, gridFTPDataMovement); + } catch (RegistryServiceException e) { + String msg = "Error while updating GridFTP data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public GridFTPDataMovement getGridFTPDataMovement(String dataMovementId) throws AiravataSystemException { + try { + return registryService.getGridFTPDataMovement(dataMovementId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving GridFTP data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteDataMovementInterface(String resourceId, String dataMovementInterfaceId, DMType dmType) + throws AiravataSystemException { + try { + return registryService.deleteDataMovementInterface(resourceId, dataMovementInterfaceId, dmType); + } catch (RegistryServiceException e) { + String msg = "Error while deleting data movement interface: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteBatchQueue(String computeResourceId, String queueName) throws AiravataSystemException { + try { + return registryService.deleteBatchQueue(computeResourceId, queueName); + } catch (RegistryServiceException e) { + String msg = "Error while deleting batch queue: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean addGatewayComputeResourcePreference( + String gatewayID, String computeResourceId, ComputeResourcePreference computeResourcePreference) + throws AiravataSystemException { + try { + return registryService.addGatewayComputeResourcePreference( + gatewayID, computeResourceId, computeResourcePreference); + } catch (RegistryServiceException e) { + String msg = "Error while registering gateway resource profile preference: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean addGatewayStoragePreference( + String gatewayID, String storageResourceId, StoragePreference dataStoragePreference) + throws AiravataSystemException { + try { + return registryService.addGatewayStoragePreference(gatewayID, storageResourceId, dataStoragePreference); + } catch (RegistryServiceException e) { + String msg = "Error while registering gateway storage preference: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ComputeResourcePreference getGatewayComputeResourcePreference(String gatewayID, String computeResourceId) + throws AiravataSystemException { + try { + return registryService.getGatewayComputeResourcePreference(gatewayID, computeResourceId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving gateway compute resource preference: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public StoragePreference getGatewayStoragePreference(String gatewayID, String storageId) + throws AiravataSystemException { + try { + return registryService.getGatewayStoragePreference(gatewayID, storageId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving gateway storage preference: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllGatewayComputeResourcePreferences(String gatewayID) + throws AiravataSystemException { + try { + return registryService.getAllGatewayComputeResourcePreferences(gatewayID); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving all gateway compute resource preferences: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllGatewayStoragePreferences(String gatewayID) throws AiravataSystemException { + try { + return registryService.getAllGatewayStoragePreferences(gatewayID); + } catch (Throwable e) { + String msg = "Error while retrieving all gateway storage preferences: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllGatewayResourceProfiles() throws AiravataSystemException { + try { + return registryService.getAllGatewayResourceProfiles(); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving all gateway resource profiles: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateGatewayComputeResourcePreference( + String gatewayID, String computeResourceId, ComputeResourcePreference computeResourcePreference) + throws AiravataSystemException { + try { + return registryService.updateGatewayComputeResourcePreference( + gatewayID, computeResourceId, computeResourcePreference); + } catch (RegistryServiceException e) { + String msg = "Error while updating gateway compute resource preference: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateGatewayStoragePreference( + String gatewayID, String storageId, StoragePreference dataStoragePreference) + throws AiravataSystemException { + try { + return registryService.updateGatewayStoragePreference(gatewayID, storageId, dataStoragePreference); + } catch (RegistryServiceException e) { + String msg = "Error while updating gateway data storage preference: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteGatewayComputeResourcePreference(String gatewayID, String computeResourceId) + throws AiravataSystemException { + try { + return registryService.deleteGatewayComputeResourcePreference(gatewayID, computeResourceId); + } catch (Throwable e) { + String msg = "Error while deleting gateway compute resource preference: " + gatewayID + " " + + computeResourceId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteGatewayStoragePreference(String gatewayID, String storageId) throws AiravataSystemException { + try { + return registryService.deleteGatewayStoragePreference(gatewayID, storageId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting gateway data storage preference: " + gatewayID + " " + storageId + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerUserResourceProfile(UserResourceProfile userResourceProfile) throws AiravataSystemException { + try { + return registryService.registerUserResourceProfile(userResourceProfile); + } catch (RegistryServiceException e) { + String msg = "Error while registering user resource profile: " + userResourceProfile.getUserId() + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean isUserResourceProfileExists(String userId, String gatewayId) throws AiravataSystemException { + try { + return registryService.isUserResourceProfileExists(userId, gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while checking existence of user resource profile: " + userId + " " + gatewayId + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean addUserComputeResourcePreference( + String userId, + String gatewayID, + String computeResourceId, + UserComputeResourcePreference userComputeResourcePreference) + throws AiravataSystemException { + try { + return registryService.addUserComputeResourcePreference( + userId, gatewayID, computeResourceId, userComputeResourcePreference); + } catch (Throwable e) { + String msg = "Error while registering user resource profile preference: " + userId + " " + gatewayID + " " + + computeResourceId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean addUserStoragePreference( + String userId, String gatewayID, String userStorageResourceId, UserStoragePreference dataStoragePreference) + throws AiravataSystemException { + try { + return registryService.addUserStoragePreference( + userId, gatewayID, userStorageResourceId, dataStoragePreference); + } catch (RegistryServiceException e) { + String msg = "Error while registering user storage preference: " + userId + " " + gatewayID + " " + + userStorageResourceId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public UserComputeResourcePreference getUserComputeResourcePreference( + String userId, String gatewayID, String userComputeResourceId) throws AiravataSystemException { + try { + return registryService.getUserComputeResourcePreference(userId, gatewayID, userComputeResourceId); + } catch (RegistryServiceException e) { + String msg = "Error while reading user compute resource preference: " + userId + " " + gatewayID + " " + + userComputeResourceId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public UserStoragePreference getUserStoragePreference(String userId, String gatewayID, String userStorageId) + throws AiravataSystemException { + try { + return registryService.getUserStoragePreference(userId, gatewayID, userStorageId); + } catch (RegistryServiceException e) { + String msg = "Error while reading user data storage preference: " + userId + " " + gatewayID + " " + + userStorageId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllUserComputeResourcePreferences(String userId, String gatewayID) + throws AiravataSystemException { + try { + return registryService.getAllUserComputeResourcePreferences(userId, gatewayID); + } catch (RegistryServiceException e) { + String msg = "Error while reading User compute resource preferences: " + userId + " " + gatewayID + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllUserStoragePreferences(String userId, String gatewayID) + throws AiravataSystemException { + try { + return registryService.getAllUserStoragePreferences(userId, gatewayID); + } catch (RegistryServiceException e) { + String msg = "Error while reading User data storage preferences: " + userId + " " + gatewayID + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllUserResourceProfiles() throws AiravataSystemException { + try { + return registryService.getAllUserResourceProfiles(); + } catch (RegistryServiceException e) { + String msg = "Error while reading retrieving all user resource profiles: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateUserComputeResourcePreference( + String userId, + String gatewayID, + String computeResourceId, + UserComputeResourcePreference userComputeResourcePreference) + throws AiravataSystemException { + try { + return registryService.updateUserComputeResourcePreference( + userId, gatewayID, computeResourceId, userComputeResourcePreference); + } catch (RegistryServiceException e) { + String msg = "Error while updating user compute resource preference: " + userId + " " + gatewayID + " " + + computeResourceId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean updateUserStoragePreference( + String userId, String gatewayID, String userStorageId, UserStoragePreference userStoragePreference) + throws AiravataSystemException { + try { + return registryService.updateUserStoragePreference(userId, gatewayID, userStorageId, userStoragePreference); + } catch (RegistryServiceException e) { + String msg = "Error while updating user data storage preference: " + userId + " " + gatewayID + " " + + userStorageId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteUserComputeResourcePreference(String userId, String gatewayID, String userComputeResourceId) + throws AiravataSystemException { + try { + return registryService.deleteUserComputeResourcePreference(userId, gatewayID, userComputeResourceId); + } catch (Throwable e) { + String msg = "Error while deleting user compute resource preference: " + userId + " " + gatewayID + " " + + userComputeResourceId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteUserStoragePreference(String userId, String gatewayID, String userStorageId) + throws AiravataSystemException { + try { + return registryService.deleteUserStoragePreference(userId, gatewayID, userStorageId); + } catch (RegistryServiceException e) { + String msg = "Error while deleting user data storage preference: " + userId + " " + gatewayID + " " + + userStorageId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getLatestQueueStatuses() throws AiravataSystemException { + try { + return registryService.getLatestQueueStatuses(); + } catch (Throwable e) { + String msg = "Error in retrieving queue statuses: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String createGroupResourceProfile(GroupResourceProfile groupResourceProfile) throws AiravataSystemException { + try { + return registryService.createGroupResourceProfile(groupResourceProfile); + } catch (RegistryServiceException e) { + String msg = "Error while creating group resource profile: " + + groupResourceProfile.getGroupResourceProfileId() + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean removeGroupResourceProfile(String groupResourceProfileId) throws AiravataSystemException { + try { + return registryService.removeGroupResourceProfile(groupResourceProfileId); + } catch (RegistryServiceException e) { + String msg = + "Error while removing group resource profile: " + groupResourceProfileId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean removeGroupComputePrefs(String computeResourceId, String groupResourceProfileId) + throws AiravataSystemException { + try { + return registryService.removeGroupComputePrefs(computeResourceId, groupResourceProfileId); + } catch (RegistryServiceException e) { + String msg = "Error while removing group compute preferences: " + computeResourceId + " " + + groupResourceProfileId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public GroupComputeResourcePreference getGroupComputeResourcePreference( + String computeResourceId, String groupResourceProfileId) throws AiravataSystemException { + try { + return registryService.getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving group compute resource preference: " + computeResourceId + " " + + groupResourceProfileId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ComputeResourcePolicy getGroupComputeResourcePolicy(String resourcePolicyId) throws AiravataSystemException { + try { + return registryService.getGroupComputeResourcePolicy(resourcePolicyId); + } catch (RegistryServiceException e) { + String msg = + "Error while retrieving group compute resource policy: " + resourcePolicyId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean removeGroupComputeResourcePolicy(String resourcePolicyId) throws AiravataSystemException { + try { + return registryService.removeGroupComputeResourcePolicy(resourcePolicyId); + } catch (RegistryServiceException e) { + String msg = + "Error while removing group compute resource policy: " + resourcePolicyId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public BatchQueueResourcePolicy getBatchQueueResourcePolicy(String resourcePolicyId) + throws AiravataSystemException { + try { + return registryService.getBatchQueueResourcePolicy(resourcePolicyId); + } catch (RegistryServiceException e) { + String msg = + "Error while retrieving batch queue resource policy: " + resourcePolicyId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean removeGroupBatchQueueResourcePolicy(String resourcePolicyId) throws AiravataSystemException { + try { + return registryService.removeGroupBatchQueueResourcePolicy(resourcePolicyId); + } catch (RegistryServiceException e) { + String msg = "Error while removing group batch queue resource policy: " + resourcePolicyId + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getGroupComputeResourcePrefList(String groupResourceProfileId) + throws AiravataSystemException { + try { + return registryService.getGroupComputeResourcePrefList(groupResourceProfileId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving group compute resource preference list: " + groupResourceProfileId + + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getGroupBatchQueueResourcePolicyList(String groupResourceProfileId) + throws AiravataSystemException { + try { + return registryService.getGroupBatchQueueResourcePolicyList(groupResourceProfileId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving group batch queue resource policy list: " + groupResourceProfileId + + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getGroupComputeResourcePolicyList(String groupResourceProfileId) + throws AiravataSystemException { + try { + return registryService.getGroupComputeResourcePolicyList(groupResourceProfileId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving group compute resource policy list: " + groupResourceProfileId + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public Parser getParser(String parserId, String gatewayId) throws AiravataSystemException { + try { + return registryService.getParser(parserId, gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving parser: " + parserId + " " + gatewayId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String saveParser(Parser parser) throws AiravataSystemException { + try { + return registryService.saveParser(parser); + } catch (RegistryServiceException e) { + String msg = + "Error while saving parser: " + parser.getId() + " " + parser.getGatewayId() + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List listAllParsers(String gatewayId) throws AiravataSystemException { + try { + return registryService.listAllParsers(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while listing all parsers: " + gatewayId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void removeParser(String parserId, String gatewayId) throws AiravataSystemException { + try { + registryService.removeParser(parserId, gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while removing parser: " + parserId + " " + gatewayId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ParsingTemplate getParsingTemplate(String templateId, String gatewayId) throws AiravataSystemException { + try { + return registryService.getParsingTemplate(templateId, gatewayId); + } catch (RegistryServiceException e) { + String msg = + "Error while retrieving parsing template: " + templateId + " " + gatewayId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getParsingTemplatesForExperiment(String experimentId, String gatewayId) + throws AiravataSystemException { + try { + return registryService.getParsingTemplatesForExperiment(experimentId, gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while retrieving parsing templates for experiment: " + experimentId + " " + gatewayId + + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String saveParsingTemplate(ParsingTemplate parsingTemplate) throws AiravataSystemException { + try { + return registryService.saveParsingTemplate(parsingTemplate); + } catch (RegistryServiceException e) { + String msg = "Error while saving parsing template: " + parsingTemplate.getId() + " " + + parsingTemplate.getGatewayId() + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void removeParsingTemplate(String templateId, String gatewayId) throws AiravataSystemException { + try { + registryService.removeParsingTemplate(templateId, gatewayId); + } catch (RegistryServiceException e) { + String msg = + "Error while removing parsing template: " + templateId + " " + gatewayId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List listAllParsingTemplates(String gatewayId) throws AiravataSystemException { + try { + return registryService.listAllParsingTemplates(gatewayId); + } catch (RegistryServiceException e) { + String msg = "Error while listing all parsing templates: " + gatewayId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + // Helper methods for sharing registry and authorization + public GatewayGroups retrieveGatewayGroups(String gatewayId) throws AiravataSystemException { + try { + if (isGatewayGroupsExists(gatewayId)) { + return getGatewayGroups(gatewayId); + } else { + return GatewayGroupsInitializer.initializeGatewayGroups(gatewayId); + } + } catch (AiravataSystemException e) { + throw e; + } + } + + public void createManageSharingPermissionTypeIfMissing(String domainId) throws AiravataSystemException { + // AIRAVATA-3297 Some gateways were created without the MANAGE_SHARING + // permission, so add it if missing + var permissionTypeId = domainId + ":MANAGE_SHARING"; + try { + if (!sharingRegistryService.isPermissionExists(domainId, permissionTypeId)) { + var permissionType = new PermissionType(); + permissionType.setPermissionTypeId(permissionTypeId); + permissionType.setDomainId(domainId); + permissionType.setName("MANAGE_SHARING"); + permissionType.setDescription("Manage sharing permission type"); + sharingRegistryService.createPermissionType(permissionType); + logger.info("Created MANAGE_SHARING permission type for domain " + domainId); + } + } catch (Exception e) { + String msg = "Error creating MANAGE_SHARING permission type: " + domainId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void shareEntityWithAdminGatewayGroups(Entity entity) + throws AiravataSystemException, InvalidRequestException, AuthorizationException, + ApplicationSettingsException, SharingRegistryException { + final String domainId = entity.getDomainId(); + GatewayGroups gatewayGroups = retrieveGatewayGroups(domainId); + createManageSharingPermissionTypeIfMissing(domainId); + sharingRegistryService.shareEntityWithGroups( + domainId, + entity.getEntityId(), + Arrays.asList(gatewayGroups.getAdminsGroupId()), + domainId + ":MANAGE_SHARING", + true); + sharingRegistryService.shareEntityWithGroups( + domainId, + entity.getEntityId(), + Arrays.asList(gatewayGroups.getAdminsGroupId()), + domainId + ":WRITE", + true); + sharingRegistryService.shareEntityWithGroups( + domainId, + entity.getEntityId(), + Arrays.asList(gatewayGroups.getAdminsGroupId(), gatewayGroups.getReadOnlyAdminsGroupId()), + domainId + ":READ", + true); + } + + public boolean userHasAccess(AuthzToken authzToken, String entityId, ResourcePermissionType permissionType) + throws AiravataSystemException { + final String domainId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + final String userId = authzToken.getClaimsMap().get(Constants.USER_NAME) + "@" + domainId; + try { + final boolean hasOwnerAccess = sharingRegistryService.userHasAccess( + domainId, userId, entityId, domainId + ":" + ResourcePermissionType.OWNER); + boolean hasAccess = false; + if (permissionType.equals(ResourcePermissionType.WRITE)) { + hasAccess = hasOwnerAccess + || sharingRegistryService.userHasAccess( + domainId, userId, entityId, domainId + ":" + ResourcePermissionType.WRITE); + } else if (permissionType.equals(ResourcePermissionType.READ)) { + hasAccess = hasOwnerAccess + || sharingRegistryService.userHasAccess( + domainId, userId, entityId, domainId + ":" + ResourcePermissionType.READ); + } else if (permissionType.equals(ResourcePermissionType.MANAGE_SHARING)) { + hasAccess = hasOwnerAccess + || sharingRegistryService.userHasAccess( + domainId, userId, entityId, domainId + ":" + ResourcePermissionType.MANAGE_SHARING); + } else if (permissionType.equals(ResourcePermissionType.OWNER)) { + hasAccess = hasOwnerAccess; + } + return hasAccess; + } catch (Exception e) { + String msg = "Error while checking if user has access: " + entityId + " " + permissionType + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + // Credential management methods + public String generateAndRegisterSSHKeys(String gatewayId, String userName, String description) + throws InvalidRequestException, AiravataSystemException { + try { + var sshCredential = new SSHCredential(); + sshCredential.setUsername(userName); + sshCredential.setGatewayId(gatewayId); + sshCredential.setDescription(description); + var key = credentialStoreService.addSSHCredential(sshCredential); + + try { + var entity = new Entity(); + entity.setEntityId(key); + entity.setDomainId(gatewayId); + entity.setEntityTypeId(gatewayId + ":" + ResourceType.CREDENTIAL_TOKEN); + entity.setOwnerId(userName + "@" + gatewayId); + entity.setName(key); + entity.setDescription(description); + sharingRegistryService.createEntity(entity); + } catch (Exception ex) { + String msg = "Error while creating SSH credential: " + userName + " " + description + " " + + ex.getMessage() + ". rolling back ssh key creation"; + logger.error(msg, ex); + credentialStoreService.deleteSSHCredential(key, gatewayId); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, ex); + } + logger.debug("Airavata generated SSH keys for gateway : " + gatewayId + " and for user : " + userName); + return key; + } catch (AiravataSystemException e) { + throw e; + } catch (CredentialStoreException e) { + String msg = "Error occurred while registering SSH Credential: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String registerPwdCredential( + String gatewayId, String userName, String loginUserName, String password, String description) + throws InvalidRequestException, AiravataSystemException { + try { + var pwdCredential = new PasswordCredential(); + pwdCredential.setPortalUserName(userName); + pwdCredential.setLoginUserName(loginUserName); + pwdCredential.setPassword(password); + pwdCredential.setDescription(description); + pwdCredential.setGatewayId(gatewayId); + var key = addPasswordCredential(pwdCredential); + try { + var entity = new Entity(); + entity.setEntityId(key); + entity.setDomainId(gatewayId); + entity.setEntityTypeId(gatewayId + ":" + ResourceType.CREDENTIAL_TOKEN); + entity.setOwnerId(userName + "@" + gatewayId); + entity.setName(key); + entity.setDescription(description); + sharingRegistryService.createEntity(entity); + } catch (Exception ex) { + String msg = "Error while registering password credential: " + userName + " " + description + " " + + ex.getMessage() + ". rolling back password registration"; + logger.error(msg, ex); + try { + deletePWDCredential(key, gatewayId); + } catch (Exception rollbackEx) { + logger.error("Failed to rollback password credential deletion", rollbackEx); + } + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, ex); + } + logger.debug("Generated PWD credential for gateway: " + gatewayId + ", user: " + loginUserName); + return key; + } catch (AiravataSystemException e) { + throw e; + } catch (CredentialStoreException e) { + String msg = "Error occurred while registering password credential: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public CredentialSummary getCredentialSummary(AuthzToken authzToken, String tokenId, String gatewayId) + throws AiravataSystemException, AuthorizationException { + try { + if (!userHasAccess(authzToken, tokenId, ResourcePermissionType.READ)) { + throw new AuthorizationException("User does not have permission to access this resource"); + } + var credentialSummary = getCredentialSummary(tokenId, gatewayId); + logger.debug("Retrieved the credential summary for token: " + tokenId + ", GatewayId: " + gatewayId); + return credentialSummary; + } catch (AuthorizationException e) { + throw e; + } catch (CredentialStoreException e) { + String msg = "Error occurred while getting credential summary: " + tokenId + " " + gatewayId + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getAllCredentialSummaries( + AuthzToken authzToken, SummaryType type, String gatewayId, String userName) + throws AiravataSystemException, InvalidRequestException { + try { + List filters = new ArrayList<>(); + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); + searchCriteria.setSearchCondition(SearchCondition.EQUAL); + searchCriteria.setValue(gatewayId + ":" + ResourceType.CREDENTIAL_TOKEN.name()); + filters.add(searchCriteria); + List accessibleTokenIds = + sharingRegistryService + .searchEntities(gatewayId, userName + "@" + gatewayId, filters, 0, -1) + .stream() + .map(p -> p.getEntityId()) + .collect(Collectors.toList()); + List credentialSummaries = + getAllCredentialSummaries(type, accessibleTokenIds, gatewayId); + logger.debug("Successfully retrieved credential summaries of type: " + type + ", GatewayId: " + gatewayId); + return credentialSummaries; + } catch (CredentialStoreException | SharingRegistryException e) { + String msg = "Error occurred while getting all credential summaries: " + type + " " + gatewayId + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteSSHPubKey(AuthzToken authzToken, String airavataCredStoreToken, String gatewayId) + throws AiravataSystemException, AuthorizationException { + try { + if (!userHasAccess(authzToken, airavataCredStoreToken, ResourcePermissionType.WRITE)) { + throw new AuthorizationException("User does not have permission to delete this resource."); + } + logger.debug("Deleted SSH pub key for gateway Id : " + gatewayId + " and with token id : " + + airavataCredStoreToken); + return deleteSSHCredential(airavataCredStoreToken, gatewayId); + } catch (AuthorizationException e) { + throw e; + } catch (CredentialStoreException e) { + String msg = "Error occurred while deleting SSH pub key: " + airavataCredStoreToken + " " + gatewayId + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deletePWDCredential(AuthzToken authzToken, String airavataCredStoreToken, String gatewayId) + throws AiravataSystemException, AuthorizationException { + try { + if (!userHasAccess(authzToken, airavataCredStoreToken, ResourcePermissionType.WRITE)) { + throw new AuthorizationException("User does not have permission to delete this resource."); + } + logger.debug("Deleted PWD credential for gateway Id : " + gatewayId + " and with token id : " + + airavataCredStoreToken); + deletePWDCredential(airavataCredStoreToken, gatewayId); + return true; + } catch (AuthorizationException e) { + throw e; + } catch (CredentialStoreException e) { + String msg = "Error occurred while deleting PWD credential: " + airavataCredStoreToken + " " + gatewayId + + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + // Project management methods with sharing registry integration + public String createProject(String gatewayId, Project project) throws AiravataSystemException { + try { + var projectId = registryService.createProject(gatewayId, project); + // TODO: verify that gatewayId and project.gatewayId match authzToken + if (ServerSettings.isEnableSharing()) { + try { + var entity = new Entity(); + entity.setEntityId(projectId); + final String domainId = project.getGatewayId(); + entity.setDomainId(domainId); + entity.setEntityTypeId(domainId + ":" + "PROJECT"); + entity.setOwnerId(project.getOwner() + "@" + domainId); + entity.setName(project.getName()); + entity.setDescription(project.getDescription()); + sharingRegistryService.createEntity(entity); + } catch (Exception ex) { + logger.error(ex.getMessage(), ex); + logger.error("Rolling back project creation Proj ID : " + projectId); + try { + deleteProject(projectId); + } catch (ProjectNotFoundException e) { + // Ignore - project may not exist if creation failed + } + String msg = + "Failed to create entry for project in Sharing Registry. More info : " + ex.getMessage(); + logger.error(msg, ex); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, ex); + } + } + logger.debug("Airavata created project with project Id : " + projectId + " for gateway Id : " + gatewayId); + return projectId; + } catch (AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException | RegistryServiceException e) { + String msg = "Error occurred while creating project: " + project.getName() + " " + project.getDescription() + + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void updateProject(AuthzToken authzToken, String projectId, Project updatedProject) + throws InvalidRequestException, AiravataSystemException, ProjectNotFoundException, AuthorizationException { + try { + var existingProject = getProject(projectId); + if (ServerSettings.isEnableSharing() + && !authzToken + .getClaimsMap() + .get(Constants.USER_NAME) + .equals(existingProject.getOwner()) + || !authzToken.getClaimsMap().get(Constants.GATEWAY_ID).equals(existingProject.getGatewayId())) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!sharingRegistryService.userHasAccess( + gatewayId, userId + "@" + gatewayId, projectId, gatewayId + ":WRITE")) { + throw new AuthorizationException("User does not have permission to access this resource"); + } + } + if (!updatedProject.getOwner().equals(existingProject.getOwner())) { + throw new InvalidRequestException("Owner of a project cannot be changed"); + } + if (!updatedProject.getGatewayId().equals(existingProject.getGatewayId())) { + throw new InvalidRequestException("Gateway ID of a project cannot be changed"); + } + updateProject(projectId, updatedProject); + logger.debug("Updated project with project Id : " + projectId); + } catch (ProjectNotFoundException + | AuthorizationException + | InvalidRequestException + | AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException | SharingRegistryException e) { + String msg = "Error occurred while updating project: " + projectId + " " + updatedProject.getName() + " " + + updatedProject.getDescription() + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean deleteProject(AuthzToken authzToken, String projectId) + throws AiravataSystemException, ProjectNotFoundException, AuthorizationException { + try { + var existingProject = getProject(projectId); + if (ServerSettings.isEnableSharing() + && !authzToken + .getClaimsMap() + .get(Constants.USER_NAME) + .equals(existingProject.getOwner()) + || !authzToken.getClaimsMap().get(Constants.GATEWAY_ID).equals(existingProject.getGatewayId())) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!sharingRegistryService.userHasAccess( + gatewayId, userId + "@" + gatewayId, projectId, gatewayId + ":WRITE")) { + throw new AuthorizationException("User does not have permission to access this resource"); + } + } + boolean ret = deleteProject(projectId); + logger.debug("Airavata deleted project with project Id : " + projectId); + return ret; + } catch (ProjectNotFoundException | AuthorizationException | AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException | SharingRegistryException e) { + String msg = "Error occurred while deleting project: " + projectId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public Project getProject(AuthzToken authzToken, String projectId) + throws AiravataSystemException, ProjectNotFoundException, AuthorizationException { + try { + var project = getProject(projectId); + if (authzToken.getClaimsMap().get(Constants.USER_NAME).equals(project.getOwner()) + && authzToken.getClaimsMap().get(Constants.GATEWAY_ID).equals(project.getGatewayId())) { + return project; + } else if (ServerSettings.isEnableSharing()) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!sharingRegistryService.userHasAccess( + gatewayId, userId + "@" + gatewayId, projectId, gatewayId + ":READ")) { + throw new AuthorizationException("User does not have permission to access this resource"); + } + return project; + } else { + return null; + } + } catch (ProjectNotFoundException | AuthorizationException | AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException | SharingRegistryException e) { + String msg = "Error occurred while getting project: " + projectId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + // Experiment management methods with sharing registry integration + public String createExperiment(String gatewayId, ExperimentModel experiment) throws AiravataSystemException { + try { + var experimentId = createExperimentInternal(gatewayId, experiment); + if (ServerSettings.isEnableSharing()) { + try { + var entity = new Entity(); + entity.setEntityId(experimentId); + final String domainId = experiment.getGatewayId(); + entity.setDomainId(domainId); + entity.setEntityTypeId(domainId + ":" + "EXPERIMENT"); + entity.setOwnerId(experiment.getUserName() + "@" + domainId); + entity.setName(experiment.getExperimentName()); + entity.setDescription(experiment.getDescription()); + entity.setParentEntityId(experiment.getProjectId()); + + sharingRegistryService.createEntity(entity); + shareEntityWithAdminGatewayGroups(entity); + } catch (Exception ex) { + logger.error(ex.getMessage(), ex); + logger.error("Rolling back experiment creation Exp ID : " + experimentId); + deleteExperiment(experimentId); + throw airavataSystemException( + AiravataErrorType.INTERNAL_ERROR, + "Failed to create sharing registry record. " + ex.getMessage(), + ex); + } + } + + logger.info( + experimentId, + "Created new experiment with experiment name {} and id ", + experiment.getExperimentName(), + experimentId); + return experimentId; + } catch (AiravataSystemException e) { + throw e; + } catch (Throwable e) { + String msg = "Error occurred while creating experiment: " + experiment.getExperimentName() + " " + + experiment.getExperimentId() + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void validateLaunchExperimentAccess(AuthzToken authzToken, String gatewayId, ExperimentModel experiment) + throws InvalidRequestException, AuthorizationException, AiravataSystemException, SharingRegistryException { + String username = authzToken.getClaimsMap().get(Constants.USER_NAME); + + // For backwards compatibility, if there is no groupResourceProfileId, look up + // one that is shared with the user + if (!experiment.getUserConfigurationData().isSetGroupResourceProfileId()) { + // This will be handled by the handler calling getGroupResourceList + throw new InvalidRequestException("Experiment doesn't have groupResourceProfileId"); + } + + // Verify user has READ access to groupResourceProfileId + if (!sharingRegistryService.userHasAccess( + gatewayId, + username + "@" + gatewayId, + experiment.getUserConfigurationData().getGroupResourceProfileId(), + gatewayId + ":READ")) { + throw new AuthorizationException("User " + username + " in gateway " + gatewayId + + " doesn't have access to group resource profile " + + experiment.getUserConfigurationData().getGroupResourceProfileId()); + } + + // Verify user has READ access to Application Deployment + final String appInterfaceId = experiment.getExecutionId(); + var applicationInterfaceDescription = getApplicationInterface(appInterfaceId); + + List appModuleIds = applicationInterfaceDescription.getApplicationModules(); + // Assume that there is only one app module for this interface + var appModuleId = appModuleIds.get(0); + List applicationDeploymentDescriptions = + getApplicationDeployments(appModuleId); + + if (!experiment.getUserConfigurationData().isAiravataAutoSchedule()) { + final String resourceHostId = experiment + .getUserConfigurationData() + .getComputationalResourceScheduling() + .getResourceHostId(); + + Optional applicationDeploymentDescription = + applicationDeploymentDescriptions.stream() + .filter(dep -> dep.getComputeHostId().equals(resourceHostId)) + .findFirst(); + if (applicationDeploymentDescription.isPresent()) { + final String appDeploymentId = + applicationDeploymentDescription.get().getAppDeploymentId(); + if (!sharingRegistryService.userHasAccess( + gatewayId, username + "@" + gatewayId, appDeploymentId, gatewayId + ":READ")) { + throw new AuthorizationException("User " + username + " in gateway " + gatewayId + + " doesn't have access to app deployment " + appDeploymentId); + } + } else { + throw new InvalidRequestException("Application deployment doesn't exist for application interface " + + appInterfaceId + " and host " + resourceHostId + " in gateway " + gatewayId); + } + } else if (experiment.getUserConfigurationData().getAutoScheduledCompResourceSchedulingList() != null + && !experiment + .getUserConfigurationData() + .getAutoScheduledCompResourceSchedulingList() + .isEmpty()) { + List compResourceSchedulingList = + experiment.getUserConfigurationData().getAutoScheduledCompResourceSchedulingList(); + for (ComputationalResourceSchedulingModel crScheduling : compResourceSchedulingList) { + Optional applicationDeploymentDescription = + applicationDeploymentDescriptions.stream() + .filter(dep -> dep.getComputeHostId().equals(crScheduling.getResourceHostId())) + .findFirst(); + if (applicationDeploymentDescription.isPresent()) { + final String appDeploymentId = + applicationDeploymentDescription.get().getAppDeploymentId(); + if (!sharingRegistryService.userHasAccess( + gatewayId, username + "@" + gatewayId, appDeploymentId, gatewayId + ":READ")) { + throw new AuthorizationException("User " + username + " in gateway " + gatewayId + + " doesn't have access to app deployment " + appDeploymentId); + } + } + } + } + } + + public boolean deleteExperimentWithAuth(AuthzToken authzToken, String experimentId) + throws AuthorizationException, InvalidRequestException, AiravataSystemException, + ExperimentNotFoundException, ProjectNotFoundException { + try { + var experimentModel = getExperiment(experimentId); + + if (ServerSettings.isEnableSharing() + && !authzToken + .getClaimsMap() + .get(Constants.USER_NAME) + .equals(experimentModel.getUserName()) + || !authzToken.getClaimsMap().get(Constants.GATEWAY_ID).equals(experimentModel.getGatewayId())) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!sharingRegistryService.userHasAccess( + gatewayId, userId + "@" + gatewayId, experimentId, gatewayId + ":WRITE")) { + throw new AuthorizationException("User does not have permission to access this resource"); + } + } + + if (!(experimentModel.getExperimentStatus().get(0).getState() == ExperimentState.CREATED)) { + throw new InvalidRequestException( + "Experiment is not in CREATED state. Hence cannot deleted. ID:" + experimentId); + } + return deleteExperiment(experimentId); + } catch (AuthorizationException | InvalidRequestException | AiravataSystemException e) { + throw e; + } catch (ApplicationSettingsException | SharingRegistryException e) { + String msg = "Error occurred while deleting experiment: " + experimentId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ResourceType getResourceType(String domainId, String entityId) throws AiravataSystemException { + try { + var entity = sharingRegistryService.getEntity(domainId, entityId); + for (ResourceType resourceType : ResourceType.values()) { + if (entity.getEntityTypeId().equals(domainId + ":" + resourceType.name())) { + return resourceType; + } + } + throw new RuntimeException("Unrecognized entity type id: " + entity.getEntityTypeId()); + } catch (SharingRegistryException e) { + String msg = "Error while getting resource type: " + domainId + " " + entityId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + // Gateway management methods with sharing registry integration + public String addGateway(Gateway gateway) throws AiravataSystemException { + try { + var gatewayId = registryService.addGateway(gateway); + Domain domain = new Domain(); + domain.setDomainId(gateway.getGatewayId()); + domain.setName(gateway.getGatewayName()); + domain.setDescription("Domain entry for " + domain.getName()); + sharingRegistryService.createDomain(domain); + + // Creating Entity Types for each domain + EntityType entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":PROJECT"); + entityType.setDomainId(domain.getDomainId()); + entityType.setName("PROJECT"); + entityType.setDescription("Project entity type"); + sharingRegistryService.createEntityType(entityType); + + entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":EXPERIMENT"); + entityType.setDomainId(domain.getDomainId()); + entityType.setName("EXPERIMENT"); + entityType.setDescription("Experiment entity type"); + sharingRegistryService.createEntityType(entityType); + + entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":FILE"); + entityType.setDomainId(domain.getDomainId()); + entityType.setName("FILE"); + entityType.setDescription("File entity type"); + sharingRegistryService.createEntityType(entityType); + + entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":" + ResourceType.APPLICATION_DEPLOYMENT.name()); + entityType.setDomainId(domain.getDomainId()); + entityType.setName("APPLICATION-DEPLOYMENT"); + entityType.setDescription("Application Deployment entity type"); + sharingRegistryService.createEntityType(entityType); + + entityType = new EntityType(); + entityType.setEntityTypeId(domain.getDomainId() + ":" + ResourceType.GROUP_RESOURCE_PROFILE.name()); + entityType.setDomainId(domain.getDomainId()); + entityType.setName(ResourceType.GROUP_RESOURCE_PROFILE.name()); + entityType.setDescription("Group Resource Profile entity type"); + sharingRegistryService.createEntityType(entityType); + + // Creating Permission Types for each domain + PermissionType permissionType = new PermissionType(); + permissionType.setPermissionTypeId(domain.getDomainId() + ":READ"); + permissionType.setDomainId(domain.getDomainId()); + permissionType.setName("READ"); + permissionType.setDescription("Read permission type"); + sharingRegistryService.createPermissionType(permissionType); + + permissionType = new PermissionType(); + permissionType.setPermissionTypeId(domain.getDomainId() + ":WRITE"); + permissionType.setDomainId(domain.getDomainId()); + permissionType.setName("WRITE"); + permissionType.setDescription("Write permission type"); + sharingRegistryService.createPermissionType(permissionType); + + permissionType = new PermissionType(); + permissionType.setPermissionTypeId(domain.getDomainId() + ":MANAGE_SHARING"); + permissionType.setDomainId(domain.getDomainId()); + permissionType.setName("MANAGE_SHARING"); + permissionType.setDescription("Sharing permission type"); + sharingRegistryService.createPermissionType(permissionType); + + logger.debug("Successfully created the gateway with " + gatewayId); + return gatewayId; + } catch (RegistryServiceException | SharingRegistryException | DuplicateEntryException e) { + String msg = "Error while adding gateway: " + gateway.getGatewayId() + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + // Event publishing methods + public void publishExperimentSubmitEvent(Publisher experimentPublisher, String gatewayId, String experimentId) + throws AiravataSystemException { + var event = new ExperimentSubmitEvent(experimentId, gatewayId); + var messageContext = new MessageContext( + event, MessageType.EXPERIMENT, "LAUNCH.EXP-" + UUID.randomUUID().toString(), gatewayId); + messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); + try { + experimentPublisher.publish(messageContext); + } catch (AiravataException e) { + String msg = "Error while publishing experiment submit event: " + experimentId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void publishExperimentCancelEvent(Publisher experimentPublisher, String gatewayId, String experimentId) + throws AiravataSystemException { + var event = new ExperimentSubmitEvent(experimentId, gatewayId); + var messageContext = new MessageContext( + event, + MessageType.EXPERIMENT_CANCEL, + "CANCEL.EXP-" + UUID.randomUUID().toString(), + gatewayId); + messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); + try { + experimentPublisher.publish(messageContext); + } catch (AiravataException e) { + String msg = "Error while publishing experiment cancel event: " + experimentId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void publishExperimentIntermediateOutputsEvent( + Publisher experimentPublisher, String gatewayId, String experimentId, List outputNames) + throws AiravataSystemException { + var event = new ExperimentIntermediateOutputsEvent(experimentId, gatewayId, outputNames); + var messageContext = new MessageContext( + event, + MessageType.INTERMEDIATE_OUTPUTS, + "INTERMEDIATE_OUTPUTS.EXP-" + UUID.randomUUID().toString(), + gatewayId); + messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); + try { + experimentPublisher.publish(messageContext); + } catch (AiravataException e) { + String msg = "Error while publishing experiment intermediate outputs event: " + experimentId + " " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + /** + * Validate and fetch intermediate outputs - checks access, job state, and + * existing processes + */ + public void fetchIntermediateOutputs(AuthzToken authzToken, String airavataExperimentId, List outputNames) + throws InvalidRequestException, AiravataSystemException, AuthorizationException { + try { + // Verify that user has WRITE access to experiment + final boolean hasAccess = userHasAccess(authzToken, airavataExperimentId, ResourcePermissionType.WRITE); + if (!hasAccess) { + var msg = "User does not have WRITE access to this experiment"; + logger.error(msg); + throw new AuthorizationException(msg); + } + + // Verify that the experiment's job is currently ACTIVE + ExperimentModel existingExperiment = getExperiment(airavataExperimentId); + var jobs = getJobDetails(airavataExperimentId); + boolean anyJobIsActive = jobs.stream().anyMatch(j -> { + if (j.getJobStatusesSize() > 0) { + return j.getJobStatuses().get(j.getJobStatusesSize() - 1).getJobState() == JobState.ACTIVE; + } else { + return false; + } + }); + if (!anyJobIsActive) { + var msg = "Experiment does not have currently ACTIVE job"; + logger.error(msg); + throw new InvalidRequestException(msg); + } + + // Figure out if there are any currently running intermediate output fetching + // processes for outputNames + // First, find any existing intermediate output fetch processes for outputNames + List intermediateOutputFetchProcesses = existingExperiment.getProcesses().stream() + .filter(p -> { + // Filter out completed or failed processes + if (p.getProcessStatusesSize() > 0) { + var latestStatus = p.getProcessStatuses().get(p.getProcessStatusesSize() - 1); + if (latestStatus.getState() == ProcessState.COMPLETED + || latestStatus.getState() == ProcessState.FAILED) { + return false; + } + } + return true; + }) + .filter(p -> { + return p.getTasks().stream().allMatch(t -> t.getTaskType() == TaskTypes.OUTPUT_FETCHING); + }) + .filter(p -> { + return p.getProcessOutputs().stream().anyMatch(o -> outputNames.contains(o.getName())); + }) + .collect(Collectors.toList()); + if (!intermediateOutputFetchProcesses.isEmpty()) { + var msg = "There are already intermediate output fetching tasks running for those outputs."; + logger.error(msg); + throw new InvalidRequestException(msg); + } + + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + publishExperimentIntermediateOutputsEvent( + experimentPublisher, gatewayId, airavataExperimentId, outputNames); + } catch (AuthorizationException | InvalidRequestException e) { + throw e; + } catch (Throwable e) { + String msg = "Error while processing request to fetch intermediate outputs for experiment: " + + airavataExperimentId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + /** + * Get intermediate output process status - finds the most recent matching + * process and returns its status + */ + public ProcessStatus getIntermediateOutputProcessStatus( + AuthzToken authzToken, String airavataExperimentId, List outputNames) + throws InvalidRequestException, AiravataSystemException, AuthorizationException { + try { + // Verify that user has READ access to experiment + final boolean hasAccess = userHasAccess(authzToken, airavataExperimentId, ResourcePermissionType.READ); + if (!hasAccess) { + var msg = "User does not have READ access to this experiment"; + logger.debug(msg); + throw new AuthorizationException(msg); + } + + ExperimentModel existingExperiment = getExperiment(airavataExperimentId); + + // Find the most recent intermediate output fetching process for the outputNames + // Assumption: only one of these output fetching processes runs at a + // time so we only need to check the status of the most recent one + Optional mostRecentOutputFetchProcess = existingExperiment.getProcesses().stream() + .filter(p -> p.getTasks().stream().allMatch(t -> t.getTaskType() == TaskTypes.OUTPUT_FETCHING)) + .filter(p -> { + List names = p.getProcessOutputs().stream() + .map(o -> o.getName()) + .collect(Collectors.toList()); + return new HashSet<>(names).equals(new HashSet<>(outputNames)); + }) + .sorted(Comparator.comparing(ProcessModel::getLastUpdateTime) + .reversed()) + .findFirst(); + + if (!mostRecentOutputFetchProcess.isPresent()) { + var msg = "No matching intermediate output fetching process found."; + logger.debug(msg); + throw new InvalidRequestException(msg); + } + + ProcessStatus result; + // Determine the most recent status for the most recent process + ProcessModel process = mostRecentOutputFetchProcess.get(); + if (process.getProcessStatusesSize() > 0) { + result = process.getProcessStatuses().get(process.getProcessStatusesSize() - 1); + } else { + // Process has no statuses so it must be created but not yet running + result = new ProcessStatus(ProcessState.CREATED); + } + + return result; + } catch (AuthorizationException | InvalidRequestException e) { + throw e; + } catch (Throwable e) { + String msg = "Error while processing request to get intermediate output process status for experiment: " + + airavataExperimentId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + // Access control methods + public List getAllAccessibleUsers( + String gatewayId, + String resourceId, + ResourcePermissionType permissionType, + BiFunction> userListFunction) { + HashSet accessibleUsers = new HashSet<>(); + if (permissionType.equals(ResourcePermissionType.WRITE)) { + userListFunction.apply(sharingRegistryService, ResourcePermissionType.WRITE).stream() + .forEach(u -> accessibleUsers.add(u.getUserId())); + userListFunction.apply(sharingRegistryService, ResourcePermissionType.OWNER).stream() + .forEach(u -> accessibleUsers.add(u.getUserId())); + } else if (permissionType.equals(ResourcePermissionType.READ)) { + userListFunction.apply(sharingRegistryService, ResourcePermissionType.READ).stream() + .forEach(u -> accessibleUsers.add(u.getUserId())); + userListFunction.apply(sharingRegistryService, ResourcePermissionType.OWNER).stream() + .forEach(u -> accessibleUsers.add(u.getUserId())); + } else if (permissionType.equals(ResourcePermissionType.OWNER)) { + userListFunction.apply(sharingRegistryService, ResourcePermissionType.OWNER).stream() + .forEach(u -> accessibleUsers.add(u.getUserId())); + } else if (permissionType.equals(ResourcePermissionType.MANAGE_SHARING)) { + userListFunction.apply(sharingRegistryService, ResourcePermissionType.MANAGE_SHARING).stream() + .forEach(u -> accessibleUsers.add(u.getUserId())); + userListFunction.apply(sharingRegistryService, ResourcePermissionType.OWNER).stream() + .forEach(u -> accessibleUsers.add(u.getUserId())); + } + return new ArrayList<>(accessibleUsers); + } + + public List getAllAccessibleGroups( + String gatewayId, + String resourceId, + ResourcePermissionType permissionType, + BiFunction> groupListFunction) { + HashSet accessibleGroups = new HashSet<>(); + if (permissionType.equals(ResourcePermissionType.WRITE)) { + groupListFunction.apply(sharingRegistryService, ResourcePermissionType.WRITE).stream() + .forEach(g -> accessibleGroups.add(g.getGroupId())); + } else if (permissionType.equals(ResourcePermissionType.READ)) { + groupListFunction.apply(sharingRegistryService, ResourcePermissionType.READ).stream() + .forEach(g -> accessibleGroups.add(g.getGroupId())); + } else if (permissionType.equals(ResourcePermissionType.MANAGE_SHARING)) { + groupListFunction.apply(sharingRegistryService, ResourcePermissionType.MANAGE_SHARING).stream() + .forEach(g -> accessibleGroups.add(g.getGroupId())); + } + return new ArrayList<>(accessibleGroups); + } + + /** + * Get all accessible users for a resource (includes shared and directly shared) + */ + public List getAllAccessibleUsers( + AuthzToken authzToken, String resourceId, ResourcePermissionType permissionType, boolean directlySharedOnly) + throws AiravataSystemException { + try { + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + BiFunction> userListFunction; + if (directlySharedOnly) { + userListFunction = (c, t) -> { + try { + return c.getListOfDirectlySharedUsers(gatewayId, resourceId, gatewayId + ":" + t.name()); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } else { + userListFunction = (c, t) -> { + try { + return c.getListOfSharedUsers(gatewayId, resourceId, gatewayId + ":" + t.name()); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } + return getAllAccessibleUsers(gatewayId, resourceId, permissionType, userListFunction); + } catch (Exception e) { + String msg = "Error occurred while getting all accessible users: " + resourceId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + /** + * Get all accessible groups for a resource (includes shared and directly + * shared) + */ + public List getAllAccessibleGroups( + AuthzToken authzToken, String resourceId, ResourcePermissionType permissionType, boolean directlySharedOnly) + throws AiravataSystemException { + try { + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + BiFunction> groupListFunction; + if (directlySharedOnly) { + groupListFunction = (c, t) -> { + try { + return c.getListOfDirectlySharedGroups(gatewayId, resourceId, gatewayId + ":" + t.name()); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } else { + groupListFunction = (c, t) -> { + try { + return c.getListOfSharedGroups(gatewayId, resourceId, gatewayId + ":" + t.name()); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; + } + return getAllAccessibleGroups(gatewayId, resourceId, permissionType, groupListFunction); + } catch (Exception e) { + String msg = "Error occurred while getting all accessible groups: " + resourceId + " " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + // Group resource profile management with sharing registry integration + public String createGroupResourceProfileWithSharing( + AuthzToken authzToken, GroupResourceProfile groupResourceProfile) + throws AuthorizationException, AiravataSystemException, SharingRegistryException, DuplicateEntryException, + InvalidRequestException, ApplicationSettingsException { + String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); + validateGroupResourceProfile(authzToken, groupResourceProfile); + String groupResourceProfileId = createGroupResourceProfile(groupResourceProfile); + if (ServerSettings.isEnableSharing()) { + try { + var entity = new Entity(); + entity.setEntityId(groupResourceProfileId); + entity.setDomainId(groupResourceProfile.getGatewayId()); + entity.setEntityTypeId(groupResourceProfile.getGatewayId() + ":" + "GROUP_RESOURCE_PROFILE"); + entity.setOwnerId(userName + "@" + groupResourceProfile.getGatewayId()); + entity.setName(groupResourceProfile.getGroupResourceProfileName()); + + sharingRegistryService.createEntity(entity); + shareEntityWithAdminGatewayGroups(entity); + } catch (SharingRegistryException + | DuplicateEntryException + | AiravataSystemException + | InvalidRequestException + | AuthorizationException + | ApplicationSettingsException ex) { + String msg = "Error while creating group resource profile: " + groupResourceProfileId + " " + + ex.getMessage() + ". Rolling back group resource profile creation."; + logger.error(msg, ex); + try { + removeGroupResourceProfile(groupResourceProfileId); + } catch (Throwable rollbackEx) { + String rollbackMsg = "Failed to rollback group resource profile creation: " + groupResourceProfileId + + " " + rollbackEx.getMessage(); + logger.error(rollbackMsg, rollbackEx); + } + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, ex); + } + } + return groupResourceProfileId; + } + + public void validateGroupResourceProfile(AuthzToken authzToken, GroupResourceProfile groupResourceProfile) + throws AuthorizationException, AiravataSystemException { + Set tokenIds = new HashSet<>(); + if (groupResourceProfile.getComputePreferences() != null) { + for (GroupComputeResourcePreference groupComputeResourcePreference : + groupResourceProfile.getComputePreferences()) { + if (groupComputeResourcePreference.getResourceSpecificCredentialStoreToken() != null) { + tokenIds.add(groupComputeResourcePreference.getResourceSpecificCredentialStoreToken()); + } + } + } + if (groupResourceProfile.getDefaultCredentialStoreToken() != null) { + tokenIds.add(groupResourceProfile.getDefaultCredentialStoreToken()); + } + for (String tokenId : tokenIds) { + if (!userHasAccess(authzToken, tokenId, ResourcePermissionType.READ)) { + String msg = "User does not have READ permission to credential token " + tokenId + "."; + throw new AuthorizationException(msg); + } + } + } + + // Launch experiment business logic + public void launchExperiment(AuthzToken authzToken, String gatewayId, String airavataExperimentId) + throws InvalidRequestException, AiravataSystemException, AuthorizationException, + ExperimentNotFoundException, ProjectNotFoundException { + try { + logger.info("Launching experiment {}", airavataExperimentId); + ExperimentModel experiment = getExperiment(airavataExperimentId); + + if (experiment == null) { + throw new ExperimentNotFoundException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + String username = authzToken.getClaimsMap().get(Constants.USER_NAME); + + // For backwards compatibility, if there is no groupResourceProfileId, look up + // one that is shared with the + // user + if (!experiment.getUserConfigurationData().isSetGroupResourceProfileId()) { + List groupResourceProfiles = getGroupResourceList(authzToken, gatewayId); + if (groupResourceProfiles != null && !groupResourceProfiles.isEmpty()) { + // Just pick the first one + final String groupResourceProfileId = + groupResourceProfiles.get(0).getGroupResourceProfileId(); + logger.warn( + "Experiment {} doesn't have groupResourceProfileId, picking first one user has access to: {}", + airavataExperimentId, + groupResourceProfileId); + experiment.getUserConfigurationData().setGroupResourceProfileId(groupResourceProfileId); + updateExperimentConfiguration(airavataExperimentId, experiment.getUserConfigurationData()); + } else { + String msg = "User " + username + " in gateway " + gatewayId + + " doesn't have access to any group resource profiles."; + logger.error(msg); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, null); + } + } + + // Validate access to group resource profile and application deployments + validateLaunchExperimentAccess(authzToken, gatewayId, experiment); + publishExperimentSubmitEvent(experimentPublisher, gatewayId, airavataExperimentId); + } catch (InvalidRequestException + | AiravataSystemException + | AuthorizationException + | ExperimentNotFoundException e) { + throw e; + } catch (Throwable e) { + String msg = "Error launching experiment: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + /** + * Get group resource list with sharing registry integration + */ + public List getGroupResourceList(AuthzToken authzToken, String gatewayId) + throws AiravataSystemException { + try { + String userName = authzToken.getClaimsMap().get(Constants.USER_NAME); + var accessibleGroupResProfileIds = new ArrayList(); + if (ServerSettings.isEnableSharing()) { + var filters = new ArrayList(); + SearchCriteria searchCriteria = new SearchCriteria(); + searchCriteria.setSearchField(EntitySearchField.ENTITY_TYPE_ID); + searchCriteria.setSearchCondition(SearchCondition.EQUAL); + searchCriteria.setValue(gatewayId + ":" + ResourceType.GROUP_RESOURCE_PROFILE.name()); + filters.add(searchCriteria); + sharingRegistryService + .searchEntities( + authzToken.getClaimsMap().get(Constants.GATEWAY_ID), + userName + "@" + gatewayId, + filters, + 0, + -1) + .stream() + .forEach(p -> accessibleGroupResProfileIds.add(p.getEntityId())); + } + return getGroupResourceList(gatewayId, accessibleGroupResProfileIds); + } catch (ApplicationSettingsException | SharingRegistryException e) { + String msg = "Error occurred while getting group resource list: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + // Sharing Registry Delegation Methods for ServerHandler + public boolean isDomainExists(String domainId) throws SharingRegistryException { + return sharingRegistryService.isDomainExists(domainId); + } + + public String createDomain(Domain domain) throws SharingRegistryException, DuplicateEntryException { + return sharingRegistryService.createDomain(domain); + } + + public String createUser(User user) throws SharingRegistryException, DuplicateEntryException { + return sharingRegistryService.createUser(user); + } + + public String createGroup(UserGroup group) throws SharingRegistryException, DuplicateEntryException { + return sharingRegistryService.createGroup(group); + } + + public boolean addUsersToGroup(String domainId, List userIds, String groupId) + throws SharingRegistryException { + return sharingRegistryService.addUsersToGroup(domainId, userIds, groupId); + } + + public String createEntityType(EntityType entityType) throws SharingRegistryException, DuplicateEntryException { + return sharingRegistryService.createEntityType(entityType); + } + + public String createPermissionType(PermissionType permissionType) + throws SharingRegistryException, DuplicateEntryException { + return sharingRegistryService.createPermissionType(permissionType); + } + + public boolean userHasAccess(String domainId, String userId, String entityId, String permissionTypeId) + throws SharingRegistryException { + return sharingRegistryService.userHasAccess(domainId, userId, entityId, permissionTypeId); + } + + public SharingEntity getEntity(String domainId, String entityId) throws SharingRegistryException { + return new SharingEntity(sharingRegistryService.getEntity(domainId, entityId)); + } + + public void updateEntity(SharingEntity entity) throws SharingRegistryException { + sharingRegistryService.updateEntity(entity.delegate()); + } + + public boolean shareEntityWithUsers( + String domainId, String entityId, List userList, String permissionTypeId, boolean cascade) + throws SharingRegistryException { + return sharingRegistryService.shareEntityWithUsers(domainId, entityId, userList, permissionTypeId, cascade); + } + + public SSHCredential getSSHCredential(String token, String gatewayId) throws AiravataSystemException { + try { + return credentialStoreService.getSSHCredential(token, gatewayId); + } catch (CredentialStoreException e) { + String msg = "Error while retrieving SSH credential: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void createEntity(SharingEntity entity) throws SharingRegistryException, DuplicateEntryException { + sharingRegistryService.createEntity(entity.delegate()); + } + + public List searchEntities( + String domainId, String userId, List filters, int offset, int limit) + throws SharingRegistryException { + return sharingRegistryService.searchEntities(domainId, userId, filters, offset, limit).stream() + .map(SharingEntity::new) + .collect(Collectors.toList()); + } + + public boolean shareEntityWithGroups( + String domainId, String entityId, List groupList, String permissionTypeId, boolean cascade) + throws SharingRegistryException { + return sharingRegistryService.shareEntityWithGroups(domainId, entityId, groupList, permissionTypeId, cascade); + } + + public boolean revokeEntitySharingFromUsers( + String domainId, String entityId, List userList, String permissionTypeId) + throws SharingRegistryException { + return sharingRegistryService.revokeEntitySharingFromUsers(domainId, entityId, userList, permissionTypeId); + } + + public boolean revokeEntitySharingFromGroups( + String domainId, String entityId, List groupList, String permissionTypeId) + throws SharingRegistryException { + return sharingRegistryService.revokeEntitySharingFromGroups(domainId, entityId, groupList, permissionTypeId); + } + + public boolean deleteEntity(String domainId, String entityId) throws SharingRegistryException { + return sharingRegistryService.deleteEntity(domainId, entityId); + } + + /** + * Resolves compute resource storage info context (login username, credential + * token, and adaptor). + * Handles user preference → group preference fallback for both login and + * credentials. + */ + private StorageInfoContext resolveComputeStorageInfoContext( + AuthzToken authzToken, String gatewayId, String userId, String resourceId) + throws InvalidRequestException, AiravataSystemException, ApplicationSettingsException, AgentException { + String loginUserName = null; + boolean loginFromUserPref = false; + GroupComputeResourcePreference groupComputePref = null; + GroupResourceProfile groupResourceProfile = null; + + UserComputeResourcePreference userComputePref = null; + if (safeIsUserResourceProfileExists(authzToken, userId, gatewayId)) { + userComputePref = getUserComputeResourcePreference(userId, gatewayId, resourceId); + } else { + logger.debug( + "User resource profile does not exist for user {} in gateway {}, will try group preferences", + userId, + gatewayId); + } + + if (userComputePref != null + && userComputePref.getLoginUserName() != null + && !userComputePref.getLoginUserName().trim().isEmpty()) { + loginUserName = userComputePref.getLoginUserName(); + loginFromUserPref = true; + logger.debug("Using user preference login username: {}", loginUserName); + + } else { + // Fallback to GroupComputeResourcePreference + var groupResourceProfiles = getGroupResourceList(authzToken, gatewayId); + for (GroupResourceProfile groupProfile : groupResourceProfiles) { + List groupComputePrefs = groupProfile.getComputePreferences(); + + if (groupComputePrefs != null && !groupComputePrefs.isEmpty()) { + for (GroupComputeResourcePreference groupPref : groupComputePrefs) { + if (resourceId.equals(groupPref.getComputeResourceId()) + && groupPref.getLoginUserName() != null + && !groupPref.getLoginUserName().trim().isEmpty()) { + loginUserName = groupPref.getLoginUserName(); + groupComputePref = groupPref; + groupResourceProfile = groupProfile; + logger.debug( + "Using login username from group compute resource preference for resource {}", + resourceId); + break; + } + } + } + if (loginUserName != null) { + break; + } + } + if (loginUserName == null) { + logger.debug("No login username found for compute resource {}", resourceId); + throw new InvalidRequestException("No login username found for compute resource " + resourceId); + } + } + + // Resolve credential token based on where login came from + String credentialToken; + if (loginFromUserPref) { + // Login username came from user preference. Use user preference token → user + // profile token + if (userComputePref != null + && userComputePref.getResourceSpecificCredentialStoreToken() != null + && !userComputePref + .getResourceSpecificCredentialStoreToken() + .trim() + .isEmpty()) { + credentialToken = userComputePref.getResourceSpecificCredentialStoreToken(); + } else { + UserResourceProfile userResourceProfile = getUserResourceProfile(userId, gatewayId); + if (userResourceProfile == null + || userResourceProfile.getCredentialStoreToken() == null + || userResourceProfile.getCredentialStoreToken().trim().isEmpty()) { + String msg = "No credential store token found for user " + userId + " in gateway " + gatewayId; + logger.error(msg); + throw airavataSystemException(AiravataErrorType.AUTHENTICATION_FAILURE, msg, null); + } + credentialToken = userResourceProfile.getCredentialStoreToken(); + } + } else { + // Login username came from group preference. Use group preference token → group + // profile default token → + // user profile token (fallback) + if (groupComputePref != null + && groupComputePref.getResourceSpecificCredentialStoreToken() != null + && !groupComputePref + .getResourceSpecificCredentialStoreToken() + .trim() + .isEmpty()) { + credentialToken = groupComputePref.getResourceSpecificCredentialStoreToken(); + + } else if (groupResourceProfile != null + && groupResourceProfile.getDefaultCredentialStoreToken() != null + && !groupResourceProfile + .getDefaultCredentialStoreToken() + .trim() + .isEmpty()) { + credentialToken = groupResourceProfile.getDefaultCredentialStoreToken(); + + } else { + UserResourceProfile userResourceProfile = getUserResourceProfile(userId, gatewayId); + if (userResourceProfile == null + || userResourceProfile.getCredentialStoreToken() == null + || userResourceProfile.getCredentialStoreToken().trim().isEmpty()) { + String msg = "No credential store token found for user " + userId + " in gateway " + gatewayId; + logger.error(msg); + throw airavataSystemException(AiravataErrorType.AUTHENTICATION_FAILURE, msg, null); + } + credentialToken = userResourceProfile.getCredentialStoreToken(); + } + } + + AgentAdaptor adaptor = AdaptorSupportImpl.getInstance() + .fetchComputeSSHAdaptor(gatewayId, resourceId, credentialToken, userId, loginUserName); + logger.info("Resolved resource {} as compute resource to fetch storage details", resourceId); + + return new StorageInfoContext(loginUserName, credentialToken, adaptor); + } + + /** + * Resolves storage resource storage info context (login username, credential + * token, and adaptor). + * Handles user preference → gateway preference fallback for both login and + * credentials. + */ + private StorageInfoContext resolveStorageStorageInfoContext( + AuthzToken authzToken, String gatewayId, String userId, String resourceId) + throws InvalidRequestException, AgentException, ApplicationSettingsException, AiravataSystemException, + AuthorizationException { + UserStoragePreference userStoragePref = null; + if (safeIsUserResourceProfileExists(authzToken, userId, gatewayId)) { + userStoragePref = getUserStoragePreference(userId, gatewayId, resourceId); + } else { + logger.debug( + "User resource profile does not exist for user {} in gateway {}, will try gateway preferences", + userId, + gatewayId); + } + + StoragePreference storagePref = null; + if (isGatewayResourceProfileExists(gatewayId)) { + storagePref = getGatewayStoragePreference(gatewayId, resourceId); + } else { + logger.debug( + "Gateway resource profile does not exist for gateway {}, will check if user preference exists", + gatewayId); + } + + String loginUserName; + boolean loginFromUserPref; + + if (userStoragePref != null + && userStoragePref.getLoginUserName() != null + && !userStoragePref.getLoginUserName().trim().isEmpty()) { + loginUserName = userStoragePref.getLoginUserName(); + loginFromUserPref = true; + logger.debug("Using login username from user storage preference for resource {}", resourceId); + + } else if (storagePref != null + && storagePref.getLoginUserName() != null + && !storagePref.getLoginUserName().trim().isEmpty()) { + loginUserName = storagePref.getLoginUserName(); + loginFromUserPref = false; + logger.debug("Using login username from gateway storage preference for resource {}", resourceId); + + } else { + logger.error("No login username found for storage resource {}", resourceId); + throw new InvalidRequestException("No login username found for storage resource " + resourceId); + } + + // Resolve credential token based on where login came from + String credentialToken; + if (loginFromUserPref) { + // Login came from user preference. Use user preference token or user profile + // token + if (userStoragePref != null + && userStoragePref.getResourceSpecificCredentialStoreToken() != null + && !userStoragePref + .getResourceSpecificCredentialStoreToken() + .trim() + .isEmpty()) { + credentialToken = userStoragePref.getResourceSpecificCredentialStoreToken(); + logger.debug("Using login username from user preference for resource {}", resourceId); + + } else { + UserResourceProfile userResourceProfile = getUserResourceProfile(userId, gatewayId); + if (userResourceProfile == null + || userResourceProfile.getCredentialStoreToken() == null + || userResourceProfile.getCredentialStoreToken().trim().isEmpty()) { + String msg = "No credential store token found for user " + userId + " in gateway " + gatewayId; + logger.error(msg); + throw airavataSystemException(AiravataErrorType.AUTHENTICATION_FAILURE, msg, null); + } + credentialToken = userResourceProfile.getCredentialStoreToken(); + } + } else { + // Login came from gateway preference. Use gateway preference token or gateway + // profile token + if (storagePref != null + && storagePref.getResourceSpecificCredentialStoreToken() != null + && !storagePref + .getResourceSpecificCredentialStoreToken() + .trim() + .isEmpty()) { + credentialToken = storagePref.getResourceSpecificCredentialStoreToken(); + + } else { + GatewayResourceProfile gatewayResourceProfile = getGatewayResourceProfile(gatewayId); + if (gatewayResourceProfile == null + || gatewayResourceProfile.getCredentialStoreToken() == null + || gatewayResourceProfile + .getCredentialStoreToken() + .trim() + .isEmpty()) { + String msg = "No credential store token found for gateway " + gatewayId; + logger.error(msg); + throw airavataSystemException(AiravataErrorType.AUTHENTICATION_FAILURE, msg, null); + } + credentialToken = gatewayResourceProfile.getCredentialStoreToken(); + } + } + + AgentAdaptor adaptor = AdaptorSupportImpl.getInstance() + .fetchStorageSSHAdaptor(gatewayId, resourceId, credentialToken, userId, loginUserName); + logger.info("Resolved resource {} as storage resource to fetch storage details", resourceId); + + return new StorageInfoContext(loginUserName, credentialToken, adaptor); + } + + public StorageVolumeInfo getResourceStorageInfo(AuthzToken authzToken, String resourceId, String location) + throws InvalidRequestException, AiravataSystemException, AuthorizationException { + try { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + StorageInfoContext context; + + Optional computeResourceOp = Optional.empty(); + try { + ComputeResourceDescription computeResource = getComputeResource(resourceId); + if (computeResource != null) { + computeResourceOp = Optional.of(computeResource); + } + } catch (Throwable e) { + logger.debug("Compute resource {} not found: {}", resourceId, e.getMessage()); + } + + Optional storageResourceOp = Optional.empty(); + if (computeResourceOp.isEmpty()) { + try { + StorageResourceDescription storageResource = getStorageResource(resourceId); + if (storageResource != null) { + storageResourceOp = Optional.of(storageResource); + } + } catch (Throwable e) { + logger.debug("Storage resource {} not found: {}", resourceId, e.getMessage()); + } + } + + if (computeResourceOp.isEmpty() && storageResourceOp.isEmpty()) { + logger.error( + "Resource with ID {} not found as either compute resource or storage resource", resourceId); + throw new InvalidRequestException("Resource with ID '" + resourceId + + "' not found as either compute resource or storage resource"); + } + + if (computeResourceOp.isPresent()) { + logger.debug("Found compute resource with ID {}. Resolving login username and credentials", resourceId); + context = resolveComputeStorageInfoContext(authzToken, gatewayId, userId, resourceId); + } else { + logger.debug("Found storage resource with ID {}. Resolving login username and credentials", resourceId); + context = resolveStorageStorageInfoContext(authzToken, gatewayId, userId, resourceId); + } + + return context.adaptor().getStorageVolumeInfo(location); + } catch (InvalidRequestException | AiravataSystemException | AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error occurred while getting resource storage info: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public StorageDirectoryInfo getStorageDirectoryInfo(AuthzToken authzToken, String resourceId, String location) + throws InvalidRequestException, AiravataSystemException, AuthorizationException { + try { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + StorageInfoContext context; + + Optional computeResourceOp = Optional.empty(); + try { + ComputeResourceDescription computeResource = getComputeResource(resourceId); + if (computeResource != null) { + computeResourceOp = Optional.of(computeResource); + } + } catch (Throwable e) { + logger.debug("Compute resource {} not found: {}", resourceId, e.getMessage()); + } + + Optional storageResourceOp = Optional.empty(); + if (computeResourceOp.isEmpty()) { + try { + StorageResourceDescription storageResource = getStorageResource(resourceId); + if (storageResource != null) { + storageResourceOp = Optional.of(storageResource); + } + } catch (Throwable e) { + logger.debug("Storage resource {} not found: {}", resourceId, e.getMessage()); + } + } + + if (computeResourceOp.isEmpty() && storageResourceOp.isEmpty()) { + logger.error( + "Resource with ID {} not found as either compute resource or storage resource", resourceId); + throw new InvalidRequestException("Resource with ID '" + resourceId + + "' not found as either compute resource or storage resource"); + } + + if (computeResourceOp.isPresent()) { + logger.debug("Found compute resource with ID {}. Resolving login username and credentials", resourceId); + context = resolveComputeStorageInfoContext(authzToken, gatewayId, userId, resourceId); + } else { + logger.debug("Found storage resource with ID {}. Resolving login username and credentials", resourceId); + context = resolveStorageStorageInfoContext(authzToken, gatewayId, userId, resourceId); + } + + return context.adaptor().getStorageDirectoryInfo(location); + } catch (InvalidRequestException | AiravataSystemException | AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error occurred while getting storage directory info: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean doesUserHaveSSHAccount(AuthzToken authzToken, String computeResourceId, String userId) + throws InvalidRequestException, AiravataSystemException, AuthorizationException { + try { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + logger.debug( + "Checking if user {} has SSH account on compute resource {} in gateway {}", + userId, + computeResourceId, + gatewayId); + return SSHAccountManager.doesUserHaveSSHAccount(gatewayId, computeResourceId, userId); + } catch (Throwable e) { + String msg = "Error occurred while checking if user has an SSH Account: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean isSSHAccountSetupComplete( + AuthzToken authzToken, String computeResourceId, String airavataCredStoreToken) + throws AiravataSystemException, AuthorizationException { + try { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + logger.debug( + "Checking if SSH account setup is complete for user {} on compute resource {} in gateway {}", + userId, + computeResourceId, + gatewayId); + + SSHCredential sshCredential = getSSHCredential(airavataCredStoreToken, gatewayId); + return SSHAccountManager.isSSHAccountSetupComplete(gatewayId, computeResourceId, userId, sshCredential); + } catch (Throwable e) { + String msg = "Error occurred while checking if setup of SSH account is complete: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public UserComputeResourcePreference setupSSHAccount( + AuthzToken authzToken, String computeResourceId, String userId, String airavataCredStoreToken) + throws InvalidRequestException, AiravataSystemException, AuthorizationException { + try { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + logger.debug( + "Setting up SSH account for user {} on compute resource {} in gateway {}", + userId, + computeResourceId, + gatewayId); + + SSHCredential sshCredential = getSSHCredential(airavataCredStoreToken, gatewayId); + return SSHAccountManager.setupSSHAccount(gatewayId, computeResourceId, userId, sshCredential); + } catch (AiravataSystemException e) { + throw e; + } catch (Throwable e) { + String msg = "Error occurred while automatically setting up SSH account for user: " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean shareResourceWithUsers( + AuthzToken authzToken, String resourceId, Map userPermissionList) + throws AuthorizationException, AiravataSystemException { + try { + if (!userHasAccess(authzToken, resourceId, ResourcePermissionType.OWNER) + && !userHasAccess(authzToken, resourceId, ResourcePermissionType.MANAGE_SHARING)) { + throw new AuthorizationException( + "User is not allowed to change sharing because the user is either not the resource owner or does not have access to share the resource"); + } + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + for (Map.Entry userPermission : userPermissionList.entrySet()) { + if (userPermission.getValue().equals(ResourcePermissionType.WRITE)) { + shareEntityWithUsers( + gatewayId, + resourceId, + Arrays.asList(userPermission.getKey()), + gatewayId + ":" + "WRITE", + true); + } else if (userPermission.getValue().equals(ResourcePermissionType.READ)) { + shareEntityWithUsers( + gatewayId, + resourceId, + Arrays.asList(userPermission.getKey()), + gatewayId + ":" + "READ", + true); + } else if (userPermission.getValue().equals(ResourcePermissionType.MANAGE_SHARING)) { + if (userHasAccess(authzToken, resourceId, ResourcePermissionType.OWNER)) { + createManageSharingPermissionTypeIfMissing(gatewayId); + shareEntityWithUsers( + gatewayId, + resourceId, + Arrays.asList(userPermission.getKey()), + gatewayId + ":" + "MANAGE_SHARING", + true); + } else { + throw new AuthorizationException( + "User is not allowed to grant sharing permission because the user is not the resource owner."); + } + } else { + logger.error( + "Invalid ResourcePermissionType : {}", + userPermission.getValue().toString()); + throw new AiravataSystemException(AiravataErrorType.UNSUPPORTED_OPERATION); + } + } + return true; + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error in sharing resource with users. Resource ID : " + resourceId + ": " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean shareResourceWithGroups( + AuthzToken authzToken, String resourceId, Map groupPermissionList) + throws AuthorizationException, AiravataSystemException { + try { + if (!userHasAccess(authzToken, resourceId, ResourcePermissionType.OWNER) + && !userHasAccess(authzToken, resourceId, ResourcePermissionType.MANAGE_SHARING)) { + throw new AuthorizationException( + "User is not allowed to change sharing because the user is either not the resource owner or does not have access to share the resource"); + } + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + for (Map.Entry groupPermission : groupPermissionList.entrySet()) { + if (groupPermission.getValue().equals(ResourcePermissionType.WRITE)) { + shareEntityWithGroups( + gatewayId, + resourceId, + Arrays.asList(groupPermission.getKey()), + gatewayId + ":" + "WRITE", + true); + } else if (groupPermission.getValue().equals(ResourcePermissionType.READ)) { + shareEntityWithGroups( + gatewayId, + resourceId, + Arrays.asList(groupPermission.getKey()), + gatewayId + ":" + "READ", + true); + } else if (groupPermission.getValue().equals(ResourcePermissionType.MANAGE_SHARING)) { + if (userHasAccess(authzToken, resourceId, ResourcePermissionType.OWNER)) { + createManageSharingPermissionTypeIfMissing(gatewayId); + shareEntityWithGroups( + gatewayId, + resourceId, + Arrays.asList(groupPermission.getKey()), + gatewayId + ":" + "MANAGE_SHARING", + true); + } else { + throw new AuthorizationException( + "User is not allowed to grant sharing permission because the user is not the resource owner."); + } + } else { + logger.error( + "Invalid ResourcePermissionType : {}", + groupPermission.getValue().toString()); + throw new AiravataSystemException(AiravataErrorType.UNSUPPORTED_OPERATION); + } + } + return true; + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + var msg = "Error in sharing resource with groups. Resource ID : " + resourceId + ". More info : " + + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean revokeSharingOfResourceFromUsers( + AuthzToken authzToken, String resourceId, Map userPermissionList) + throws AuthorizationException, AiravataSystemException, InvalidRequestException { + try { + if (!userHasAccess(authzToken, resourceId, ResourcePermissionType.OWNER) + && !userHasAccess(authzToken, resourceId, ResourcePermissionType.MANAGE_SHARING)) { + throw new AuthorizationException( + "User is not allowed to change sharing because the user is either not the resource owner or does not have access to share the resource"); + } + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + for (Map.Entry userPermission : userPermissionList.entrySet()) { + if (userPermission.getValue().equals(ResourcePermissionType.WRITE)) { + revokeEntitySharingFromUsers( + gatewayId, resourceId, Arrays.asList(userPermission.getKey()), gatewayId + ":" + "WRITE"); + } else if (userPermission.getValue().equals(ResourcePermissionType.READ)) { + revokeEntitySharingFromUsers( + gatewayId, resourceId, Arrays.asList(userPermission.getKey()), gatewayId + ":" + "READ"); + } else if (userPermission.getValue().equals(ResourcePermissionType.MANAGE_SHARING)) { + if (userHasAccess(authzToken, resourceId, ResourcePermissionType.OWNER)) { + createManageSharingPermissionTypeIfMissing(gatewayId); + revokeEntitySharingFromUsers( + gatewayId, + resourceId, + Arrays.asList(userPermission.getKey()), + gatewayId + ":" + "MANAGE_SHARING"); + } else { + throw new AuthorizationException( + "User is not allowed to change sharing permission because the user is not the resource owner."); + } + } else { + logger.error( + "Invalid ResourcePermissionType : {}", + userPermission.getValue().toString()); + throw new AiravataSystemException(AiravataErrorType.UNSUPPORTED_OPERATION); + } + } + return true; + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + var msg = "Error in revoking access to resource from users. Resource ID : " + resourceId; + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean revokeSharingOfResourceFromGroups( + AuthzToken authzToken, String resourceId, Map groupPermissionList) + throws AuthorizationException, InvalidRequestException, AiravataSystemException { + try { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + if (!userHasAccess(authzToken, resourceId, ResourcePermissionType.OWNER) + && !userHasAccess(authzToken, resourceId, ResourcePermissionType.MANAGE_SHARING)) { + throw new AuthorizationException( + "User is not allowed to change sharing because the user is either not the resource owner or does not have access to share the resource"); + } + // For certain resource types, restrict them from being unshared with admin + // groups + ResourceType resourceType = getResourceType(gatewayId, resourceId); + Set adminRestrictedResourceTypes = new HashSet<>(Arrays.asList( + ResourceType.EXPERIMENT, ResourceType.APPLICATION_DEPLOYMENT, ResourceType.GROUP_RESOURCE_PROFILE)); + if (adminRestrictedResourceTypes.contains(resourceType)) { + // Prevent removing Admins WRITE/MANAGE_SHARING access and Read Only Admins READ + // access + GatewayGroups gatewayGroups = retrieveGatewayGroups(gatewayId); + if (groupPermissionList.containsKey(gatewayGroups.getAdminsGroupId()) + && groupPermissionList + .get(gatewayGroups.getAdminsGroupId()) + .equals(ResourcePermissionType.WRITE)) { + throw new InvalidRequestException("Not allowed to remove Admins group's WRITE access."); + } + if (groupPermissionList.containsKey(gatewayGroups.getReadOnlyAdminsGroupId()) + && groupPermissionList + .get(gatewayGroups.getReadOnlyAdminsGroupId()) + .equals(ResourcePermissionType.READ)) { + throw new InvalidRequestException("Not allowed to remove Read Only Admins group's READ access."); + } + if (groupPermissionList.containsKey(gatewayGroups.getAdminsGroupId()) + && groupPermissionList + .get(gatewayGroups.getAdminsGroupId()) + .equals(ResourcePermissionType.READ)) { + throw new InvalidRequestException("Not allowed to remove Admins group's READ access."); + } + if (groupPermissionList.containsKey(gatewayGroups.getAdminsGroupId()) + && groupPermissionList + .get(gatewayGroups.getAdminsGroupId()) + .equals(ResourcePermissionType.MANAGE_SHARING)) { + throw new InvalidRequestException("Not allowed to remove Admins group's MANAGE_SHARING access."); + } + } + for (Map.Entry groupPermission : groupPermissionList.entrySet()) { + if (groupPermission.getValue().equals(ResourcePermissionType.WRITE)) { + revokeEntitySharingFromGroups( + gatewayId, resourceId, Arrays.asList(groupPermission.getKey()), gatewayId + ":" + "WRITE"); + } else if (groupPermission.getValue().equals(ResourcePermissionType.READ)) { + revokeEntitySharingFromGroups( + gatewayId, resourceId, Arrays.asList(groupPermission.getKey()), gatewayId + ":" + "READ"); + } else if (groupPermission.getValue().equals(ResourcePermissionType.MANAGE_SHARING)) { + if (userHasAccess(authzToken, resourceId, ResourcePermissionType.OWNER)) { + createManageSharingPermissionTypeIfMissing(gatewayId); + revokeEntitySharingFromGroups( + gatewayId, + resourceId, + Arrays.asList(groupPermission.getKey()), + gatewayId + ":" + "MANAGE_SHARING"); + } else { + throw new AuthorizationException( + "User is not allowed to change sharing because the user is not the resource owner"); + } + } else { + logger.error( + "Invalid ResourcePermissionType : {}", + groupPermission.getValue().toString()); + throw new AiravataSystemException(AiravataErrorType.UNSUPPORTED_OPERATION); + } + } + return true; + } catch (AuthorizationException | InvalidRequestException e) { + throw e; + } catch (Throwable e) { + String msg = "Error in revoking access to resource from groups. Resource ID : " + resourceId + + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public GroupResourceProfile getGroupResourceProfile(AuthzToken authzToken, String groupResourceProfileId) + throws AuthorizationException, AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess(gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":READ")) { + throw new AuthorizationException("User does not have permission to access group resource profile"); + } + } + return getGroupResourceProfile(groupResourceProfileId); + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error retrieving group resource profile. groupResourceProfileId: " + groupResourceProfileId + + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean removeGroupResourceProfile(AuthzToken authzToken, String groupResourceProfileId) + throws AuthorizationException, AiravataSystemException { + try { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + if (ServerSettings.isEnableSharing()) { + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess(gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":WRITE")) { + throw new AuthorizationException("User does not have permission to remove group resource profile"); + } + } + boolean result = removeGroupResourceProfile(groupResourceProfileId); + if (result) { + deleteEntity(gatewayId, groupResourceProfileId); + } + return result; + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + var msg = "Error removing group resource profile. groupResourceProfileId: " + groupResourceProfileId; + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean removeGroupComputePrefs( + AuthzToken authzToken, String computeResourceId, String groupResourceProfileId) + throws AuthorizationException, AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess(gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":WRITE")) { + throw new AuthorizationException( + "User does not have permission to remove group compute preferences"); + } + } + return removeGroupComputePrefs(computeResourceId, groupResourceProfileId); + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + var msg = "Error removing group compute preferences. GroupResourceProfileId: " + groupResourceProfileId + + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean removeGroupComputeResourcePolicy(AuthzToken authzToken, String resourcePolicyId) + throws AuthorizationException, AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + ComputeResourcePolicy computeResourcePolicy = getGroupComputeResourcePolicy(resourcePolicyId); + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess( + gatewayId, + userId + "@" + gatewayId, + computeResourcePolicy.getGroupResourceProfileId(), + gatewayId + ":WRITE")) { + throw new AuthorizationException( + "User does not have permission to remove group compute resource policy"); + } + } + return removeGroupComputeResourcePolicy(resourcePolicyId); + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error removing group compute resource policy. ResourcePolicyId: " + resourcePolicyId + + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public boolean removeGroupBatchQueueResourcePolicy(AuthzToken authzToken, String resourcePolicyId) + throws AuthorizationException, AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + BatchQueueResourcePolicy batchQueueResourcePolicy = getBatchQueueResourcePolicy(resourcePolicyId); + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess( + gatewayId, + userId + "@" + gatewayId, + batchQueueResourcePolicy.getGroupResourceProfileId(), + gatewayId + ":WRITE")) { + throw new AuthorizationException( + "User does not have permission to remove batch queue resource policy"); + } + } + return removeGroupBatchQueueResourcePolicy(resourcePolicyId); + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error removing batch queue resource policy. ResourcePolicyId: " + resourcePolicyId + + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public GroupComputeResourcePreference getGroupComputeResourcePreference( + AuthzToken authzToken, String computeResourceId, String groupResourceProfileId) + throws AuthorizationException, AiravataSystemException, InvalidRequestException { + try { + if (ServerSettings.isEnableSharing()) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess(gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":READ")) { + throw new AuthorizationException("User does not have permission to access group resource profile"); + } + } + return getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId); + } catch (AuthorizationException | AiravataSystemException e) { + throw e; + } catch (Throwable e) { + String msg = "Error retrieving Group compute preference. GroupResourceProfileId: " + groupResourceProfileId + + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public ComputeResourcePolicy getGroupComputeResourcePolicy(AuthzToken authzToken, String resourcePolicyId) + throws AuthorizationException, AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + ComputeResourcePolicy computeResourcePolicy = getGroupComputeResourcePolicy(resourcePolicyId); + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess( + gatewayId, + userId + "@" + gatewayId, + computeResourcePolicy.getGroupResourceProfileId(), + gatewayId + ":READ")) { + throw new AuthorizationException("User does not have permission to access group resource profile"); + } + } + return getGroupComputeResourcePolicy(resourcePolicyId); + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error retrieving Group compute resource policy. ResourcePolicyId: " + resourcePolicyId + + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public BatchQueueResourcePolicy getBatchQueueResourcePolicy(AuthzToken authzToken, String resourcePolicyId) + throws AuthorizationException, AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + BatchQueueResourcePolicy batchQueueResourcePolicy = getBatchQueueResourcePolicy(resourcePolicyId); + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess( + gatewayId, + userId + "@" + gatewayId, + batchQueueResourcePolicy.getGroupResourceProfileId(), + gatewayId + ":READ")) { + throw new AuthorizationException("User does not have permission to access group resource profile"); + } + } + return getBatchQueueResourcePolicy(resourcePolicyId); + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error retrieving batch queue resource policy. ResourcePolicyId: " + resourcePolicyId + + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public void updateGroupResourceProfile(AuthzToken authzToken, GroupResourceProfile groupResourceProfile) + throws AuthorizationException, AiravataSystemException { + try { + validateGroupResourceProfile(authzToken, groupResourceProfile); + if (!userHasAccess( + authzToken, groupResourceProfile.getGroupResourceProfileId(), ResourcePermissionType.WRITE)) { + throw new AuthorizationException("User does not have permission to update group resource profile"); + } + updateGroupResourceProfile(groupResourceProfile); + } catch (AuthorizationException e) { + var userName = authzToken.getClaimsMap().get(Constants.USER_NAME); + logger.info("User " + userName + " not allowed access to update GroupResourceProfile " + + groupResourceProfile.getGroupResourceProfileId() + ", reason: " + e.getMessage()); + throw e; + } catch (Throwable e) { + String msg = "Error updating group resource profile. groupResourceProfileId: " + + groupResourceProfile.getGroupResourceProfileId() + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getGroupComputeResourcePrefList( + AuthzToken authzToken, String groupResourceProfileId) + throws AuthorizationException, AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess(gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":READ")) { + throw new AuthorizationException("User does not have permission to access group resource profile"); + } + } + return getGroupComputeResourcePrefList(groupResourceProfileId); + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error retrieving Group compute resource preference. GroupResourceProfileId: " + + groupResourceProfileId + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getGroupBatchQueueResourcePolicyList( + AuthzToken authzToken, String groupResourceProfileId) + throws AuthorizationException, AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess(gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":READ")) { + throw new AuthorizationException("User does not have permission to access group resource profile"); + } + } + return getGroupBatchQueueResourcePolicyList(groupResourceProfileId); + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error retrieving Group batch queue resource policy list. GroupResourceProfileId: " + + groupResourceProfileId + ". More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public List getGroupComputeResourcePolicyList( + AuthzToken authzToken, String groupResourceProfileId) + throws AuthorizationException, AiravataSystemException { + try { + if (ServerSettings.isEnableSharing()) { + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + var userId = authzToken.getClaimsMap().get(Constants.USER_NAME); + if (!userHasAccess(gatewayId, userId + "@" + gatewayId, groupResourceProfileId, gatewayId + ":READ")) { + throw new AuthorizationException("User does not have permission to access group resource profile"); + } + } + return getGroupComputeResourcePolicyList(groupResourceProfileId); + } catch (AuthorizationException e) { + throw e; + } catch (Throwable e) { + String msg = "Error retrieving Group compute resource policy list. GroupResourceProfileId: " + + groupResourceProfileId + ". More info : " + e.getMessage(); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } + + public String createGroupResourceProfile(AuthzToken authzToken, GroupResourceProfile groupResourceProfile) + throws AuthorizationException, AiravataSystemException, InvalidRequestException { + try { + var result = createGroupResourceProfileWithSharing(authzToken, groupResourceProfile); + return result; + } catch (AuthorizationException | AiravataSystemException | InvalidRequestException e) { + throw e; + } catch (Throwable e) { + String msg = "Error creating group resource profile. More info : " + e.getMessage(); + logger.error(msg, e); + throw airavataSystemException(AiravataErrorType.INTERNAL_ERROR, msg, e); + } + } +} diff --git a/airavata-api/src/main/java/org/apache/airavata/service/CredentialStoreService.java b/airavata-api/src/main/java/org/apache/airavata/service/CredentialStoreService.java new file mode 100644 index 0000000000..f15f649238 --- /dev/null +++ b/airavata-api/src/main/java/org/apache/airavata/service/CredentialStoreService.java @@ -0,0 +1,557 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.airavata.service; + +import java.io.ByteArrayInputStream; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.*; +import java.util.stream.Collectors; +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.DBInitializer; +import org.apache.airavata.common.utils.DBUtil; +import org.apache.airavata.common.utils.ServerSettings; +import org.apache.airavata.credential.store.credential.CommunityUser; +import org.apache.airavata.credential.store.credential.Credential; +import org.apache.airavata.credential.store.credential.CredentialOwnerType; +import org.apache.airavata.credential.store.exception.CredentialStoreException; +import org.apache.airavata.credential.store.store.impl.CertificateCredentialWriter; +import org.apache.airavata.credential.store.store.impl.CredentialReaderImpl; +import org.apache.airavata.credential.store.store.impl.SSHCredentialWriter; +import org.apache.airavata.credential.store.store.impl.util.CredentialStoreDBInitConfig; +import org.apache.airavata.credential.store.util.TokenGenerator; +import org.apache.airavata.credential.store.util.Utility; +import org.apache.airavata.model.credential.store.*; +import org.apache.commons.codec.binary.Base64; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CredentialStoreService { + private static final Logger logger = LoggerFactory.getLogger(CredentialStoreService.class); + + private DBUtil dbUtil; + private SSHCredentialWriter sshCredentialWriter; + private CertificateCredentialWriter certificateCredentialWriter; + private CredentialReaderImpl credentialReader; + + public CredentialStoreService() + throws ApplicationSettingsException, IllegalAccessException, ClassNotFoundException, + InstantiationException { + String jdbcUrl = ServerSettings.getCredentialStoreDBURL(); + String userName = ServerSettings.getCredentialStoreDBUser(); + String password = ServerSettings.getCredentialStoreDBPassword(); + String driverName = ServerSettings.getCredentialStoreDBDriver(); + + logger.debug("Starting credential store, connecting to database - " + jdbcUrl + " DB user - " + userName + + " driver name - " + driverName); + DBInitializer.initializeDB(new CredentialStoreDBInitConfig()); + + dbUtil = new DBUtil(jdbcUrl, userName, password, driverName); + sshCredentialWriter = new SSHCredentialWriter(dbUtil); + certificateCredentialWriter = new CertificateCredentialWriter(dbUtil); + credentialReader = new CredentialReaderImpl(dbUtil); + } + + public String addSSHCredential(SSHCredential sshCredential) throws CredentialStoreException { + try { + org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential credential = + new org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential(); + credential.setGateway(sshCredential.getGatewayId()); + credential.setPortalUserName(sshCredential.getUsername()); + // only username and gateway id will be sent by client. + String token = TokenGenerator.generateToken(sshCredential.getGatewayId(), null); + credential.setToken(token); + credential.setPassphrase(String.valueOf(UUID.randomUUID())); + if (sshCredential.getPrivateKey() != null) { + credential.setPrivateKey(sshCredential.getPrivateKey().getBytes()); + } + if (sshCredential.getDescription() != null) { + credential.setDescription(sshCredential.getDescription()); + } + if (sshCredential.getPublicKey() != null) { + credential.setPublicKey(sshCredential.getPublicKey().getBytes()); + } + if (sshCredential.getPublicKey() == null || sshCredential.getPrivateKey() == null) { + credential = Utility.generateKeyPair(credential); + } + credential.setCredentialOwnerType(CredentialOwnerType.GATEWAY); + sshCredentialWriter.writeCredentials(credential); + return token; + } catch (Throwable e) { + logger.error("Error occurred while saving SSH Credentials.", e); + CredentialStoreException exception = new CredentialStoreException( + "Error occurred while saving SSH Credentials.. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addCertificateCredential(CertificateCredential certificateCredential) + throws CredentialStoreException { + try { + org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential credential = + new org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential(); + credential.setPortalUserName( + certificateCredential.getCommunityUser().getUsername()); + credential.setCommunityUser(new CommunityUser( + certificateCredential.getCommunityUser().getGatewayName(), + certificateCredential.getCommunityUser().getUsername(), + certificateCredential.getCommunityUser().getUserEmail())); + String token = TokenGenerator.generateToken( + certificateCredential.getCommunityUser().getGatewayName(), null); + credential.setToken(token); + Base64 encoder = new Base64(64); + byte[] decoded = encoder.decode(certificateCredential + .getX509Cert() + .replaceAll("-----BEGIN CERTIFICATE-----", "") + .replaceAll("-----END CERTIFICATE-----", "")); + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + X509Certificate certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(decoded)); + X509Certificate[] certificates = new X509Certificate[1]; + certificates[0] = certificate; + credential.setCertificates(certificates); + certificateCredentialWriter.writeCredentials(credential); + return token; + } catch (Throwable e) { + logger.error("Error occurred while saving Certificate Credentials.", e); + CredentialStoreException exception = new CredentialStoreException( + "Error occurred while saving Certificate Credentials.. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addPasswordCredential(PasswordCredential passwordCredential) throws CredentialStoreException { + try { + org.apache.airavata.credential.store.credential.impl.password.PasswordCredential credential = + new org.apache.airavata.credential.store.credential.impl.password.PasswordCredential(); + credential.setGateway(passwordCredential.getGatewayId()); + credential.setPortalUserName(passwordCredential.getPortalUserName()); + credential.setUserName(passwordCredential.getLoginUserName()); + credential.setPassword(passwordCredential.getPassword()); + credential.setDescription(passwordCredential.getDescription()); + String token = TokenGenerator.generateToken(passwordCredential.getGatewayId(), null); + credential.setToken(token); + sshCredentialWriter.writeCredentials(credential); + return token; + } catch (Throwable e) { + logger.error("Error occurred while saving PWD Credentials.", e); + CredentialStoreException exception = new CredentialStoreException( + "Error occurred while saving PWD Credentials.. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public SSHCredential getSSHCredential(String tokenId, String gatewayId) throws CredentialStoreException { + try { + Credential credential = credentialReader.getCredential(gatewayId, tokenId); + if (credential instanceof org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential + && !(credential + instanceof + org.apache.airavata.credential.store.credential.impl.password.PasswordCredential)) { + org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential credential1 = + (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) credential; + SSHCredential sshCredential = new SSHCredential(); + sshCredential.setUsername(credential1.getPortalUserName()); + sshCredential.setGatewayId(credential1.getGateway()); + sshCredential.setPublicKey(new String(credential1.getPublicKey())); + sshCredential.setPrivateKey(new String(credential1.getPrivateKey())); + sshCredential.setPassphrase(credential1.getPassphrase()); + sshCredential.setToken(credential1.getToken()); + sshCredential.setPersistedTime( + credential1.getCertificateRequestedTime().getTime()); + sshCredential.setDescription(credential1.getDescription()); + return sshCredential; + } else { + logger.info("Could not find SSH credentials for token - " + tokenId + " and " + "gateway id - " + + gatewayId); + return null; + } + } catch (Throwable e) { + String msg = "Error occurred while retrieving SSH credential for token - " + tokenId + " and gateway id - " + + gatewayId; + logger.error(msg, e); + CredentialStoreException exception = new CredentialStoreException(msg); + exception.initCause(e); + throw exception; + } + } + + public CredentialSummary getCredentialSummary(String tokenId, String gatewayId) throws CredentialStoreException { + try { + Credential credential = credentialReader.getCredential(gatewayId, tokenId); + if (isSSHCredential(credential)) { + return convertToCredentialSummary( + (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) credential); + } else if (isCertificateCredential(credential)) { + return convertToCredentialSummary( + (org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential) + credential); + } else if (isPasswordCredential(credential)) { + return convertToCredentialSummary( + (org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) credential); + } + String msg = "Unrecognized type of credential for token: " + tokenId; + logger.error(msg, new RuntimeException(msg)); + CredentialStoreException exception = new CredentialStoreException(msg); + exception.initCause(new RuntimeException(msg)); + throw exception; + } catch (CredentialStoreException e) { + throw e; + } catch (Throwable e) { + final String msg = "Error occurred while retrieving credential summary for token - " + tokenId + + " and gateway id - " + gatewayId; + logger.error(msg, e); + CredentialStoreException exception = new CredentialStoreException(msg + ". More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllCredentialSummaries( + SummaryType type, List accessibleTokenIds, String gatewayId) throws CredentialStoreException { + try { + List credentials = + credentialReader.getAllAccessibleCredentialsPerGateway(gatewayId, accessibleTokenIds); + if (type.equals(SummaryType.SSH)) { + return credentials.stream() + .filter(this::isSSHCredential) + .map(cred -> (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) cred) + .map(cred -> convertToCredentialSummary(cred)) + .collect(Collectors.toList()); + } else if (type.equals(SummaryType.CERT)) { + return credentials.stream() + .filter(this::isCertificateCredential) + .map(cred -> + (org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential) + cred) + .map(cred -> convertToCredentialSummary(cred)) + .collect(Collectors.toList()); + } else if (type.equals(SummaryType.PASSWD)) { + return credentials.stream() + .filter(this::isPasswordCredential) + .map(cred -> + (org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) cred) + .map(cred -> convertToCredentialSummary(cred)) + .collect(Collectors.toList()); + } else { + String msg = "Summary Type " + type + " is not supported."; + logger.error(msg, new RuntimeException(msg)); + CredentialStoreException exception = new CredentialStoreException(msg); + exception.initCause(new RuntimeException(msg)); + throw exception; + } + } catch (CredentialStoreException e) { + throw e; + } catch (Throwable e) { + final String msg = "Error occurred while retrieving " + type + " credential Summary for tokens - " + + accessibleTokenIds + " and gateway id - " + gatewayId; + logger.error(msg, e); + CredentialStoreException exception = new CredentialStoreException(msg + ". More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private boolean isSSHCredential(Credential cred) { + return cred instanceof org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential + && !(cred instanceof org.apache.airavata.credential.store.credential.impl.password.PasswordCredential); + } + + private boolean isCertificateCredential(Credential cred) { + return cred instanceof org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential; + } + + private boolean isPasswordCredential(Credential cred) { + return cred instanceof org.apache.airavata.credential.store.credential.impl.password.PasswordCredential; + } + + private CredentialSummary convertToCredentialSummary( + org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential cred) { + CredentialSummary credentialSummary = new CredentialSummary(); + credentialSummary.setType(SummaryType.SSH); + credentialSummary.setUsername(cred.getPortalUserName()); + credentialSummary.setGatewayId(cred.getGateway()); + credentialSummary.setPublicKey(new String(cred.getPublicKey())); + credentialSummary.setToken(cred.getToken()); + credentialSummary.setPersistedTime(cred.getCertificateRequestedTime().getTime()); + credentialSummary.setDescription(cred.getDescription()); + return credentialSummary; + } + + private CredentialSummary convertToCredentialSummary( + org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential cred) { + CredentialSummary credentialSummary = new CredentialSummary(); + credentialSummary.setType(SummaryType.CERT); + credentialSummary.setUsername(cred.getPortalUserName()); + // FIXME: need to get gatewayId for CertificateCredentials + credentialSummary.setGatewayId(""); + // FIXME: get the public key? Or what would be appropriate for a summary of a CertificateCredential? + // credentialSummary.setPublicKey(new String(cred.getPublicKey())); + credentialSummary.setToken(cred.getToken()); + credentialSummary.setPersistedTime(cred.getCertificateRequestedTime().getTime()); + credentialSummary.setDescription(cred.getDescription()); + return credentialSummary; + } + + private CredentialSummary convertToCredentialSummary( + org.apache.airavata.credential.store.credential.impl.password.PasswordCredential cred) { + CredentialSummary credentialSummary = new CredentialSummary(); + credentialSummary.setType(SummaryType.PASSWD); + credentialSummary.setUsername(cred.getPortalUserName()); + credentialSummary.setGatewayId(cred.getGateway()); + credentialSummary.setToken(cred.getToken()); + credentialSummary.setPersistedTime(cred.getCertificateRequestedTime().getTime()); + credentialSummary.setDescription(cred.getDescription()); + return credentialSummary; + } + + public CertificateCredential getCertificateCredential(String tokenId, String gatewayId) + throws CredentialStoreException { + try { + Credential credential = credentialReader.getCredential(gatewayId, tokenId); + if (credential + instanceof org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential) { + org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential credential1 = + (org.apache.airavata.credential.store.credential.impl.certificate.CertificateCredential) + credential; + CertificateCredential certificateCredential = new CertificateCredential(); + org.apache.airavata.model.credential.store.CommunityUser communityUser = + new org.apache.airavata.model.credential.store.CommunityUser(); + communityUser.setGatewayName(credential1.getCommunityUser().getGatewayName()); + communityUser.setUsername(credential1.getCommunityUser().getUserName()); + communityUser.setUserEmail(credential1.getCommunityUser().getUserEmail()); + certificateCredential.setCommunityUser(communityUser); + certificateCredential.setToken(credential1.getToken()); + certificateCredential.setLifeTime(credential1.getLifeTime()); + certificateCredential.setNotAfter(credential1.getNotAfter()); + certificateCredential.setNotBefore(credential1.getNotBefore()); + certificateCredential.setPersistedTime( + credential1.getCertificateRequestedTime().getTime()); + if (credential1.getPrivateKey() != null) { + certificateCredential.setPrivateKey( + credential1.getPrivateKey().toString()); + } + certificateCredential.setX509Cert(credential1.getCertificates()[0].toString()); + return certificateCredential; + } else { + logger.info("Could not find Certificate credentials for token - " + tokenId + " and " + "gateway id - " + + gatewayId); + return null; + } + } catch (Throwable e) { + String msg = "Error occurred while retrieving Certificate credential for token - " + tokenId + + " and gateway id - " + gatewayId; + logger.error(msg, e); + CredentialStoreException exception = new CredentialStoreException(msg); + exception.initCause(e); + throw exception; + } + } + + public PasswordCredential getPasswordCredential(String tokenId, String gatewayId) throws CredentialStoreException { + try { + Credential credential = credentialReader.getCredential(gatewayId, tokenId); + if (credential + instanceof org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) { + org.apache.airavata.credential.store.credential.impl.password.PasswordCredential credential1 = + (org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) credential; + PasswordCredential pwdCredential = new PasswordCredential(); + pwdCredential.setGatewayId(credential1.getGateway()); + pwdCredential.setPortalUserName(credential1.getPortalUserName()); + pwdCredential.setLoginUserName(credential1.getUserName()); + pwdCredential.setPassword(credential1.getPassword()); + pwdCredential.setDescription(credential1.getDescription()); + pwdCredential.setToken(credential1.getToken()); + pwdCredential.setPersistedTime( + credential1.getCertificateRequestedTime().getTime()); + return pwdCredential; + } else { + logger.info("Could not find PWD credentials for token - " + tokenId + " and " + "gateway id - " + + gatewayId); + return null; + } + } catch (Throwable e) { + String msg = "Error occurred while retrieving PWD credential for token - " + tokenId + " and gateway id - " + + gatewayId; + logger.error(msg, e); + CredentialStoreException exception = new CredentialStoreException(msg); + exception.initCause(e); + throw exception; + } + } + + @Deprecated + public List getAllCredentialSummaryForGateway(SummaryType type, String gatewayId) + throws CredentialStoreException { + if (type.equals(SummaryType.SSH)) { + Map sshKeyMap = new HashMap<>(); + List summaryList = new ArrayList<>(); + try { + List allCredentials = credentialReader.getAllCredentialsPerGateway(gatewayId); + if (allCredentials != null && !allCredentials.isEmpty()) { + for (Credential credential : allCredentials) { + if (credential instanceof org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential + && !(credential + instanceof + org.apache.airavata.credential.store.credential.impl.password + .PasswordCredential) + && credential.getCredentialOwnerType() == CredentialOwnerType.GATEWAY) { + org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential sshCredential = + (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) credential; + CredentialSummary sshCredentialSummary = new CredentialSummary(); + sshCredentialSummary.setType(SummaryType.SSH); + sshCredentialSummary.setToken(sshCredential.getToken()); + sshCredentialSummary.setUsername(sshCredential.getPortalUserName()); + sshCredentialSummary.setGatewayId(sshCredential.getGateway()); + sshCredentialSummary.setDescription(sshCredential.getDescription()); + sshCredentialSummary.setPublicKey(new String(sshCredential.getPublicKey())); + summaryList.add(sshCredentialSummary); + } + } + } + } catch (Throwable e) { + logger.error("Error occurred while retrieving credential Summary", e); + CredentialStoreException exception = new CredentialStoreException( + "Error occurred while retrieving credential Summary. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + return summaryList; + } else { + logger.info("Summay Type" + type.toString() + " not supported for gateway id - " + gatewayId); + return null; + } + } + + @Deprecated + public List getAllCredentialSummaryForUserInGateway( + SummaryType type, String gatewayId, String userId) throws CredentialStoreException { + if (type.equals(SummaryType.SSH)) { + Map sshKeyMap = new HashMap<>(); + List summaryList = new ArrayList<>(); + try { + List allCredentials = credentialReader.getAllCredentials(); + if (allCredentials != null && !allCredentials.isEmpty()) { + for (Credential credential : allCredentials) { + if (credential instanceof org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential + && !(credential + instanceof + org.apache.airavata.credential.store.credential.impl.password + .PasswordCredential)) { + org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential sshCredential = + (org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential) credential; + String portalUserName = sshCredential.getPortalUserName(); + String gateway = sshCredential.getGateway(); + if (portalUserName != null && gateway != null) { + if (portalUserName.equals(userId) + && gateway.equals(gatewayId) + && sshCredential.getCredentialOwnerType() == CredentialOwnerType.USER) { + org.apache.airavata.credential.store.credential.impl.ssh.SSHCredential + sshCredentialKey = + (org.apache.airavata.credential.store.credential.impl.ssh + .SSHCredential) + credential; + CredentialSummary sshCredentialSummary = new CredentialSummary(); + sshCredentialSummary.setType(SummaryType.SSH); + sshCredentialSummary.setToken(sshCredentialKey.getToken()); + sshCredentialSummary.setUsername(sshCredentialKey.getPortalUserName()); + sshCredentialSummary.setGatewayId(sshCredentialKey.getGateway()); + sshCredentialSummary.setDescription(sshCredentialKey.getDescription()); + sshCredentialSummary.setPublicKey(new String(sshCredentialKey.getPublicKey())); + summaryList.add(sshCredentialSummary); + } + } + } + } + } + } catch (Throwable e) { + logger.error("Error occurred while retrieving credential Summary", e); + CredentialStoreException exception = new CredentialStoreException( + "Error occurred while retrieving credential Summary. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + return summaryList; + } else { + logger.info("Summay Type" + type.toString() + " not supported for user Id - " + userId + " and " + + "gateway id - " + gatewayId); + return null; + } + } + + @Deprecated + public Map getAllPWDCredentialsForGateway(String gatewayId) throws CredentialStoreException { + Map pwdCredMap = new HashMap<>(); + try { + List allCredentials = credentialReader.getAllCredentialsPerGateway(gatewayId); + if (allCredentials != null && !allCredentials.isEmpty()) { + for (Credential credential : allCredentials) { + if (credential + instanceof + org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) { + org.apache.airavata.credential.store.credential.impl.password.PasswordCredential pwdCredential = + (org.apache.airavata.credential.store.credential.impl.password.PasswordCredential) + credential; + pwdCredMap.put( + pwdCredential.getToken(), + pwdCredential.getDescription() == null ? "" : pwdCredential.getDescription()); + } + } + } + } catch (Throwable e) { + logger.error("Error occurred while retrieving credentials", e); + CredentialStoreException exception = new CredentialStoreException( + "Error occurred while retrieving credentials. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + return pwdCredMap; + } + + public boolean deleteSSHCredential(String tokenId, String gatewayId) throws CredentialStoreException { + try { + credentialReader.removeCredentials(gatewayId, tokenId); + return true; + } catch (Throwable e) { + String msg = "Error occurred while deleting SSH credential for token - " + tokenId + " and gateway id - " + + gatewayId; + logger.error(msg, e); + CredentialStoreException exception = new CredentialStoreException(msg); + exception.initCause(e); + throw exception; + } + } + + public boolean deletePWDCredential(String tokenId, String gatewayId) throws CredentialStoreException { + try { + credentialReader.removeCredentials(gatewayId, tokenId); + return true; + } catch (Throwable e) { + String msg = "Error occurred while deleting PWD credential for token - " + tokenId + " and gateway id - " + + gatewayId; + logger.error(msg, e); + CredentialStoreException exception = new CredentialStoreException(msg); + exception.initCause(e); + throw exception; + } + } +} diff --git a/airavata-api/src/main/java/org/apache/airavata/service/GroupManagerService.java b/airavata-api/src/main/java/org/apache/airavata/service/GroupManagerService.java new file mode 100644 index 0000000000..52a464286c --- /dev/null +++ b/airavata-api/src/main/java/org/apache/airavata/service/GroupManagerService.java @@ -0,0 +1,361 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.airavata.service; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.airavata.common.utils.Constants; +import org.apache.airavata.model.group.GroupModel; +import org.apache.airavata.model.security.AuthzToken; +import org.apache.airavata.model.user.UserProfile; +import org.apache.airavata.service.profile.groupmanager.cpi.exception.GroupManagerServiceException; +import org.apache.airavata.service.profile.user.core.repositories.UserProfileRepository; +import org.apache.airavata.sharing.registry.models.GroupCardinality; +import org.apache.airavata.sharing.registry.models.GroupType; +import org.apache.airavata.sharing.registry.models.SharingRegistryException; +import org.apache.airavata.sharing.registry.models.User; +import org.apache.airavata.sharing.registry.models.UserGroup; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class GroupManagerService { + private static final Logger logger = LoggerFactory.getLogger(GroupManagerService.class); + private UserProfileRepository userProfileRepository = new UserProfileRepository(); + private SharingRegistryService sharingService = new SharingRegistryService(); + + public String createGroup(AuthzToken authzToken, GroupModel groupModel) throws GroupManagerServiceException { + try { + // TODO Validations for authorization + var sharingUserGroup = new UserGroup(); + sharingUserGroup.setGroupId(UUID.randomUUID().toString()); + sharingUserGroup.setName(groupModel.getName()); + sharingUserGroup.setDescription(groupModel.getDescription()); + sharingUserGroup.setGroupType(GroupType.USER_LEVEL_GROUP); + sharingUserGroup.setGroupCardinality(GroupCardinality.MULTI_USER); + var gatewayId = getDomainId(authzToken); + sharingUserGroup.setDomainId(gatewayId); + sharingUserGroup.setOwnerId(getUserId(authzToken)); + + var groupId = sharingService.createGroup(sharingUserGroup); + internalAddUsersToGroup(sharingService, gatewayId, groupModel.getMembers(), groupId); + if (groupModel.getAdmins() != null && !groupModel.getAdmins().isEmpty()) { + sharingService.addGroupAdmins(gatewayId, groupId, groupModel.getAdmins()); + } + return groupId; + } catch (Exception e) { + var msg = "Error Creating Group"; + logger.error(msg, e); + var exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateGroup(AuthzToken authzToken, GroupModel groupModel) throws GroupManagerServiceException { + try { + var userId = getUserId(authzToken); + var domainId = getDomainId(authzToken); + if (!(sharingService.hasOwnerAccess(domainId, groupModel.getId(), userId) + || sharingService.hasAdminAccess(domainId, groupModel.getId(), userId))) { + throw new GroupManagerServiceException("User does not have permission to update group"); + } + + var sharingUserGroup = new UserGroup(); + sharingUserGroup.setGroupId(groupModel.getId()); + sharingUserGroup.setName(groupModel.getName()); + sharingUserGroup.setDescription(groupModel.getDescription()); + sharingUserGroup.setGroupType(GroupType.USER_LEVEL_GROUP); + sharingUserGroup.setDomainId(getDomainId(authzToken)); + + // adding and removal of users should be handle separately + sharingService.updateGroup(sharingUserGroup); + return true; + } catch (Exception e) { + String msg = "Error Updating Group"; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteGroup(AuthzToken authzToken, String groupId, String ownerId) + throws GroupManagerServiceException { + try { + String userId = getUserId(authzToken); + String domainId = getDomainId(authzToken); + if (!(sharingService.hasOwnerAccess(domainId, groupId, userId))) { + throw new GroupManagerServiceException("User does not have permission to delete group"); + } + + sharingService.deleteGroup(getDomainId(authzToken), groupId); + return true; + } catch (Exception e) { + String msg = "Error Deleting Group. Group ID: " + groupId; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public GroupModel getGroup(AuthzToken authzToken, String groupId) throws GroupManagerServiceException { + try { + final String domainId = getDomainId(authzToken); + UserGroup userGroup = sharingService.getGroup(domainId, groupId); + GroupModel groupModel = convertToGroupModel(userGroup, sharingService); + return groupModel; + } catch (Exception e) { + String msg = "Error Retreiving Group. Group ID: " + groupId; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getGroups(AuthzToken authzToken) throws GroupManagerServiceException { + final String domainId = getDomainId(authzToken); + try { + List userGroups = sharingService.getGroups(domainId, 0, -1); + return convertToGroupModels(userGroups, sharingService); + } catch (Exception e) { + String msg = "Error Retrieving Groups. Domain ID: " + domainId; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllGroupsUserBelongs(AuthzToken authzToken, String userName) + throws GroupManagerServiceException { + try { + final String domainId = getDomainId(authzToken); + List userGroups = sharingService.getAllMemberGroupsForUser(domainId, userName); + return convertToGroupModels(userGroups, sharingService); + } catch (Exception e) { + String msg = "Error Retreiving All Groups for User. User ID: " + userName; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean addUsersToGroup(AuthzToken authzToken, List userIds, String groupId) + throws GroupManagerServiceException { + try { + String userId = getUserId(authzToken); + String domainId = getDomainId(authzToken); + if (!(sharingService.hasOwnerAccess(domainId, groupId, userId) + || sharingService.hasAdminAccess(domainId, groupId, userId))) { + throw new GroupManagerServiceException("User does not have access to add users to the group"); + } + return internalAddUsersToGroup(sharingService, domainId, userIds, groupId); + + } catch (Exception e) { + String msg = "Error adding users to group. Group ID: " + groupId; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean removeUsersFromGroup(AuthzToken authzToken, List userIds, String groupId) + throws GroupManagerServiceException { + try { + String userId = getUserId(authzToken); + String domainId = getDomainId(authzToken); + if (!(sharingService.hasOwnerAccess(domainId, groupId, userId) + || sharingService.hasAdminAccess(domainId, groupId, userId))) { + throw new GroupManagerServiceException("User does not have access to remove users to the group"); + } + return sharingService.removeUsersFromGroup(domainId, userIds, groupId); + } catch (Exception e) { + String msg = "Error remove users to group. Group ID: " + groupId; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean transferGroupOwnership(AuthzToken authzToken, String groupId, String newOwnerId) + throws GroupManagerServiceException { + try { + String userId = getUserId(authzToken); + String domainId = getDomainId(authzToken); + if (!(sharingService.hasOwnerAccess(domainId, groupId, userId))) { + throw new GroupManagerServiceException( + "User does not have Owner permission to transfer group ownership"); + } + return sharingService.transferGroupOwnership(getDomainId(authzToken), groupId, newOwnerId); + } catch (Exception e) { + String msg = "Error Transferring Group Ownership"; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean addGroupAdmins(AuthzToken authzToken, String groupId, List adminIds) + throws GroupManagerServiceException { + try { + String userId = getUserId(authzToken); + String domainId = getDomainId(authzToken); + if (!(sharingService.hasOwnerAccess(domainId, groupId, userId))) { + throw new GroupManagerServiceException("User does not have Owner permission to add group admins"); + } + return sharingService.addGroupAdmins(getDomainId(authzToken), groupId, adminIds); + } catch (Exception e) { + String msg = "Error Adding Admins to Group. Group ID: " + groupId; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean removeGroupAdmins(AuthzToken authzToken, String groupId, List adminIds) + throws GroupManagerServiceException { + try { + String userId = getUserId(authzToken); + String domainId = getDomainId(authzToken); + if (!(sharingService.hasOwnerAccess(domainId, groupId, userId))) { + throw new GroupManagerServiceException("User does not have Owner permission to remove group admins"); + } + return sharingService.removeGroupAdmins(getDomainId(authzToken), groupId, adminIds); + } catch (Exception e) { + String msg = "Error Removing Admins from the Group. Group ID: " + groupId; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean hasAdminAccess(AuthzToken authzToken, String groupId, String adminId) + throws GroupManagerServiceException { + try { + return sharingService.hasAdminAccess(getDomainId(authzToken), groupId, adminId); + } catch (Exception e) { + String msg = "Error Checking Admin Access for the Group. Group ID: " + groupId + " Admin ID: " + adminId; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean hasOwnerAccess(AuthzToken authzToken, String groupId, String ownerId) + throws GroupManagerServiceException { + try { + return sharingService.hasOwnerAccess(getDomainId(authzToken), groupId, ownerId); + } catch (Exception e) { + String msg = "Error Checking Owner Access for the Group. Group ID: " + groupId + " Owner ID: " + ownerId; + logger.error(msg, e); + GroupManagerServiceException exception = new GroupManagerServiceException(); + exception.setMessage(msg + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private String getDomainId(AuthzToken authzToken) { + return authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + } + + private String getUserId(AuthzToken authzToken) { + return authzToken.getClaimsMap().get(Constants.USER_NAME) + "@" + getDomainId(authzToken); + } + + private List convertToGroupModels(List userGroups, SharingRegistryService sharingService) + throws SharingRegistryException { + + List groupModels = new ArrayList<>(); + + for (UserGroup userGroup : userGroups) { + GroupModel groupModel = convertToGroupModel(userGroup, sharingService); + + groupModels.add(groupModel); + } + return groupModels; + } + + private GroupModel convertToGroupModel(UserGroup userGroup, SharingRegistryService sharingService) + throws SharingRegistryException { + GroupModel groupModel = new GroupModel(); + groupModel.setId(userGroup.getGroupId()); + groupModel.setName(userGroup.getName()); + groupModel.setDescription(userGroup.getDescription()); + groupModel.setOwnerId(userGroup.getOwnerId()); + final List admins = userGroup.getGroupAdmins().stream() + .map(groupAdmin -> groupAdmin.getAdminId()) + .collect(Collectors.toList()); + groupModel.setAdmins(admins); + + sharingService.getGroupMembersOfTypeUser(userGroup.getDomainId(), userGroup.getGroupId(), 0, -1).stream() + .forEach(user -> groupModel.addToMembers(user.getUserId())); + return groupModel; + } + + private boolean internalAddUsersToGroup( + SharingRegistryService sharingService, String domainId, List userIds, String groupId) + throws SharingRegistryException { + + // FIXME: workaround for UserProfiles that failed to sync to the sharing + // registry: create any missing users in the sharing registry + for (String userId : userIds) { + if (!sharingService.isUserExists(domainId, userId)) { + User user = new User(); + user.setDomainId(domainId); + user.setUserId(userId); + UserProfile userProfile = userProfileRepository.get(userId); + user.setUserName(userProfile.getUserId()); + user.setCreatedTime(userProfile.getCreationTime()); + user.setEmail( + userProfile.getEmailsSize() > 0 + ? userProfile.getEmails().get(0) + : null); + user.setFirstName(userProfile.getFirstName()); + user.setLastName(userProfile.getLastName()); + sharingService.createUser(user); + } + } + return sharingService.addUsersToGroup(domainId, userIds, groupId); + } +} diff --git a/airavata-api/src/main/java/org/apache/airavata/service/IamAdminService.java b/airavata-api/src/main/java/org/apache/airavata/service/IamAdminService.java new file mode 100644 index 0000000000..582aa0b3bd --- /dev/null +++ b/airavata-api/src/main/java/org/apache/airavata/service/IamAdminService.java @@ -0,0 +1,362 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.airavata.service; + +import java.util.List; +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.AiravataUtils; +import org.apache.airavata.common.utils.Constants; +import org.apache.airavata.common.utils.DBEventService; +import org.apache.airavata.common.utils.ServerSettings; +import org.apache.airavata.credential.store.exception.CredentialStoreException; +import org.apache.airavata.messaging.core.util.DBEventPublisherUtils; +import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile; +import org.apache.airavata.model.credential.store.PasswordCredential; +import org.apache.airavata.model.dbevent.CrudType; +import org.apache.airavata.model.dbevent.EntityType; +import org.apache.airavata.model.security.AuthzToken; +import org.apache.airavata.model.user.UserProfile; +import org.apache.airavata.model.workspace.Gateway; +import org.apache.airavata.registry.api.exception.RegistryServiceException; +import org.apache.airavata.service.profile.iam.admin.services.core.impl.TenantManagementKeycloakImpl; +import org.apache.airavata.service.profile.iam.admin.services.cpi.exception.IamAdminServicesException; +import org.apache.airavata.service.profile.user.core.repositories.UserProfileRepository; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IamAdminService { + private static final Logger logger = LoggerFactory.getLogger(IamAdminService.class); + private UserProfileRepository userProfileRepository = new UserProfileRepository(); + private DBEventPublisherUtils dbEventPublisherUtils = new DBEventPublisherUtils(DBEventService.IAM_ADMIN); + private final CredentialStoreService credentialStoreService; + private final RegistryService registryService; + + public IamAdminService() throws ApplicationSettingsException { + try { + credentialStoreService = new CredentialStoreService(); + registryService = new RegistryService(); + } catch (Throwable e) { + throw new RuntimeException("Unable to create credential store and registry services", e); + } + } + + public Gateway setUpGateway(AuthzToken authzToken, Gateway gateway) throws IamAdminServicesException { + var keycloakclient = new TenantManagementKeycloakImpl(); + var isSuperAdminCredentials = getSuperAdminPasswordCredential(); + try { + keycloakclient.addTenant(isSuperAdminCredentials, gateway); + + // Load the tenant admin password stored in gateway request + // Admin password token should already be stored under requested gateway's gatewayId + var tenantAdminPasswordCredential = credentialStoreService.getPasswordCredential( + gateway.getIdentityServerPasswordToken(), gateway.getGatewayId()); + + if (!keycloakclient.createTenantAdminAccount( + isSuperAdminCredentials, gateway, tenantAdminPasswordCredential.getPassword())) { + logger.error("Admin account creation failed !!, please refer error logs for reason"); + } + var gatewayWithIdAndSecret = keycloakclient.configureClient(isSuperAdminCredentials, gateway); + return gatewayWithIdAndSecret; + } catch (Throwable ex) { + String msg = "Gateway Setup Failed, reason: " + ex.getMessage(); + logger.error(msg, ex); + IamAdminServicesException exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean isUsernameAvailable(AuthzToken authzToken, String username) throws IamAdminServicesException { + try { + var keycloakClient = new TenantManagementKeycloakImpl(); + var gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + return keycloakClient.isUsernameAvailable(authzToken.getAccessToken(), gatewayId, username); + } catch (IamAdminServicesException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while checking username availability, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean registerUser( + AuthzToken authzToken, + String username, + String emailAddress, + String firstName, + String lastName, + String newPassword) + throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + if (keycloakclient.createUser( + authzToken.getAccessToken(), gatewayId, username, emailAddress, firstName, lastName, newPassword)) + return true; + else return false; + } catch (Throwable ex) { + String msg = "Error while registering user into Identity Server, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean enableUser(AuthzToken authzToken, String username) throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + if (keycloakclient.enableUserAccount(authzToken.getAccessToken(), gatewayId, username)) { + // Check if user profile exists, if not create it + boolean userProfileExists = + userProfileRepository.getUserProfileByIdAndGateWay(username, gatewayId) != null; + if (!userProfileExists) { + // Load basic user profile information from Keycloak and then save in UserProfileRepository + UserProfile userProfile = keycloakclient.getUser(authzToken.getAccessToken(), gatewayId, username); + userProfile.setCreationTime( + AiravataUtils.getCurrentTimestamp().getTime()); + userProfile.setLastAccessTime( + AiravataUtils.getCurrentTimestamp().getTime()); + userProfile.setValidUntil(-1); + userProfileRepository.createUserProfile(userProfile); + // Dispatch IAM_ADMIN service event for a new USER_PROFILE + dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.CREATE, userProfile); + } + return true; + } else { + return false; + } + } catch (Throwable ex) { + String msg = "Error while enabling user account, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean isUserEnabled(AuthzToken authzToken, String username) throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + return keycloakclient.isUserAccountEnabled(authzToken.getAccessToken(), gatewayId, username); + } catch (Exception ex) { + String msg = "Error while checking if user account is enabled, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean isUserExist(AuthzToken authzToken, String username) throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + return keycloakclient.isUserExist(authzToken.getAccessToken(), gatewayId, username); + } catch (Exception ex) { + String msg = "Error while checking if user account exists, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public UserProfile getUser(AuthzToken authzToken, String username) throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + return keycloakclient.getUser(authzToken.getAccessToken(), gatewayId, username); + } catch (Exception ex) { + String msg = "Error while retrieving user profile from IAM backend, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getUsers(AuthzToken authzToken, int offset, int limit, String search) + throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + return keycloakclient.getUsers(authzToken.getAccessToken(), gatewayId, offset, limit, search); + } catch (Exception ex) { + String msg = "Error while retrieving user profile from IAM backend, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean resetUserPassword(AuthzToken authzToken, String username, String newPassword) + throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + if (keycloakclient.resetUserPassword(authzToken.getAccessToken(), gatewayId, username, newPassword)) + return true; + else return false; + } catch (Throwable ex) { + String msg = "Error while resetting user password in Identity Server, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List findUsers(AuthzToken authzToken, String email, String userId) + throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + return keycloakclient.findUser(authzToken.getAccessToken(), gatewayId, email, userId); + } catch (Throwable ex) { + String msg = "Error while retrieving users from Identity Server, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public void updateUserProfile(AuthzToken authzToken, UserProfile userDetails) throws IamAdminServicesException { + try { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String username = userDetails.getUserId(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + keycloakclient.updateUserProfile(authzToken.getAccessToken(), gatewayId, username, userDetails); + } catch (IamAdminServicesException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while updating user profile, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean deleteUser(AuthzToken authzToken, String username) throws IamAdminServicesException { + try { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + return keycloakclient.deleteUser(authzToken.getAccessToken(), gatewayId, username); + } catch (IamAdminServicesException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while deleting user, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean addRoleToUser(AuthzToken authzToken, String username, String roleName) + throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + PasswordCredential isRealmAdminCredentials = getTenantAdminPasswordCredential(gatewayId); + return keycloakclient.addRoleToUser(isRealmAdminCredentials, gatewayId, username, roleName); + } catch (Throwable ex) { + String msg = "Error while adding role to user, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean removeRoleFromUser(AuthzToken authzToken, String username, String roleName) + throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + PasswordCredential isRealmAdminCredentials = getTenantAdminPasswordCredential(gatewayId); + return keycloakclient.removeRoleFromUser(isRealmAdminCredentials, gatewayId, username, roleName); + } catch (Throwable ex) { + String msg = "Error while removing role from user, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getUsersWithRole(AuthzToken authzToken, String roleName) throws IamAdminServicesException { + TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + PasswordCredential isRealmAdminCredentials = getTenantAdminPasswordCredential(gatewayId); + return keycloakclient.getUsersWithRole(isRealmAdminCredentials, gatewayId, roleName); + } catch (Exception ex) { + String msg = "Error while retrieving users with role, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new IamAdminServicesException(msg); + exception.initCause(ex); + throw exception; + } + } + + private PasswordCredential getSuperAdminPasswordCredential() { + PasswordCredential isSuperAdminCredentials = new PasswordCredential(); + try { + isSuperAdminCredentials.setLoginUserName(ServerSettings.getIamServerSuperAdminUsername()); + isSuperAdminCredentials.setPassword(ServerSettings.getIamServerSuperAdminPassword()); + } catch (ApplicationSettingsException e) { + throw new RuntimeException("Unable to get settings for IAM super admin username/password", e); + } + return isSuperAdminCredentials; + } + + private PasswordCredential getTenantAdminPasswordCredential(String tenantId) throws IamAdminServicesException { + + GatewayResourceProfile gwrp = null; + try { + gwrp = registryService.getGatewayResourceProfile(tenantId); + } catch (RegistryServiceException e) { + String msg = "Error while getting gateway resource profile, reason: " + e.getMessage(); + logger.error(msg, e); + var exception = new IamAdminServicesException(msg); + exception.initCause(e); + throw exception; + } + try { + return credentialStoreService.getPasswordCredential( + gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID()); + } catch (CredentialStoreException e) { + String msg = "Error while getting password credential, reason: " + e.getMessage(); + logger.error(msg, e); + var exception = new IamAdminServicesException(msg); + exception.initCause(e); + throw exception; + } + } +} diff --git a/airavata-api/src/main/java/org/apache/airavata/service/OrchestratorRegistryService.java b/airavata-api/src/main/java/org/apache/airavata/service/OrchestratorRegistryService.java new file mode 100644 index 0000000000..2a014b362d --- /dev/null +++ b/airavata-api/src/main/java/org/apache/airavata/service/OrchestratorRegistryService.java @@ -0,0 +1,125 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.airavata.service; + +import java.util.List; +import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription; +import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription; +import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription; +import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference; +import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile; +import org.apache.airavata.model.application.io.OutputDataObjectType; +import org.apache.airavata.model.commons.ErrorModel; +import org.apache.airavata.model.data.replica.DataProductModel; +import org.apache.airavata.model.experiment.ExperimentModel; +import org.apache.airavata.model.process.ProcessModel; +import org.apache.airavata.model.status.ExperimentStatus; +import org.apache.airavata.model.status.ProcessStatus; +import org.apache.airavata.model.status.QueueStatusModel; +import org.apache.airavata.registry.api.exception.RegistryServiceException; + +public class OrchestratorRegistryService { + + private RegistryService registryService = new RegistryService(); + + public ExperimentModel getExperiment(String airavataExperimentId) throws RegistryServiceException { + return registryService.getExperiment(airavataExperimentId); + } + + public GroupComputeResourcePreference getGroupComputeResourcePreference( + String computeResourceId, String groupResourceProfileId) throws RegistryServiceException { + return registryService.getGroupComputeResourcePreference(computeResourceId, groupResourceProfileId); + } + + public GroupResourceProfile getGroupResourceProfile(String groupResourceProfileId) throws RegistryServiceException { + return registryService.getGroupResourceProfile(groupResourceProfileId); + } + + public DataProductModel getDataProduct(String productUri) throws RegistryServiceException { + return registryService.getDataProduct(productUri); + } + + public void updateProcess(ProcessModel processModel, String processId) throws RegistryServiceException { + registryService.updateProcess(processModel, processId); + } + + public void addErrors(String errorType, ErrorModel errorModel, String id) throws RegistryServiceException { + registryService.addErrors(errorType, errorModel, id); + } + + public ExperimentStatus getExperimentStatus(String airavataExperimentId) throws RegistryServiceException { + return registryService.getExperimentStatus(airavataExperimentId); + } + + public void updateExperimentStatus(ExperimentStatus experimentStatus, String experimentId) + throws RegistryServiceException { + registryService.updateExperimentStatus(experimentStatus, experimentId); + } + + public String addProcess(ProcessModel processModel, String experimentId) throws RegistryServiceException { + return registryService.addProcess(processModel, experimentId); + } + + public ProcessModel getProcess(String processId) throws RegistryServiceException { + return registryService.getProcess(processId); + } + + public List getProcessList(String experimentId) throws RegistryServiceException { + return registryService.getProcessList(experimentId); + } + + public ProcessStatus getProcessStatus(String processId) throws RegistryServiceException { + return registryService.getProcessStatus(processId); + } + + public List getProcessIds(String experimentId) throws RegistryServiceException { + return registryService.getProcessIds(experimentId); + } + + public void addProcessStatus(ProcessStatus processStatus, String processId) throws RegistryServiceException { + registryService.addProcessStatus(processStatus, processId); + } + + public List getApplicationOutputs(String appInterfaceId) throws RegistryServiceException { + return registryService.getApplicationOutputs(appInterfaceId); + } + + public ApplicationInterfaceDescription getApplicationInterface(String appInterfaceId) + throws RegistryServiceException { + return registryService.getApplicationInterface(appInterfaceId); + } + + public List getApplicationDeployments(String appModuleId) + throws RegistryServiceException { + return registryService.getApplicationDeployments(appModuleId); + } + + public ComputeResourceDescription getComputeResource(String computeResourceId) throws RegistryServiceException { + return registryService.getComputeResource(computeResourceId); + } + + public void deleteTasks(String processId) throws RegistryServiceException { + registryService.deleteTasks(processId); + } + + public void registerQueueStatuses(List queueStatuses) throws RegistryServiceException { + registryService.registerQueueStatuses(queueStatuses); + } +} diff --git a/airavata-api/src/main/java/org/apache/airavata/service/OrchestratorService.java b/airavata-api/src/main/java/org/apache/airavata/service/OrchestratorService.java new file mode 100644 index 0000000000..58a73bb785 --- /dev/null +++ b/airavata-api/src/main/java/org/apache/airavata/service/OrchestratorService.java @@ -0,0 +1,926 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.airavata.service; + +import java.lang.reflect.InvocationTargetException; +import java.text.MessageFormat; +import java.util.*; +import java.util.concurrent.ExecutorService; +import org.apache.airavata.common.exception.AiravataException; +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.logging.MDCConstants; +import org.apache.airavata.common.logging.MDCUtil; +import org.apache.airavata.common.utils.AiravataUtils; +import org.apache.airavata.common.utils.ServerSettings; +import org.apache.airavata.common.utils.ThriftUtils; +import org.apache.airavata.common.utils.ZkConstants; +import org.apache.airavata.messaging.core.MessageContext; +import org.apache.airavata.messaging.core.MessageHandler; +import org.apache.airavata.messaging.core.MessagingFactory; +import org.apache.airavata.messaging.core.Publisher; +import org.apache.airavata.messaging.core.Subscriber; +import org.apache.airavata.messaging.core.Type; +import org.apache.airavata.metascheduler.core.api.ProcessScheduler; +import org.apache.airavata.metascheduler.process.scheduling.api.ProcessSchedulerImpl; +import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription; +import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription; +import org.apache.airavata.model.appcatalog.computeresource.ComputeResourceDescription; +import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference; +import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile; +import org.apache.airavata.model.application.io.DataType; +import org.apache.airavata.model.application.io.OutputDataObjectType; +import org.apache.airavata.model.commons.ErrorModel; +import org.apache.airavata.model.data.replica.DataProductModel; +import org.apache.airavata.model.data.replica.DataReplicaLocationModel; +import org.apache.airavata.model.data.replica.ReplicaLocationCategory; +import org.apache.airavata.model.error.ExperimentNotFoundException; +import org.apache.airavata.model.error.LaunchValidationException; +import org.apache.airavata.model.error.ValidationResults; +import org.apache.airavata.model.experiment.ExperimentModel; +import org.apache.airavata.model.experiment.ExperimentType; +import org.apache.airavata.model.experiment.UserConfigurationDataModel; +import org.apache.airavata.model.messaging.event.*; +import org.apache.airavata.model.process.ProcessModel; +import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel; +import org.apache.airavata.model.status.ExperimentState; +import org.apache.airavata.model.status.ExperimentStatus; +import org.apache.airavata.model.status.ProcessState; +import org.apache.airavata.model.status.ProcessStatus; +import org.apache.airavata.model.status.QueueStatusModel; +import org.apache.airavata.model.task.TaskTypes; +import org.apache.airavata.model.util.ExperimentModelUtil; +import org.apache.airavata.orchestrator.core.exception.OrchestratorException; +import org.apache.airavata.orchestrator.core.schedule.HostScheduler; +import org.apache.airavata.orchestrator.core.utils.OrchestratorConstants; +import org.apache.airavata.orchestrator.cpi.impl.SimpleOrchestratorImpl; +import org.apache.airavata.registry.api.exception.RegistryServiceException; +import org.apache.commons.lang3.StringUtils; +import org.apache.curator.RetryPolicy; +import org.apache.curator.framework.CuratorFramework; +import org.apache.curator.framework.CuratorFrameworkFactory; +import org.apache.curator.retry.ExponentialBackoffRetry; +import org.apache.curator.utils.ZKPaths; +import org.apache.thrift.TException; +import org.apache.zookeeper.data.Stat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; + +public class OrchestratorService { + private static final Logger logger = LoggerFactory.getLogger(OrchestratorService.class); + + private OrchestratorRegistryService orchestratorRegistryService; + private SimpleOrchestratorImpl orchestrator; + private CuratorFramework curatorClient; + private Publisher publisher; + private Subscriber experimentSubscriber; + // private String airavataUserName; + // private String gatewayName; + + public OrchestratorService() throws OrchestratorException { + try { + this.orchestratorRegistryService = new OrchestratorRegistryService(); + // setAiravataUserName(ServerSettings.getDefaultUser()); + this.orchestrator = new SimpleOrchestratorImpl(); + this.publisher = MessagingFactory.getPublisher(Type.STATUS); + this.orchestrator.initialize(); + this.orchestrator.getOrchestratorContext().setPublisher(this.publisher); + startCurator(); + this.experimentSubscriber = getExperimentSubscriber(); + } catch (Exception e) { + throw new OrchestratorException("Error initializing OrchestratorService", e); + } + } + + public OrchestratorService( + OrchestratorRegistryService orchestratorRegistryService, + SimpleOrchestratorImpl orchestrator, + CuratorFramework curatorClient, + Publisher publisher) { + this.orchestratorRegistryService = orchestratorRegistryService; + this.orchestrator = orchestrator; + this.curatorClient = curatorClient; + this.publisher = publisher; + } + + private boolean launchExperimentInternal(String experimentId, String gatewayId) + throws ExperimentNotFoundException, OrchestratorException, RegistryServiceException, + LaunchValidationException { + String experimentNodePath = getExperimentNodePath(experimentId); + try { + ZKPaths.mkdirs(curatorClient.getZookeeperClient().getZooKeeper(), experimentNodePath); + String experimentCancelNode = + ZKPaths.makePath(experimentNodePath, ZkConstants.ZOOKEEPER_CANCEL_LISTENER_NODE); + ZKPaths.mkdirs(curatorClient.getZookeeperClient().getZooKeeper(), experimentCancelNode); + } catch (Exception e) { + throw new OrchestratorException("Error creating ZooKeeper nodes for experiment: " + experimentId, e); + } + ExperimentModel experiment = orchestratorRegistryService.getExperiment(experimentId); + if (experiment == null) { + throw new ExperimentNotFoundException( + "Error retrieving the Experiment by the given experimentID: " + experimentId); + } + + UserConfigurationDataModel userConfigurationData = experiment.getUserConfigurationData(); + String token = getCredentialToken(experiment, userConfigurationData); + + ExperimentType executionType = experiment.getExperimentType(); + if (executionType == ExperimentType.SINGLE_APPLICATION) { + return launchSingleAppExperiment(experiment, experimentId, gatewayId, token); + } else if (executionType == ExperimentType.WORKFLOW) { + logger.debug(experimentId, "Launching workflow experiment {}.", experimentId); + launchWorkflowExperiment(experimentId, token, gatewayId); + return true; + } else { + logger.error( + experimentId, + "Couldn't identify experiment type, experiment {} is neither single application nor workflow.", + experimentId); + throw new OrchestratorException("Experiment '" + experimentId + + "' launch failed. Unable to figureout execution type for application " + + experiment.getExecutionId()); + } + } + + private boolean launchSingleAppExperiment( + ExperimentModel experiment, String experimentId, String gatewayId, String token) + throws OrchestratorException, RegistryServiceException, LaunchValidationException { + List processes = orchestrator.createProcesses(experimentId, gatewayId); + + for (ProcessModel processModel : processes) { + resolveInputReplicas(processModel); + + if (!experiment.getUserConfigurationData().isAiravataAutoSchedule()) { + String taskDag = orchestrator.createAndSaveTasks(gatewayId, processModel); + processModel.setTaskDag(taskDag); + } + orchestratorRegistryService.updateProcess(processModel, processModel.getProcessId()); + } + + if (!experiment.getUserConfigurationData().isAiravataAutoSchedule() + && !validateProcess(experimentId, processes)) { + LaunchValidationException exception = new LaunchValidationException(); + ValidationResults validationResults = new ValidationResults(); + validationResults.setValidationState(false); + validationResults.setValidationResultList(new ArrayList<>()); + exception.setValidationResult(validationResults); + exception.setErrorMessage("Validating process fails for given experiment Id : " + experimentId); + throw exception; + } + + ProcessScheduler scheduler = new ProcessSchedulerImpl(); + if (!experiment.getUserConfigurationData().isAiravataAutoSchedule() || scheduler.canLaunch(experimentId)) { + createAndValidateTasks(experiment, false); + return true; // runExperimentLauncher will be called separately + } else { + logger.debug(experimentId, "Queuing single application experiment {}.", experimentId); + ExperimentStatus status = new ExperimentStatus(ExperimentState.SCHEDULED); + status.setReason("Compute resources are not ready"); + status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); + updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); + logger.info("expId: {}, Scheduled experiment ", experimentId); + return false; + } + } + + private void resolveInputReplicas(ProcessModel processModel) throws RegistryServiceException { + for (var pi : processModel.getProcessInputs()) { + if (pi.getType().equals(DataType.URI) + && pi.getValue() != null + && pi.getValue().startsWith("airavata-dp://")) { + DataProductModel dataProductModel = orchestratorRegistryService.getDataProduct(pi.getValue()); + Optional rpLocation = dataProductModel.getReplicaLocations().stream() + .filter(rpModel -> + rpModel.getReplicaLocationCategory().equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)) + .findFirst(); + if (rpLocation.isPresent()) { + pi.setValue(rpLocation.get().getFilePath()); + pi.setStorageResourceId(rpLocation.get().getStorageResourceId()); + } else { + logger.error("Could not find a replica for the URI " + pi.getValue()); + } + } else if (pi.getType().equals(DataType.URI_COLLECTION) + && pi.getValue() != null + && pi.getValue().contains("airavata-dp://")) { + String[] uriList = pi.getValue().split(","); + final ArrayList filePathList = new ArrayList<>(); + for (String uri : uriList) { + if (uri.startsWith("airavata-dp://")) { + DataProductModel dataProductModel = orchestratorRegistryService.getDataProduct(uri); + Optional rpLocation = dataProductModel.getReplicaLocations().stream() + .filter(rpModel -> rpModel.getReplicaLocationCategory() + .equals(ReplicaLocationCategory.GATEWAY_DATA_STORE)) + .findFirst(); + if (rpLocation.isPresent()) { + filePathList.add(rpLocation.get().getFilePath()); + } else { + logger.error("Could not find a replica for the URI " + pi.getValue()); + } + } else { + filePathList.add(uri); + } + } + pi.setValue(StringUtils.join(filePathList, ',')); + } + } + } + + public String getCredentialToken(ExperimentModel experiment, UserConfigurationDataModel userConfigurationData) + throws OrchestratorException, RegistryServiceException { + String token = null; + final String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId(); + if (groupResourceProfileId == null) { + throw new OrchestratorException( + "Experiment not configured with a Group Resource Profile: " + experiment.getExperimentId()); + } + + if (userConfigurationData.getComputationalResourceScheduling() != null + && userConfigurationData + .getComputationalResourceScheduling() + .isSet(ComputationalResourceSchedulingModel._Fields.RESOURCE_HOST_ID)) { + GroupComputeResourcePreference groupComputeResourcePreference = + orchestratorRegistryService.getGroupComputeResourcePreference( + userConfigurationData + .getComputationalResourceScheduling() + .getResourceHostId(), + groupResourceProfileId); + + if (groupComputeResourcePreference.getResourceSpecificCredentialStoreToken() != null) { + token = groupComputeResourcePreference.getResourceSpecificCredentialStoreToken(); + } + } + if (token == null || token.isEmpty()) { + GroupResourceProfile groupResourceProfile = + orchestratorRegistryService.getGroupResourceProfile(groupResourceProfileId); + token = groupResourceProfile.getDefaultCredentialStoreToken(); + } + if (token == null || token.isEmpty()) { + throw new OrchestratorException( + "You have not configured credential store token at group resource profile or compute resource preference." + + " Please provide the correct token at group resource profile or compute resource preference."); + } + return token; + } + + public boolean validateExperiment(String experimentId) + throws LaunchValidationException, RegistryServiceException, OrchestratorException { + ExperimentModel experimentModel = orchestratorRegistryService.getExperiment(experimentId); + return orchestrator.validateExperiment(experimentModel).isValidationState(); + } + + public boolean validateProcess(String experimentId, List processes) + throws LaunchValidationException, RegistryServiceException, OrchestratorException { + ExperimentModel experimentModel = orchestratorRegistryService.getExperiment(experimentId); + for (ProcessModel processModel : processes) { + boolean state = + orchestrator.validateProcess(experimentModel, processModel).isSetValidationState(); + if (!state) { + return false; + } + } + return true; + } + + public boolean terminateExperiment(String experimentId, String gatewayId) + throws RegistryServiceException, OrchestratorException { + logger.info(experimentId, "Experiment: {} is cancelling !!!!!", experimentId); + return validateStatesAndCancel(experimentId, gatewayId); + } + + private boolean validateStatesAndCancel(String experimentId, String gatewayId) + throws RegistryServiceException, OrchestratorException { + ExperimentStatus experimentStatus = orchestratorRegistryService.getExperimentStatus(experimentId); + switch (experimentStatus.getState()) { + case COMPLETED: + case CANCELED: + case FAILED: + case CANCELING: + logger.warn( + "Can't terminate already {} experiment", + experimentStatus.getState().name()); + return false; + case CREATED: + logger.warn("Experiment termination is only allowed for launched experiments."); + return false; + default: + ExperimentModel experimentModel = orchestratorRegistryService.getExperiment(experimentId); + final UserConfigurationDataModel userConfigurationData = experimentModel.getUserConfigurationData(); + final String groupResourceProfileId = userConfigurationData.getGroupResourceProfileId(); + + GroupComputeResourcePreference groupComputeResourcePreference = + orchestratorRegistryService.getGroupComputeResourcePreference( + userConfigurationData + .getComputationalResourceScheduling() + .getResourceHostId(), + groupResourceProfileId); + String token = groupComputeResourcePreference.getResourceSpecificCredentialStoreToken(); + if (token == null || token.isEmpty()) { + GroupResourceProfile groupResourceProfile = + orchestratorRegistryService.getGroupResourceProfile(groupResourceProfileId); + token = groupResourceProfile.getDefaultCredentialStoreToken(); + } + if (token == null || token.isEmpty()) { + logger.error( + "You have not configured credential store token at group resource profile or compute resource preference." + + " Please provide the correct token at group resource profile or compute resource preference."); + return false; + } + + orchestrator.cancelExperiment(experimentModel, token); + String expCancelNodePath = ZKPaths.makePath( + ZKPaths.makePath(ZkConstants.ZOOKEEPER_EXPERIMENT_NODE, experimentId), + ZkConstants.ZOOKEEPER_CANCEL_LISTENER_NODE); + Stat stat; + try { + stat = curatorClient.checkExists().forPath(expCancelNodePath); + } catch (Exception e) { + logger.error("Error checking existence of Zookeeper node: " + expCancelNodePath, e); + throw new OrchestratorException( + "Error checking existence of Zookeeper node: " + expCancelNodePath, e); + } + if (stat != null) { + try { + curatorClient + .setData() + .withVersion(-1) + .forPath(expCancelNodePath, ZkConstants.ZOOKEEPER_CANCEL_REQEUST.getBytes()); + } catch (Exception e) { + logger.error("Error setting data for Zookeeper node: " + expCancelNodePath, e); + throw new OrchestratorException( + "Error setting data for Zookeeper node: " + expCancelNodePath, e); + } + ExperimentStatus status = new ExperimentStatus(ExperimentState.CANCELING); + status.setReason("Experiment cancel request processed"); + status.setTimeOfStateChange( + AiravataUtils.getCurrentTimestamp().getTime()); + updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); + logger.info("expId : " + experimentId + " :- Experiment status updated to " + status.getState()); + } + return true; + } + } + + public void fetchIntermediateOutputs(String experimentId, String gatewayId, List outputNames) + throws RegistryServiceException, OrchestratorException { + submitIntermediateOutputsProcess(experimentId, gatewayId, outputNames); + } + + private void submitIntermediateOutputsProcess(String experimentId, String gatewayId, List outputNames) + throws RegistryServiceException, OrchestratorException { + + ExperimentModel experimentModel = orchestratorRegistryService.getExperiment(experimentId); + ProcessModel processModel = ExperimentModelUtil.cloneProcessFromExperiment(experimentModel); + processModel.setExperimentDataDir(processModel.getExperimentDataDir() + "/intermediates"); + + List applicationOutputs = + orchestratorRegistryService.getApplicationOutputs(experimentModel.getExecutionId()); + List requestedOutputs = new ArrayList<>(); + + for (OutputDataObjectType output : applicationOutputs) { + if (outputNames.contains(output.getName())) { + requestedOutputs.add(output); + } + } + processModel.setProcessOutputs(requestedOutputs); + String processId = orchestratorRegistryService.addProcess(processModel, experimentId); + processModel.setProcessId(processId); + + try { + Optional jobSubmissionProcess = experimentModel.getProcesses().stream() + .filter(p -> p.getTasks().stream().anyMatch(t -> t.getTaskType() == TaskTypes.JOB_SUBMISSION)) + .findFirst(); + if (!jobSubmissionProcess.isPresent()) { + throw new OrchestratorException(MessageFormat.format( + "Could not find job submission process for experiment {0}, unable to fetch intermediate outputs {1}", + experimentId, outputNames)); + } + String taskDag = orchestrator.createAndSaveIntermediateOutputFetchingTasks( + gatewayId, processModel, jobSubmissionProcess.get()); + processModel.setTaskDag(taskDag); + + orchestratorRegistryService.updateProcess(processModel, processModel.getProcessId()); + + String token = getCredentialToken(experimentModel, experimentModel.getUserConfigurationData()); + orchestrator.launchProcess(processModel, token); + } catch (RegistryServiceException | OrchestratorException e) { + logger.error("Failed to launch process for intermediate output fetching", e); + + ProcessStatus status = new ProcessStatus(ProcessState.FAILED); + status.setReason("Intermediate output fetching process failed to launch: " + e.getMessage()); + status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); + orchestratorRegistryService.addProcessStatus(status, processId); + + throw e; + } + } + + public boolean launchProcess(String processId, String airavataCredStoreToken, String gatewayId) + throws RegistryServiceException, OrchestratorException { + ProcessStatus processStatus = orchestratorRegistryService.getProcessStatus(processId); + + switch (processStatus.getState()) { + case CREATED: + case VALIDATED: + case DEQUEUING: + ProcessModel processModel = orchestratorRegistryService.getProcess(processId); + String applicationId = processModel.getApplicationInterfaceId(); + if (applicationId == null) { + logger.error(processId, "Application interface id shouldn't be null."); + throw new OrchestratorException( + "Error executing the job, application interface id shouldn't be null."); + } + ApplicationDeploymentDescription applicationDeploymentDescription = + getAppDeployment(processModel, applicationId); + if (applicationDeploymentDescription == null) { + logger.error("Could not find an application deployment for " + processModel.getComputeResourceId() + + " and application " + applicationId); + throw new OrchestratorException("Could not find an application deployment for " + + processModel.getComputeResourceId() + " and application " + applicationId); + } + processModel.setApplicationDeploymentId(applicationDeploymentDescription.getAppDeploymentId()); + processModel.setComputeResourceId( + processModel.getProcessResourceSchedule().getResourceHostId()); + orchestratorRegistryService.updateProcess(processModel, processModel.getProcessId()); + return orchestrator.launchProcess(processModel, airavataCredStoreToken); + + default: + logger.warn("Process " + processId + " is already launched. So it can not be relaunched"); + return false; + } + } + + private ApplicationDeploymentDescription getAppDeployment(ProcessModel processModel, String applicationId) + throws OrchestratorException, RegistryServiceException { + String selectedModuleId = getModuleId(applicationId); + return getAppDeploymentForModule(processModel, selectedModuleId); + } + + private ApplicationDeploymentDescription getAppDeploymentForModule( + ProcessModel processModel, String selectedModuleId) throws OrchestratorException, RegistryServiceException { + + List applicationDeployements = + orchestratorRegistryService.getApplicationDeployments(selectedModuleId); + Map deploymentMap = new HashMap<>(); + + for (ApplicationDeploymentDescription deploymentDescription : applicationDeployements) { + if (processModel.getComputeResourceId().equals(deploymentDescription.getComputeHostId())) { + deploymentMap.put( + orchestratorRegistryService.getComputeResource(deploymentDescription.getComputeHostId()), + deploymentDescription); + } + } + List computeHostList = + Arrays.asList(deploymentMap.keySet().toArray(new ComputeResourceDescription[] {})); + HostScheduler hostScheduler; + try { + var schedulerClass = + Class.forName(ServerSettings.getHostScheduler()).asSubclass(HostScheduler.class); + hostScheduler = schedulerClass.getDeclaredConstructor().newInstance(); + } catch (ClassNotFoundException + | ApplicationSettingsException + | NoSuchMethodException + | InstantiationException + | IllegalAccessException + | InvocationTargetException e) { + throw new OrchestratorException("Failed to instantiate HostScheduler", e); + } + ComputeResourceDescription ComputeResourceDescription = hostScheduler.schedule(computeHostList); + return deploymentMap.get(ComputeResourceDescription); + } + + private String getModuleId(String applicationId) throws OrchestratorException, RegistryServiceException { + ApplicationInterfaceDescription applicationInterface = + orchestratorRegistryService.getApplicationInterface(applicationId); + List applicationModules = applicationInterface.getApplicationModules(); + if (applicationModules.size() == 0) { + throw new OrchestratorException("No modules defined for application " + applicationId); + } + String selectedModuleId = applicationModules.get(0); + return selectedModuleId; + } + + private void launchWorkflowExperiment(String experimentId, String airavataCredStoreToken, String gatewayId) + throws OrchestratorException { + throw new UnsupportedOperationException("Workflow support not implemented"); + } + + public void createAndValidateTasks(ExperimentModel experiment, boolean recreateTaskDag) + throws OrchestratorException, RegistryServiceException, LaunchValidationException { + if (experiment.getUserConfigurationData().isAiravataAutoSchedule()) { + List processModels = orchestratorRegistryService.getProcessList(experiment.getExperimentId()); + for (ProcessModel processModel : processModels) { + if (processModel.getTaskDag() == null || recreateTaskDag) { + orchestratorRegistryService.deleteTasks(processModel.getProcessId()); + String taskDag = orchestrator.createAndSaveTasks(experiment.getGatewayId(), processModel); + processModel.setTaskDag(taskDag); + orchestratorRegistryService.updateProcess(processModel, processModel.getProcessId()); + } + } + if (!validateProcess(experiment.getExperimentId(), processModels)) { + LaunchValidationException exception = new LaunchValidationException(); + ValidationResults validationResults = new ValidationResults(); + validationResults.setValidationState(false); + validationResults.setValidationResultList(new ArrayList<>()); + exception.setValidationResult(validationResults); + exception.setErrorMessage( + "Validating process fails for given experiment Id : " + experiment.getExperimentId()); + throw exception; + } + } + } + + public void addProcessValidationErrors(String experimentId, ErrorModel details) throws RegistryServiceException { + orchestratorRegistryService.addErrors(OrchestratorConstants.EXPERIMENT_ERROR, details, experimentId); + } + + public String getExperimentNodePath(String experimentId) { + return ZKPaths.makePath(ZkConstants.ZOOKEEPER_EXPERIMENT_NODE, experimentId); + } + + public boolean launchSingleAppExperimentInternal( + String experimentId, String airavataCredStoreToken, String gatewayId) + throws RegistryServiceException, OrchestratorException { + try { + List processIds = orchestratorRegistryService.getProcessIds(experimentId); + for (String processId : processIds) { + launchProcess(processId, airavataCredStoreToken, gatewayId); + } + return true; + } catch (RegistryServiceException e) { + ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED); + status.setReason("Error while retrieving process IDs"); + updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); + logger.error("expId: " + experimentId + ", Error while retrieving process IDs", e); + throw e; + } catch (OrchestratorException e) { + ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED); + status.setReason("Error while launching processes"); + updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); + logger.error("expId: " + experimentId + ", Error while launching processes", e); + throw e; + } + } + + public void launchQueuedExperiment(String experimentId) + throws ExperimentNotFoundException, OrchestratorException, RegistryServiceException, + LaunchValidationException { + ExperimentModel experiment = orchestratorRegistryService.getExperiment(experimentId); + if (experiment == null) { + throw new ExperimentNotFoundException( + "Error retrieving the Experiment by the given experimentID: " + experimentId); + } + + UserConfigurationDataModel userConfigurationData = experiment.getUserConfigurationData(); + String token = getCredentialToken(experiment, userConfigurationData); + createAndValidateTasks(experiment, true); + + // Publish experiment launched status and run launcher + ExperimentStatus status = new ExperimentStatus(ExperimentState.LAUNCHED); + status.setReason("submitted all processes"); + status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); + updateAndPublishExperimentStatus(experimentId, status, publisher, experiment.getGatewayId()); + logger.info("expId: {}, Launched experiment ", experimentId); + + // Launch processes + launchSingleAppExperimentInternal(experimentId, token, experiment.getGatewayId()); + } + + public void handleProcessStatusChange( + ProcessStatusChangeEvent processStatusChangeEvent, ProcessIdentifier processIdentity) + throws ExperimentNotFoundException, OrchestratorException, RegistryServiceException, + LaunchValidationException { + ExperimentStatus status = new ExperimentStatus(); + + // Check if this is an intermediate output fetching process + ProcessModel process = orchestratorRegistryService.getProcess(processIdentity.getProcessId()); + boolean isIntermediateOutputFetchingProcess = + process.getTasks().stream().anyMatch(t -> t.getTaskType() == TaskTypes.OUTPUT_FETCHING); + if (isIntermediateOutputFetchingProcess) { + logger.info("Not updating experiment status because process is an intermediate output fetching one"); + return; + } + + switch (processStatusChangeEvent.getState()) { + case STARTED: + ExperimentStatus stat = + orchestratorRegistryService.getExperimentStatus(processIdentity.getExperimentId()); + if (stat.getState() == ExperimentState.CANCELING) { + status.setState(ExperimentState.CANCELING); + status.setReason("Process started but experiment cancelling is triggered"); + } else { + status.setState(ExperimentState.EXECUTING); + status.setReason("process started"); + } + break; + case COMPLETED: + stat = orchestratorRegistryService.getExperimentStatus(processIdentity.getExperimentId()); + if (stat.getState() == ExperimentState.CANCELING) { + status.setState(ExperimentState.CANCELED); + status.setReason("Process competed but experiment cancelling is triggered"); + } else { + status.setState(ExperimentState.COMPLETED); + status.setReason("process completed"); + } + break; + case FAILED: + stat = orchestratorRegistryService.getExperimentStatus(processIdentity.getExperimentId()); + if (stat.getState() == ExperimentState.CANCELING) { + status.setState(ExperimentState.CANCELED); + status.setReason("Process failed but experiment cancelling is triggered"); + } else { + status.setState(ExperimentState.FAILED); + status.setReason("process failed"); + } + break; + case CANCELED: + status.setState(ExperimentState.CANCELED); + status.setReason("process cancelled"); + break; + case QUEUED: + status.setState(ExperimentState.SCHEDULED); + status.setReason("Process started but compute resource not avaialable"); + break; + case REQUEUED: + status.setState(ExperimentState.SCHEDULED); + status.setReason("Job submission failed, requeued to resubmit"); + registerQueueStatusForRequeue(processIdentity.getExperimentId()); + break; + case DEQUEUING: + stat = orchestratorRegistryService.getExperimentStatus(processIdentity.getExperimentId()); + if (stat.getState() == ExperimentState.CANCELING) { + status.setState(ExperimentState.CANCELING); + status.setReason("Process started but experiment cancelling is triggered"); + } else { + launchQueuedExperiment(processIdentity.getExperimentId()); + } + break; + default: + // ignore other status changes + return; + } + + if (status.getState() != null) { + status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); + updateAndPublishExperimentStatus( + processIdentity.getExperimentId(), status, publisher, processIdentity.getGatewayId()); + logger.info("expId : " + processIdentity.getExperimentId() + " :- Experiment status updated to " + + status.getState()); + } + } + + private void registerQueueStatusForRequeue(String experimentId) { + try { + List queueStatusModels = new ArrayList<>(); + ExperimentModel experimentModel = orchestratorRegistryService.getExperiment(experimentId); + UserConfigurationDataModel userConfigurationDataModel = experimentModel.getUserConfigurationData(); + if (userConfigurationDataModel != null) { + ComputationalResourceSchedulingModel computationalResourceSchedulingModel = + userConfigurationDataModel.getComputationalResourceScheduling(); + if (computationalResourceSchedulingModel != null) { + String queueName = computationalResourceSchedulingModel.getQueueName(); + String resourceId = computationalResourceSchedulingModel.getResourceHostId(); + ComputeResourceDescription comResourceDes = + orchestratorRegistryService.getComputeResource(resourceId); + QueueStatusModel queueStatusModel = new QueueStatusModel(); + queueStatusModel.setHostName(comResourceDes.getHostName()); + queueStatusModel.setQueueName(queueName); + queueStatusModel.setQueueUp(false); + queueStatusModel.setRunningJobs(0); + queueStatusModel.setQueuedJobs(0); + queueStatusModel.setTime(System.currentTimeMillis()); + queueStatusModels.add(queueStatusModel); + orchestratorRegistryService.registerQueueStatuses(queueStatusModels); + } + } + } catch (RegistryServiceException e) { + logger.error("Error while registering queue statuses", e); + } + } + + public void handleLaunchExperiment(ExperimentSubmitEvent expEvent) + throws ExperimentNotFoundException, OrchestratorException, RegistryServiceException, + LaunchValidationException { + ExperimentModel experimentModel = orchestratorRegistryService.getExperiment(expEvent.getExperimentId()); + if (experimentModel.getExperimentStatus().get(0).getState() == ExperimentState.CREATED) { + launchExperimentInternal(expEvent.getExperimentId(), expEvent.getGatewayId()); + } + } + + /** + * Handle launch experiment from message context with deserialization and redelivery checks + */ + public void handleLaunchExperimentFromMessage(MessageContext messageContext) + throws ExperimentNotFoundException, OrchestratorException, RegistryServiceException, + LaunchValidationException, TException { + ExperimentSubmitEvent expEvent = new ExperimentSubmitEvent(); + byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent()); + ThriftUtils.createThriftFromBytes(bytes, expEvent); + + if (messageContext.isRedeliver()) { + ExperimentModel experimentModel = orchestratorRegistryService.getExperiment(expEvent.getExperimentId()); + if (experimentModel != null + && experimentModel.getExperimentStatus().get(0).getState() == ExperimentState.CREATED) { + handleLaunchExperiment(expEvent); + } + } else { + handleLaunchExperiment(expEvent); + } + } + + public void handleCancelExperiment(ExperimentSubmitEvent expEvent) + throws RegistryServiceException, OrchestratorException { + terminateExperiment(expEvent.getExperimentId(), expEvent.getGatewayId()); + } + + public void handleIntermediateOutputsEvent(ExperimentIntermediateOutputsEvent event) { + try { + fetchIntermediateOutputs(event.getExperimentId(), event.getGatewayId(), event.getOutputNames()); + } catch (Exception e) { + logger.error("Error handling intermediate outputs event", e); + throw new RuntimeException("Error handling intermediate outputs event", e); + } + } + + private void updateAndPublishExperimentStatus( + String experimentId, ExperimentStatus status, Publisher publisher, String gatewayId) { + try { + orchestratorRegistryService.updateExperimentStatus(status, experimentId); + ExperimentStatusChangeEvent event = + new ExperimentStatusChangeEvent(status.getState(), experimentId, gatewayId); + String messageId = AiravataUtils.getId("EXPERIMENT"); + MessageContext messageContext = new MessageContext(event, MessageType.EXPERIMENT, messageId, gatewayId); + messageContext.setUpdatedTime(AiravataUtils.getCurrentTimestamp()); + publisher.publish(messageContext); + } catch (AiravataException e) { + logger.error( + "expId : " + experimentId + " Error while publishing experiment status to " + status.toString(), e); + } catch (RegistryServiceException e) { + logger.error( + "expId : " + experimentId + " Error while updating experiment status to " + status.toString(), e); + } + } + + public ExperimentStatus getExperimentStatus(String experimentId) throws RegistryServiceException { + return orchestratorRegistryService.getExperimentStatus(experimentId); + } + + public ProcessModel getProcess(String processId) throws RegistryServiceException { + return orchestratorRegistryService.getProcess(processId); + } + + public boolean launchExperiment(String experimentId, String gatewayId, ExecutorService executorService) + throws OrchestratorException { + try { + boolean result = launchExperimentInternal(experimentId, gatewayId); + if (result) { + ExperimentModel experiment = orchestratorRegistryService.getExperiment(experimentId); + String token = getCredentialToken(experiment, experiment.getUserConfigurationData()); + ExperimentStatus status = new ExperimentStatus(ExperimentState.LAUNCHED); + status.setReason("submitted all processes"); + status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); + updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); + logger.info("expId: {}, Launched experiment ", experimentId); + + // Execute the single app experiment runner in the provided thread pool + if (executorService != null) { + Runnable runner = () -> { + try { + launchSingleAppExperimentInternal(experimentId, token, gatewayId); + } catch (Exception e) { + logger.error("expId: " + experimentId + ", Error while launching single app experiment", e); + } + }; + executorService.execute(MDCUtil.wrapWithMDC(runner)); + } + } + return result; + } catch (LaunchValidationException launchValidationException) { + ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED); + status.setReason("Validation failed: " + launchValidationException.getErrorMessage()); + status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); + updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); + throw new OrchestratorException( + "Experiment '" + experimentId + "' launch failed. Experiment failed to validate: " + + launchValidationException.getErrorMessage(), + launchValidationException); + } catch (RegistryServiceException e) { + ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED); + status.setReason("Registry error: " + e.getMessage()); + status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); + updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); + throw new OrchestratorException("Experiment '" + experimentId + "' launch failed.", e); + } catch (Exception e) { + ExperimentStatus status = new ExperimentStatus(ExperimentState.FAILED); + status.setReason("Unexpected error occurred: " + e.getMessage()); + status.setTimeOfStateChange(AiravataUtils.getCurrentTimestamp().getTime()); + updateAndPublishExperimentStatus(experimentId, status, publisher, gatewayId); + throw new OrchestratorException("Experiment '" + experimentId + "' launch failed.", e); + } + } + + private void startCurator() throws ApplicationSettingsException { + String connectionSting = ServerSettings.getZookeeperConnection(); + RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 5); + curatorClient = CuratorFrameworkFactory.newClient(connectionSting, retryPolicy); + curatorClient.start(); + } + + private Subscriber getExperimentSubscriber() throws AiravataException { + List routingKeys = new ArrayList<>(); + routingKeys.add(ServerSettings.getRabbitmqExperimentLaunchQueueName()); + return MessagingFactory.getSubscriber(new ExperimentHandler(), routingKeys, Type.EXPERIMENT_LAUNCH); + } + + private class ExperimentHandler implements MessageHandler { + + @Override + public void onMessage(MessageContext messageContext) { + MDC.put(MDCConstants.GATEWAY_ID, messageContext.getGatewayId()); + switch (messageContext.getType()) { + case EXPERIMENT: + launchExperiment(messageContext); + break; + case EXPERIMENT_CANCEL: + cancelExperiment(messageContext); + break; + case INTERMEDIATE_OUTPUTS: + handleIntermediateOutputsEvent(messageContext); + break; + default: + experimentSubscriber.sendAck(messageContext.getDeliveryTag()); + logger.error("Orchestrator got un-support message type : " + messageContext.getType()); + break; + } + MDC.clear(); + } + + private void cancelExperiment(MessageContext messageContext) { + try { + byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent()); + ExperimentSubmitEvent expEvent = new ExperimentSubmitEvent(); + ThriftUtils.createThriftFromBytes(bytes, expEvent); + logger.info( + "Cancelling experiment with experimentId: {} gateway Id: {}", + expEvent.getExperimentId(), + expEvent.getGatewayId()); + handleCancelExperiment(expEvent); + } catch (Throwable e) { + logger.error("Error while cancelling experiment", e); + throw new RuntimeException("Error while cancelling experiment", e); + } finally { + experimentSubscriber.sendAck(messageContext.getDeliveryTag()); + } + } + + private void handleIntermediateOutputsEvent(MessageContext messageContext) { + try { + byte[] bytes = ThriftUtils.serializeThriftObject(messageContext.getEvent()); + ExperimentIntermediateOutputsEvent event = new ExperimentIntermediateOutputsEvent(); + ThriftUtils.createThriftFromBytes(bytes, event); + logger.info( + "INTERMEDIATE_OUTPUTS event for experimentId: {} gateway Id: {} outputs: {}", + event.getExperimentId(), + event.getGatewayId(), + event.getOutputNames()); + OrchestratorService.this.handleIntermediateOutputsEvent(event); + } catch (Throwable e) { + logger.error("Error while fetching intermediate outputs", e); + throw new RuntimeException("Error while fetching intermediate outputs", e); + } finally { + experimentSubscriber.sendAck(messageContext.getDeliveryTag()); + } + } + + private void launchExperiment(MessageContext messageContext) { + try { + handleLaunchExperimentFromMessage(messageContext); + } catch (RegistryServiceException e) { + logger.error("Experiment launch failed due to registry error", e); + } catch (TException e) { + logger.error("Experiment launch failed due to Thrift conversion error", e); + } catch (Throwable e) { + logger.error("An unknown issue while launching experiment", e); + } finally { + experimentSubscriber.sendAck(messageContext.getDeliveryTag()); + MDC.clear(); + } + } + } +} diff --git a/airavata-api/src/main/java/org/apache/airavata/service/RegistryService.java b/airavata-api/src/main/java/org/apache/airavata/service/RegistryService.java new file mode 100644 index 0000000000..41ca818211 --- /dev/null +++ b/airavata-api/src/main/java/org/apache/airavata/service/RegistryService.java @@ -0,0 +1,4466 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.airavata.service; + +import java.util.*; +import org.apache.airavata.common.utils.ServerSettings; +import org.apache.airavata.model.appcatalog.appdeployment.ApplicationDeploymentDescription; +import org.apache.airavata.model.appcatalog.appdeployment.ApplicationModule; +import org.apache.airavata.model.appcatalog.appinterface.ApplicationInterfaceDescription; +import org.apache.airavata.model.appcatalog.computeresource.*; +import org.apache.airavata.model.appcatalog.gatewaygroups.GatewayGroups; +import org.apache.airavata.model.appcatalog.gatewayprofile.ComputeResourcePreference; +import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile; +import org.apache.airavata.model.appcatalog.gatewayprofile.StoragePreference; +import org.apache.airavata.model.appcatalog.groupresourceprofile.BatchQueueResourcePolicy; +import org.apache.airavata.model.appcatalog.groupresourceprofile.ComputeResourcePolicy; +import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupComputeResourcePreference; +import org.apache.airavata.model.appcatalog.groupresourceprofile.GroupResourceProfile; +import org.apache.airavata.model.appcatalog.parser.Parser; +import org.apache.airavata.model.appcatalog.parser.ParserInput; +import org.apache.airavata.model.appcatalog.parser.ParserOutput; +import org.apache.airavata.model.appcatalog.parser.ParsingTemplate; +import org.apache.airavata.model.appcatalog.storageresource.StorageResourceDescription; +import org.apache.airavata.model.appcatalog.userresourceprofile.UserComputeResourcePreference; +import org.apache.airavata.model.appcatalog.userresourceprofile.UserResourceProfile; +import org.apache.airavata.model.appcatalog.userresourceprofile.UserStoragePreference; +import org.apache.airavata.model.application.io.InputDataObjectType; +import org.apache.airavata.model.application.io.OutputDataObjectType; +import org.apache.airavata.model.commons.ErrorModel; +import org.apache.airavata.model.data.movement.*; +import org.apache.airavata.model.data.movement.DMType; +import org.apache.airavata.model.data.replica.DataProductModel; +import org.apache.airavata.model.data.replica.DataReplicaLocationModel; +import org.apache.airavata.model.error.*; +import org.apache.airavata.model.experiment.*; +import org.apache.airavata.model.job.JobModel; +import org.apache.airavata.model.process.ProcessModel; +import org.apache.airavata.model.process.ProcessWorkflow; +import org.apache.airavata.model.scheduling.ComputationalResourceSchedulingModel; +import org.apache.airavata.model.status.*; +import org.apache.airavata.model.task.TaskModel; +import org.apache.airavata.model.user.UserProfile; +import org.apache.airavata.model.workspace.Gateway; +import org.apache.airavata.model.workspace.GatewayUsageReportingCommand; +import org.apache.airavata.model.workspace.Notification; +import org.apache.airavata.model.workspace.Project; +import org.apache.airavata.registry.api.exception.RegistryServiceException; +import org.apache.airavata.registry.core.entities.expcatalog.JobPK; +import org.apache.airavata.registry.core.repositories.appcatalog.*; +import org.apache.airavata.registry.core.repositories.appcatalog.GroupResourceProfileRepository; +import org.apache.airavata.registry.core.repositories.appcatalog.GwyResourceProfileRepository; +import org.apache.airavata.registry.core.repositories.expcatalog.*; +import org.apache.airavata.registry.core.repositories.replicacatalog.DataProductRepository; +import org.apache.airavata.registry.core.repositories.replicacatalog.DataReplicaLocationRepository; +import org.apache.airavata.registry.core.repositories.workflowcatalog.WorkflowRepository; +import org.apache.airavata.registry.core.utils.DBConstants; +import org.apache.airavata.registry.cpi.*; +import org.apache.airavata.registry.cpi.ExpCatChildDataType; +import org.apache.airavata.registry.cpi.WorkflowCatalogException; +import org.apache.airavata.registry.cpi.utils.Constants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class RegistryService { + private static final Logger logger = LoggerFactory.getLogger(RegistryService.class); + + private ApplicationDeploymentRepository applicationDeploymentRepository = new ApplicationDeploymentRepository(); + private ApplicationInterfaceRepository applicationInterfaceRepository = new ApplicationInterfaceRepository(); + private StorageResourceRepository storageResourceRepository = new StorageResourceRepository(); + private UserResourceProfileRepository userResourceProfileRepository = new UserResourceProfileRepository(); + private GatewayRepository gatewayRepository = new GatewayRepository(); + private ProjectRepository projectRepository = new ProjectRepository(); + private NotificationRepository notificationRepository = new NotificationRepository(); + private ExperimentSummaryRepository experimentSummaryRepository = new ExperimentSummaryRepository(); + private ExperimentRepository experimentRepository = new ExperimentRepository(); + private ExperimentOutputRepository experimentOutputRepository = new ExperimentOutputRepository(); + private ExperimentStatusRepository experimentStatusRepository = new ExperimentStatusRepository(); + private ExperimentErrorRepository experimentErrorRepository = new ExperimentErrorRepository(); + private ProcessRepository processRepository = new ProcessRepository(); + private ProcessOutputRepository processOutputRepository = new ProcessOutputRepository(); + private ProcessWorkflowRepository processWorkflowRepository = new ProcessWorkflowRepository(); + private ProcessStatusRepository processStatusRepository = new ProcessStatusRepository(); + private ProcessErrorRepository processErrorRepository = new ProcessErrorRepository(); + private TaskRepository taskRepository = new TaskRepository(); + private TaskStatusRepository taskStatusRepository = new TaskStatusRepository(); + private TaskErrorRepository taskErrorRepository = new TaskErrorRepository(); + private JobRepository jobRepository = new JobRepository(); + private JobStatusRepository jobStatusRepository = new JobStatusRepository(); + private QueueStatusRepository queueStatusRepository = new QueueStatusRepository(); + private DataProductRepository dataProductRepository = new DataProductRepository(); + private DataReplicaLocationRepository dataReplicaLocationRepository = new DataReplicaLocationRepository(); + private WorkflowRepository workflowRepository = new WorkflowRepository(); + private GatewayGroupsRepository gatewayGroupsRepository = new GatewayGroupsRepository(); + private ParserRepository parserRepository = new ParserRepository(); + private ParserInputRepository parserInputRepository = new ParserInputRepository(); + private ParserOutputRepository parserOutputRepository = new ParserOutputRepository(); + private ParsingTemplateRepository parsingTemplateRepository = new ParsingTemplateRepository(); + private UserRepository userRepository = new UserRepository(); + private ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + private GatewayUsageReportingCommandRepository usageReportingCommandRepository = + new GatewayUsageReportingCommandRepository(); + + public String getAPIVersion() { + return org.apache.airavata.registry.api.registry_apiConstants.REGISTRY_API_VERSION; + } + + public boolean isUserExists(String gatewayId, String userName) throws RegistryServiceException { + try { + return userRepository.isUserExists(gatewayId, userName); + } catch (Throwable e) { + logger.error("Error while verifying user", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while verifying user More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllUsersInGateway(String gatewayId) throws RegistryServiceException { + try { + return userRepository.getAllUsernamesInGateway(gatewayId); + } catch (Throwable e) { + logger.error("Error while retrieving users", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving users More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public Gateway getGateway(String gatewayId) throws RegistryServiceException { + try { + if (!gatewayRepository.isGatewayExist(gatewayId)) { + logger.error("Gateway does not exist in the system. Please provide a valid gateway ID..."); + throw new RegistryException( + "Gateway does not exist in the system. Please provide a valid gateway ID..."); + } + var gateway = gatewayRepository.getGateway(gatewayId); + logger.debug("Airavata retrieved gateway with gateway id : " + gateway.getGatewayId()); + return gateway; + } catch (Throwable e) { + String msg = "Error while getting the gateway: " + e.getMessage(); + logger.error(msg, e); + var exception = new RegistryServiceException(msg); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteGateway(String gatewayId) throws RegistryServiceException { + try { + if (!gatewayRepository.isGatewayExist(gatewayId)) { + logger.error("Gateway does not exist in the system. Please provide a valid gateway ID..."); + throw new RegistryException( + "Gateway does not exist in the system. Please provide a valid gateway ID..."); + } + gatewayRepository.removeGateway(gatewayId); + logger.debug("Airavata deleted gateway with gateway id : " + gatewayId); + return true; + } catch (Throwable e) { + logger.error("Error while deleting the gateway", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting the gateway More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllGateways() throws RegistryServiceException { + try { + var gateways = gatewayRepository.getAllGateways(); + logger.debug("Airavata retrieved all available gateways..."); + return gateways; + } catch (Throwable e) { + logger.error("Error while getting all the gateways", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting all the gateways More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean isGatewayExist(String gatewayId) throws RegistryServiceException { + try { + return gatewayRepository.isGatewayExist(gatewayId); + } catch (Throwable e) { + logger.error("Error while checking if gateway exists", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while checking if gateway exists More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteNotification(String gatewayId, String notificationId) throws RegistryServiceException { + try { + notificationRepository.deleteNotification(notificationId); + return true; + } catch (Throwable e) { + logger.error("Error while deleting notification", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting notification More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public Notification getNotification(String gatewayId, String notificationId) throws RegistryServiceException { + try { + return notificationRepository.getNotification(notificationId); + } catch (Throwable e) { + logger.error("Error while retrieving notification", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving notification More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllNotifications(String gatewayId) throws RegistryServiceException { + try { + List notifications = notificationRepository.getAllGatewayNotifications(gatewayId); + return notifications; + } catch (Throwable e) { + logger.error("Error while getting all notifications", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting all notifications More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public Project getProject(String projectId) throws RegistryServiceException, ProjectNotFoundException { + try { + if (!projectRepository.isProjectExist(projectId)) { + logger.error("Project does not exist in the system. Please provide a valid project ID..."); + ProjectNotFoundException exception = new ProjectNotFoundException(); + exception.setMessage("Project does not exist in the system. Please provide a valid project ID..."); + throw exception; + } + logger.debug("Airavata retrieved project with project Id : " + projectId); + var project = projectRepository.getProject(projectId); + return project; + } catch (ProjectNotFoundException e) { + throw e; + } catch (Throwable e) { + logger.error("Error while retrieving the project", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving the project More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteProject(String projectId) throws RegistryServiceException, ProjectNotFoundException { + try { + if (!projectRepository.isProjectExist(projectId)) { + logger.error("Project does not exist in the system. Please provide a valid project ID..."); + ProjectNotFoundException exception = new ProjectNotFoundException(); + exception.setMessage("Project does not exist in the system. Please provide a valid project ID..."); + throw exception; + } + projectRepository.removeProject(projectId); + logger.debug("Airavata deleted project with project Id : " + projectId); + return true; + } catch (ProjectNotFoundException e) { + throw e; + } catch (Throwable e) { + logger.error("Error while removing the project", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while removing the project More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getUserProjects(String gatewayId, String userName, int limit, int offset) + throws RegistryServiceException { + try { + if (!validateString(userName)) { + logger.error("Username cannot be empty. Please provide a valid user.."); + throw new RegistryException("Username cannot be empty. Please provide a valid user.."); + } + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new RegistryException("Gateway does not exist.Please provide a valid gateway id..."); + } + List projects = new ArrayList<>(); + if (!userRepository.isUserExists(gatewayId, userName)) { + logger.warn("User does not exist in the system. Please provide a valid user.."); + return projects; + } + Map filters = new HashMap<>(); + filters.put(Constants.FieldConstants.ProjectConstants.OWNER, userName); + filters.put(Constants.FieldConstants.ProjectConstants.GATEWAY_ID, gatewayId); + projects = projectRepository.searchProjects( + filters, + limit, + offset, + Constants.FieldConstants.ProjectConstants.CREATION_TIME, + ResultOrderType.DESC); + logger.debug("Airavata retrieved projects for user : " + userName + " and gateway id : " + gatewayId); + return projects; + } catch (Throwable e) { + logger.error("Error while retrieving projects", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving projects More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ExperimentStatistics getExperimentStatistics( + String gatewayId, + long fromTime, + long toTime, + String userName, + String applicationName, + String resourceHostName, + List accessibleExpIds, + int limit, + int offset) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new RegistryException("Gateway does not exist.Please provide a valid gateway id..."); + } + Map filters = new HashMap<>(); + filters.put(Constants.FieldConstants.ExperimentConstants.GATEWAY_ID, gatewayId); + filters.put(Constants.FieldConstants.ExperimentConstants.FROM_DATE, fromTime + ""); + filters.put(Constants.FieldConstants.ExperimentConstants.TO_DATE, toTime + ""); + if (userName != null) { + filters.put(Constants.FieldConstants.ExperimentConstants.USER_NAME, userName); + } + if (applicationName != null) { + filters.put(Constants.FieldConstants.ExperimentConstants.EXECUTION_ID, applicationName); + } + if (resourceHostName != null) { + filters.put(Constants.FieldConstants.ExperimentConstants.RESOURCE_HOST_ID, resourceHostName); + } + limit = Math.min(limit, 1000); + ExperimentStatistics result = experimentSummaryRepository.getAccessibleExperimentStatistics( + accessibleExpIds, filters, limit, offset); + logger.debug("Airavata retrieved experiments for gateway id : " + gatewayId + " between : " + + org.apache.airavata.common.utils.AiravataUtils.getTime(fromTime) + " and " + + org.apache.airavata.common.utils.AiravataUtils.getTime(toTime)); + return result; + } catch (Throwable e) { + logger.error("Error while getting experiment statistics", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting experiment statistics More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getExperimentsInProject(String gatewayId, String projectId, int limit, int offset) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new RegistryException("Gateway does not exist.Please provide a valid gateway id..."); + } + if (!validateString(projectId)) { + logger.error("Project id cannot be empty. Please provide a valid project ID..."); + throw new RegistryException("Project id cannot be empty. Please provide a valid project ID..."); + } + if (!projectRepository.isProjectExist(projectId)) { + logger.error("Project does not exist in the system. Please provide a valid project ID..."); + throw new RegistryException( + "Project does not exist in the system. Please provide a valid project ID..."); + } + List experiments = experimentRepository.getExperimentList( + gatewayId, + Constants.FieldConstants.ExperimentConstants.PROJECT_ID, + projectId, + limit, + offset, + Constants.FieldConstants.ExperimentConstants.CREATION_TIME, + ResultOrderType.DESC); + logger.debug("Airavata retrieved experiments for project : " + projectId); + return experiments; + } catch (Throwable e) { + logger.error("Error while retrieving the experiments", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving the experiments More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getUserExperiments(String gatewayId, String userName, int limit, int offset) + throws RegistryServiceException { + try { + if (!validateString(userName)) { + logger.error("Username cannot be empty. Please provide a valid user.."); + throw new RegistryException("Username cannot be empty. Please provide a valid user.."); + } + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new RegistryException("Gateway does not exist.Please provide a valid gateway id..."); + } + List experiments = new ArrayList(); + if (!userRepository.isUserExists(gatewayId, userName)) { + logger.warn("User does not exist in the system. Please provide a valid user.."); + return experiments; + } + experiments = experimentRepository.getExperimentList( + gatewayId, + Constants.FieldConstants.ExperimentConstants.USER_NAME, + userName, + limit, + offset, + Constants.FieldConstants.ExperimentConstants.CREATION_TIME, + ResultOrderType.DESC); + logger.debug("Airavata retrieved experiments for user : " + userName); + return experiments; + } catch (Throwable e) { + logger.error("Error while retrieving the experiments", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving the experiments More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteExperiment(String experimentId) throws RegistryServiceException { + try { + if (!experimentRepository.isExperimentExist(experimentId)) { + throw new RegistryException( + "Requested experiment id " + experimentId + " does not exist in the system.."); + } + ExperimentModel experimentModel = experimentRepository.getExperiment(experimentId); + if (!(experimentModel.getExperimentStatus().get(0).getState() == ExperimentState.CREATED)) { + logger.error("Error while deleting the experiment"); + throw new RegistryException( + "Experiment is not in CREATED state. Hence cannot deleted. ID:" + experimentId); + } + experimentRepository.removeExperiment(experimentId); + logger.debug("Airavata removed experiment with experiment id : " + experimentId); + return true; + } catch (Throwable e) { + logger.error("Error while deleting the experiment", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting the experiment More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private ExperimentModel getExperimentInternal(String airavataExperimentId) throws RegistryServiceException { + try { + if (!experimentRepository.isExperimentExist(airavataExperimentId)) { + throw new RegistryException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + return experimentRepository.getExperiment(airavataExperimentId); + } catch (Throwable e) { + logger.error("Error while retrieving the experiment", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving the experiment More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ExperimentModel getExperiment(String airavataExperimentId) throws RegistryServiceException { + return getExperimentInternal(airavataExperimentId); + } + + public ExperimentModel getDetailedExperimentTree(String airavataExperimentId) throws RegistryServiceException { + try { + var experimentModel = getExperimentInternal(airavataExperimentId); + var processList = processRepository.getProcessList( + Constants.FieldConstants.ExperimentConstants.EXPERIMENT_ID, experimentModel.getExperimentId()); + if (processList != null) { + processList.stream().forEach(p -> { + (p).getTasks().stream().forEach(t -> { + try { + var jobList = jobRepository.getJobList( + Constants.FieldConstants.JobConstants.TASK_ID, ((TaskModel) t).getTaskId()); + if (jobList != null) { + Collections.sort(jobList, new Comparator() { + @Override + public int compare(JobModel o1, JobModel o2) { + return (int) (o1.getCreationTime() - o2.getCreationTime()); + } + }); + t.setJobs(jobList); + } + } catch (RegistryException e) { + logger.error(e.getMessage(), e); + } + }); + }); + experimentModel.setProcesses(processList); + } + logger.debug("Airavata retrieved detailed experiment with experiment id : " + airavataExperimentId); + return experimentModel; + } catch (Throwable e) { + logger.error("Error while retrieving the experiment", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving the experiment More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private ExperimentStatus getExperimentStatusInternal(String airavataExperimentId) throws RegistryServiceException { + try { + if (!experimentRepository.isExperimentExist(airavataExperimentId)) { + logger.error( + airavataExperimentId, + "Error while retrieving experiment status, experiment {} doesn't exist.", + airavataExperimentId); + throw new RegistryException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + return experimentStatusRepository.getExperimentStatus(airavataExperimentId); + } catch (Throwable e) { + logger.error("Error while retrieving experiment status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving experiment status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ExperimentStatus getExperimentStatus(String airavataExperimentId) throws RegistryServiceException { + try { + ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); + logger.debug("Airavata retrieved experiment status for experiment id : " + airavataExperimentId); + return experimentStatus; + } catch (Throwable e) { + logger.error("Error while retrieving experiment status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving experiment status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getExperimentOutputs(String airavataExperimentId) + throws RegistryServiceException { + try { + if (!experimentRepository.isExperimentExist(airavataExperimentId)) { + logger.error( + airavataExperimentId, + "Get experiment outputs failed, experiment {} doesn't exit.", + airavataExperimentId); + throw new RegistryException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + logger.debug("Airavata retrieved experiment outputs for experiment id : " + airavataExperimentId); + return experimentOutputRepository.getExperimentOutputs(airavataExperimentId); + } catch (Throwable e) { + logger.error("Error while retrieving the experiment outputs", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving the experiment outputs More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void updateJobStatus(JobStatus jobStatus, String taskId, String jobId) throws RegistryServiceException { + try { + var jobPK = new org.apache.airavata.registry.core.entities.expcatalog.JobPK(); + jobPK.setTaskId(taskId); + jobPK.setJobId(jobId); + jobStatusRepository.updateJobStatus(jobStatus, jobPK); + } catch (Throwable e) { + logger.error("Error while updating job status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating job status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void addJob(JobModel jobModel, String processId) throws RegistryServiceException { + try { + jobRepository.addJob(jobModel, processId); + } catch (Throwable e) { + logger.error("Error while adding job", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding job More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Note: deleteJobs method removed - JobRepository doesn't have this method + // Jobs should be deleted individually using removeJob(jobPK) or removeJob(jobModel) + + public String addProcess(ProcessModel processModel, String experimentId) throws RegistryServiceException { + try { + return processRepository.addProcess(processModel, experimentId); + } catch (Throwable e) { + logger.error("Error while adding process", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding process More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void updateProcess(ProcessModel processModel, String processId) throws RegistryServiceException { + try { + processRepository.updateProcess(processModel, processId); + } catch (Throwable e) { + logger.error("Error while updating process", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating process More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addTask(TaskModel taskModel, String processId) throws RegistryServiceException { + try { + return taskRepository.addTask(taskModel, processId); + } catch (Throwable e) { + logger.error("Error while adding task", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding task More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void deleteTasks(String processId) throws RegistryServiceException { + try { + taskRepository.deleteTasks(processId); + } catch (Throwable e) { + logger.error("Error while deleting tasks", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting tasks More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public UserConfigurationDataModel getUserConfigurationData(String experimentId) throws RegistryServiceException { + try { + return experimentRepository.getUserConfigurationData(experimentId); + } catch (Throwable e) { + logger.error("Error while getting user configuration", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting user configuration More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ProcessModel getProcess(String processId) throws RegistryServiceException { + try { + return processRepository.getProcess(processId); + } catch (Throwable e) { + logger.error("Error while retrieving process", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving process More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getProcessList(String experimentId) throws RegistryServiceException { + try { + var processModels = processRepository.getProcessList( + Constants.FieldConstants.ExperimentConstants.EXPERIMENT_ID, experimentId); + return processModels; + } catch (Throwable e) { + logger.error("Error while retrieving process list", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving process list More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ProcessStatus getProcessStatus(String processId) throws RegistryServiceException { + try { + return processStatusRepository.getProcessStatus(processId); + } catch (Throwable e) { + logger.error("Error while retrieving process status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving process status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getProcessListInState(ProcessState processState) throws RegistryServiceException { + try { + var finalProcessList = new ArrayList(); + int offset = 0; + int limit = 100; + int count = 0; + do { + var processStatusList = processStatusRepository.getProcessStatusList(processState, offset, limit); + offset += processStatusList.size(); + count = processStatusList.size(); + for (ProcessStatus processStatus : processStatusList) { + var latestStatus = processStatusRepository.getProcessStatus(processStatus.getProcessId()); + if (latestStatus.getState().name().equals(processState.name())) { + finalProcessList.add(processRepository.getProcess(latestStatus.getProcessId())); + } + } + } while (count == limit); + return finalProcessList; + } catch (Throwable e) { + logger.error("Error while retrieving process list with given status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving process list with given status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getProcessStatusList(String processId) throws RegistryServiceException { + try { + return processStatusRepository.getProcessStatusList(processId); + } catch (Throwable e) { + logger.error("Error while retrieving process status list for given process Id", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving process status list for given process Id More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private JobModel fetchJobModel(String queryType, String id) throws RegistryServiceException { + try { + if (queryType.equals(Constants.FieldConstants.JobConstants.TASK_ID)) { + var jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.TASK_ID, id); + if (jobs != null) { + for (JobModel jobModel : jobs) { + if (jobModel.getJobId() != null || !jobModel.equals("")) { + return jobModel; + } + } + } + } else if (queryType.equals(Constants.FieldConstants.JobConstants.PROCESS_ID)) { + var jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.PROCESS_ID, id); + if (jobs != null) { + for (JobModel jobModel : jobs) { + if (jobModel.getJobId() != null || !jobModel.equals("")) { + return jobModel; + } + } + } + } + return null; + } catch (Throwable e) { + logger.error("Error while fetching job model", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while fetching job model More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private List fetchJobModels(String queryType, String id) throws RegistryServiceException { + try { + List jobs; + switch (queryType) { + case Constants.FieldConstants.JobConstants.TASK_ID: + jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.TASK_ID, id); + break; + case Constants.FieldConstants.JobConstants.PROCESS_ID: + jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.PROCESS_ID, id); + break; + case Constants.FieldConstants.JobConstants.JOB_ID: + jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.JOB_ID, id); + break; + default: + jobs = new ArrayList<>(); + break; + } + return jobs; + } catch (Throwable e) { + logger.error("Error while fetching job models", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while fetching job models More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean isJobExist(String queryType, String id) throws RegistryServiceException { + JobModel jobModel = fetchJobModel(queryType, id); + return jobModel != null; + } + + public JobModel getJob(String queryType, String id) throws RegistryServiceException { + try { + var jobModel = fetchJobModel(queryType, id); + if (jobModel != null) return jobModel; + throw new RegistryException("Job not found for queryType: " + queryType + ", id: " + id); + } catch (Throwable e) { + logger.error("Error while getting job", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting job More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getJobs(String queryType, String id) throws RegistryServiceException { + try { + return fetchJobModels(queryType, id); + } catch (Throwable e) { + logger.error("Error while getting jobs", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting jobs More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public int getJobCount( + org.apache.airavata.model.status.JobStatus jobStatus, String gatewayId, double searchBackTimeInMinutes) + throws RegistryServiceException { + try { + var jobStatusList = jobStatusRepository.getDistinctListofJobStatus( + gatewayId, jobStatus.getJobState().name(), searchBackTimeInMinutes); + return jobStatusList.size(); + } catch (Throwable e) { + logger.error("Error while getting job count", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting job count More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public Map getAVGTimeDistribution(String gatewayId, double searchBackTimeInMinutes) + throws RegistryServiceException { + try { + return processRepository.getAVGTimeDistribution(gatewayId, searchBackTimeInMinutes); + } catch (Throwable e) { + logger.error("Error while getting average time distribution", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting average time distribution More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getProcessOutputs(String processId) throws RegistryServiceException { + try { + return processOutputRepository.getProcessOutputs(processId); + } catch (Throwable e) { + logger.error("Error while getting process outputs", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting process outputs More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getProcessWorkflows(String processId) throws RegistryServiceException { + try { + return processWorkflowRepository.getProcessWorkflows(processId); + } catch (Throwable e) { + logger.error("Error while getting process workflows", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting process workflows More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void addProcessWorkflow(ProcessWorkflow processWorkflow) throws RegistryServiceException { + try { + processWorkflowRepository.addProcessWorkflow(processWorkflow, processWorkflow.getProcessId()); + } catch (Throwable e) { + logger.error("Error while adding process workflow", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding process workflow More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getProcessIds(String experimentId) throws RegistryServiceException { + try { + return processRepository.getProcessIds(DBConstants.Process.EXPERIMENT_ID, experimentId); + } catch (Throwable e) { + logger.error("Error while getting process ids", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting process ids More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getJobDetails(String airavataExperimentId) throws RegistryServiceException { + try { + if (!experimentRepository.isExperimentExist(airavataExperimentId)) { + logger.error( + airavataExperimentId, + "Error while retrieving job details, experiment {} doesn't exist.", + airavataExperimentId); + throw new RegistryException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + var processModels = processRepository.getProcessList( + Constants.FieldConstants.ProcessConstants.EXPERIMENT_ID, airavataExperimentId); + var jobList = new ArrayList(); + if (processModels != null && !processModels.isEmpty()) { + for (ProcessModel processModel : processModels) { + var tasks = processModel.getTasks(); + if (tasks != null && !tasks.isEmpty()) { + for (TaskModel taskModel : tasks) { + var taskId = taskModel.getTaskId(); + var taskJobs = + jobRepository.getJobList(Constants.FieldConstants.JobConstants.TASK_ID, taskId); + jobList.addAll(taskJobs); + } + } + } + } + logger.debug("Airavata retrieved job models for experiment with experiment id : " + airavataExperimentId); + return jobList; + } catch (Throwable e) { + logger.error("Error while getting job details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting job details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private boolean validateString(String name) { + boolean valid = true; + if (name == null || name.equals("") || name.trim().length() == 0) { + valid = false; + } + return valid; + } + + public boolean isGatewayExistInternal(String gatewayId) throws RegistryServiceException { + try { + return gatewayRepository.isGatewayExist(gatewayId); + } catch (Throwable e) { + logger.error("Error while checking if gateway exists", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while checking if gateway exists More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ApplicationModule getApplicationModule(String appModuleId) throws RegistryServiceException { + try { + var module = applicationInterfaceRepository.getApplicationModule(appModuleId); + logger.debug("Airavata retrieved application module with module id : " + appModuleId); + return module; + } catch (Throwable e) { + logger.error("Error while getting application module", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting application module More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllAppModules(String gatewayId) throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + var moduleList = applicationInterfaceRepository.getAllApplicationModules(gatewayId); + logger.debug("Airavata retrieved modules for gateway id : " + gatewayId); + return moduleList; + } catch (Throwable e) { + logger.error("Error while getting all app modules", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting all app modules More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAccessibleAppModules( + String gatewayId, List accessibleAppIds, List accessibleComputeResourceIds) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + var moduleList = applicationInterfaceRepository.getAccessibleApplicationModules( + gatewayId, accessibleAppIds, accessibleComputeResourceIds); + logger.debug("Airavata retrieved modules for gateway id : " + gatewayId); + return moduleList; + } catch (Throwable e) { + logger.error("Error while getting accessible app modules", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting accessible app modules More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteApplicationModule(String appModuleId) throws RegistryServiceException { + try { + logger.debug("Airavata deleted application module with module id : " + appModuleId); + return applicationInterfaceRepository.removeApplicationModule(appModuleId); + } catch (Throwable e) { + logger.error("Error while deleting application module", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting application module More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ApplicationDeploymentDescription getApplicationDeployment(String appDeploymentId) + throws RegistryServiceException { + try { + var deployement = applicationDeploymentRepository.getApplicationDeployement(appDeploymentId); + logger.debug("Airavata registered application deployment for deployment id : " + appDeploymentId); + return deployement; + } catch (Throwable e) { + logger.error("Error while getting application deployment", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting application deployment More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteApplicationDeployment(String appDeploymentId) throws RegistryServiceException { + try { + applicationDeploymentRepository.removeAppDeployment(appDeploymentId); + logger.debug("Airavata removed application deployment with deployment id : " + appDeploymentId); + return true; + } catch (Throwable e) { + logger.error("Error while deleting application deployment", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting application deployment More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllApplicationDeployments(String gatewayId) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + var deployements = applicationDeploymentRepository.getAllApplicationDeployements(gatewayId); + logger.debug("Airavata retrieved application deployments for gateway id : " + gatewayId); + return deployements; + } catch (Throwable e) { + logger.error("Error while getting all application deployments", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting all application deployments More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAccessibleApplicationDeployments( + String gatewayId, List accessibleAppDeploymentIds, List accessibleComputeResourceIds) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + var deployements = applicationDeploymentRepository.getAccessibleApplicationDeployments( + gatewayId, accessibleAppDeploymentIds, accessibleComputeResourceIds); + logger.debug("Airavata retrieved application deployments for gateway id : " + gatewayId); + return deployements; + } catch (Throwable e) { + logger.error("Error while getting accessible application deployments", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while getting accessible application deployments More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAccessibleApplicationDeploymentsForAppModule( + String gatewayId, + String appModuleId, + List accessibleAppDeploymentIds, + List accessibleComputeResourceIds) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + var deployments = applicationDeploymentRepository.getAccessibleApplicationDeployments( + gatewayId, appModuleId, accessibleAppDeploymentIds, accessibleComputeResourceIds); + return deployments; + } catch (Throwable e) { + logger.error("Error while getting accessible application deployments for app module", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting accessible application deployments for app module More info : " + + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAppModuleDeployedResources(String appModuleId) throws RegistryServiceException { + try { + var appDeployments = new ArrayList(); + var filters = new HashMap(); + filters.put(DBConstants.ApplicationDeployment.APPLICATION_MODULE_ID, appModuleId); + var applicationDeployments = applicationDeploymentRepository.getApplicationDeployments(filters); + for (ApplicationDeploymentDescription description : applicationDeployments) { + appDeployments.add(description.getAppDeploymentId()); + } + logger.debug("Airavata retrieved application deployments for module id : " + appModuleId); + return appDeployments; + } catch (Throwable e) { + logger.error("Error while getting app module deployed resources", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting app module deployed resources More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getApplicationDeployments(String appModuleId) + throws RegistryServiceException { + try { + var filters = new HashMap(); + filters.put(DBConstants.ApplicationDeployment.APPLICATION_MODULE_ID, appModuleId); + var applicationDeployments = applicationDeploymentRepository.getApplicationDeployments(filters); + return applicationDeployments; + } catch (Throwable e) { + logger.error("Error while getting application deployments", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting application deployments More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ApplicationInterfaceDescription getApplicationInterface(String appInterfaceId) + throws RegistryServiceException { + try { + var interfaceDescription = applicationInterfaceRepository.getApplicationInterface(appInterfaceId); + logger.debug("Airavata retrieved application interface with interface id : " + appInterfaceId); + return interfaceDescription; + } catch (Throwable e) { + logger.error("Error while getting application interface", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting application interface More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteApplicationInterface(String appInterfaceId) throws RegistryServiceException { + try { + boolean removeApplicationInterface = + applicationInterfaceRepository.removeApplicationInterface(appInterfaceId); + logger.debug("Airavata removed application interface with interface id : " + appInterfaceId); + return removeApplicationInterface; + } catch (Throwable e) { + logger.error("Error while deleting application interface", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting application interface More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public Map getAllApplicationInterfaceNames(String gatewayId) throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + List allApplicationInterfaces = + applicationInterfaceRepository.getAllApplicationInterfaces(gatewayId); + Map allApplicationInterfacesMap = new HashMap<>(); + if (allApplicationInterfaces != null && !allApplicationInterfaces.isEmpty()) { + for (ApplicationInterfaceDescription interfaceDescription : allApplicationInterfaces) { + allApplicationInterfacesMap.put( + interfaceDescription.getApplicationInterfaceId(), + interfaceDescription.getApplicationName()); + } + } + logger.debug("Airavata retrieved application interfaces for gateway id : " + gatewayId); + return allApplicationInterfacesMap; + } catch (Throwable e) { + logger.error("Error while retrieving all application interface names", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving all application interface names More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllApplicationInterfaces(String gatewayId) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + List interfaces = + applicationInterfaceRepository.getAllApplicationInterfaces(gatewayId); + logger.debug("Airavata retrieved application interfaces for gateway id : " + gatewayId); + return interfaces; + } catch (Throwable e) { + logger.error("Error while retrieving all application interfaces", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving all application interfaces More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getApplicationInputs(String appInterfaceId) throws RegistryServiceException { + try { + List applicationInputs = + applicationInterfaceRepository.getApplicationInputs(appInterfaceId); + logger.debug("Airavata retrieved application inputs for application interface id : " + appInterfaceId); + return applicationInputs; + } catch (Throwable e) { + logger.error("Error while retrieving application inputs", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving application inputs More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private List getApplicationOutputsInternal(String appInterfaceId) + throws RegistryServiceException { + try { + List applicationOutputs = + applicationInterfaceRepository.getApplicationOutputs(appInterfaceId); + logger.debug("Airavata retrieved application outputs for application interface id : " + appInterfaceId); + return applicationOutputs; + } catch (Throwable e) { + logger.error("Error while retrieving application outputs", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving application outputs More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getApplicationOutputs(String appInterfaceId) throws RegistryServiceException { + try { + List list = getApplicationOutputsInternal(appInterfaceId); + logger.debug("Airavata retrieved application outputs for app interface id : " + appInterfaceId); + return list; + } catch (Throwable e) { + logger.error("Error while retrieving application outputs", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving application outputs More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public Map getAvailableAppInterfaceComputeResources(String appInterfaceId) + throws RegistryServiceException { + try { + Map allComputeResources = + new ComputeResourceRepository().getAvailableComputeResourceIdList(); + Map availableComputeResources = new HashMap(); + ApplicationInterfaceDescription applicationInterface = + applicationInterfaceRepository.getApplicationInterface(appInterfaceId); + HashMap filters = new HashMap<>(); + List applicationModules = applicationInterface.getApplicationModules(); + if (applicationModules != null && !applicationModules.isEmpty()) { + for (String moduleId : applicationModules) { + filters.put(DBConstants.ApplicationDeployment.APPLICATION_MODULE_ID, moduleId); + List applicationDeployments = + applicationDeploymentRepository.getApplicationDeployments(filters); + for (ApplicationDeploymentDescription deploymentDescription : applicationDeployments) { + if (allComputeResources.get(deploymentDescription.getComputeHostId()) != null) { + availableComputeResources.put( + deploymentDescription.getComputeHostId(), + allComputeResources.get(deploymentDescription.getComputeHostId())); + } + } + } + } + logger.debug( + "Airavata retrieved available compute resources for application interface id : " + appInterfaceId); + return availableComputeResources; + } catch (Throwable e) { + logger.error("Error while retrieving available app interface compute resources", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving available app interface compute resources More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ComputeResourceDescription getComputeResource(String computeResourceId) throws RegistryServiceException { + try { + ComputeResourceDescription computeResource = + new ComputeResourceRepository().getComputeResource(computeResourceId); + logger.debug("Airavata retrieved compute resource with compute resource Id : " + computeResourceId); + return computeResource; + } catch (Throwable e) { + logger.error("Error while retrieving compute resource", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving compute resource More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public Map getAllComputeResourceNames() throws RegistryServiceException { + try { + Map computeResourceIdList = new ComputeResourceRepository().getAllComputeResourceIdList(); + logger.debug("Airavata retrieved all the available compute resources..."); + return computeResourceIdList; + } catch (Throwable e) { + logger.error("Error while retrieving all compute resource names", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving all compute resource names More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteComputeResource(String computeResourceId) throws RegistryServiceException { + try { + new ComputeResourceRepository().removeComputeResource(computeResourceId); + logger.debug("Airavata deleted compute resource with compute resource Id : " + computeResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while deleting compute resource", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting compute resource More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public StorageResourceDescription getStorageResource(String storageResourceId) throws RegistryServiceException { + try { + StorageResourceDescription storageResource = + storageResourceRepository.getStorageResource(storageResourceId); + logger.debug("Airavata retrieved storage resource with storage resource Id : " + storageResourceId); + return storageResource; + } catch (Throwable e) { + logger.error("Error while retrieving storage resource", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving storage resource More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public Map getAllStorageResourceNames() throws RegistryServiceException { + try { + Map resourceIdList = storageResourceRepository.getAllStorageResourceIdList(); + logger.debug("Airavata retrieved storage resources list..."); + return resourceIdList; + } catch (Throwable e) { + logger.error("Error while retrieving all storage resource names", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving all storage resource names More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteStorageResource(String storageResourceId) throws RegistryServiceException { + try { + storageResourceRepository.removeStorageResource(storageResourceId); + logger.debug("Airavata deleted storage resource with storage resource Id : " + storageResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while deleting storage resource", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting storage resource More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public LOCALSubmission getLocalJobSubmission(String jobSubmissionId) throws RegistryServiceException { + try { + LOCALSubmission localJobSubmission = new ComputeResourceRepository().getLocalJobSubmission(jobSubmissionId); + logger.debug("Airavata retrieved local job submission for job submission interface id: " + jobSubmissionId); + return localJobSubmission; + } catch (Throwable e) { + logger.error("Error while retrieving local job submission", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving local job submission More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public SSHJobSubmission getSSHJobSubmission(String jobSubmissionId) throws RegistryServiceException { + try { + SSHJobSubmission sshJobSubmission = new ComputeResourceRepository().getSSHJobSubmission(jobSubmissionId); + logger.debug("Airavata retrieved SSH job submission for job submission interface id: " + jobSubmissionId); + return sshJobSubmission; + } catch (Throwable e) { + logger.error("Error while retrieving SSH job submission", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving SSH job submission More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public UnicoreJobSubmission getUnicoreJobSubmission(String jobSubmissionId) throws RegistryServiceException { + try { + UnicoreJobSubmission unicoreJobSubmission = + new ComputeResourceRepository().getUNICOREJobSubmission(jobSubmissionId); + logger.debug( + "Airavata retrieved UNICORE job submission for job submission interface id: " + jobSubmissionId); + return unicoreJobSubmission; + } catch (Throwable e) { + logger.error("Error while retrieving UNICORE job submission", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving UNICORE job submission More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public CloudJobSubmission getCloudJobSubmission(String jobSubmissionId) throws RegistryServiceException { + try { + CloudJobSubmission cloudJobSubmission = + new ComputeResourceRepository().getCloudJobSubmission(jobSubmissionId); + logger.debug("Airavata retrieved cloud job submission for job submission interface id: " + jobSubmissionId); + return cloudJobSubmission; + } catch (Throwable e) { + logger.error("Error while retrieving cloud job submission", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving cloud job submission More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean changeJobSubmissionPriority(String jobSubmissionInterfaceId, int newPriorityOrder) + throws RegistryServiceException { + return false; + } + + public boolean changeDataMovementPriority(String dataMovementInterfaceId, int newPriorityOrder) + throws RegistryServiceException { + return false; + } + + public boolean changeJobSubmissionPriorities(Map jobSubmissionPriorityMap) + throws RegistryServiceException { + return false; + } + + public boolean changeDataMovementPriorities(Map dataMovementPriorityMap) + throws RegistryServiceException { + return false; + } + + public boolean deleteJobSubmissionInterface(String computeResourceId, String jobSubmissionInterfaceId) + throws RegistryServiceException { + try { + new ComputeResourceRepository().removeJobSubmissionInterface(computeResourceId, jobSubmissionInterfaceId); + logger.debug("Airavata deleted job submission interface with interface id : " + jobSubmissionInterfaceId); + return true; + } catch (Throwable e) { + logger.error("Error while deleting job submission interface", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting job submission interface More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ResourceJobManager getResourceJobManager(String resourceJobManagerId) throws RegistryServiceException { + try { + return new ComputeResourceRepository().getResourceJobManager(resourceJobManagerId); + } catch (Throwable e) { + logger.error("Error while retrieving resource job manager", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving resource job manager More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteResourceJobManager(String resourceJobManagerId) throws RegistryServiceException { + try { + new ComputeResourceRepository().deleteResourceJobManager(resourceJobManagerId); + return true; + } catch (Throwable e) { + logger.error("Error while deleting resource job manager", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting resource job manager More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteBatchQueue(String computeResourceId, String queueName) throws RegistryServiceException { + try { + new ComputeResourceRepository().removeBatchQueue(computeResourceId, queueName); + return true; + } catch (Throwable e) { + logger.error("Error while deleting batch queue", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting batch queue More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public GatewayResourceProfile getGatewayResourceProfile(String gatewayID) throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + GatewayResourceProfile gatewayResourceProfile = gwyResourceProfileRepository.getGatewayProfile(gatewayID); + logger.debug("Airavata retrieved gateway profile with gateway id : " + gatewayID); + return gatewayResourceProfile; + } catch (Throwable e) { + logger.error("Error while retrieving gateway resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving gateway resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteGatewayResourceProfile(String gatewayID) throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + gwyResourceProfileRepository.delete(gatewayID); + logger.debug("Airavata deleted gateway profile with gateway id : " + gatewayID); + return true; + } catch (Throwable e) { + logger.error("Error while deleting gateway resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting gateway resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ComputeResourcePreference getGatewayComputeResourcePreference(String gatewayID, String computeResourceId) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + if (!gwyResourceProfileRepository.isGatewayResourceProfileExists(gatewayID)) { + logger.error( + gatewayID, + "Given gateway profile does not exist in the system. Please provide a valid gateway id..."); + throw new AppCatalogException( + "Given gateway profile does not exist in the system. Please provide a valid gateway id..."); + } + if (!computeResourceRepository.isComputeResourceExists(computeResourceId)) { + logger.error( + computeResourceId, + "Given compute resource does not exist in the system. Please provide a valid compute resource id..."); + throw new AppCatalogException( + "Given compute resource does not exist in the system. Please provide a valid compute resource id..."); + } + ComputeResourcePreference computeResourcePreference = + gwyResourceProfileRepository.getComputeResourcePreference(gatewayID, computeResourceId); + logger.debug("Airavata retrieved gateway compute resource preference with gateway id : " + gatewayID + + " and for compute resoruce id : " + computeResourceId); + return computeResourcePreference; + } catch (Throwable e) { + logger.error("Error while retrieving gateway compute resource preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving gateway compute resource preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public StoragePreference getGatewayStoragePreference(String gatewayID, String storageId) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + if (!gwyResourceProfileRepository.isGatewayResourceProfileExists(gatewayID)) { + logger.error( + gatewayID, + "Given gateway profile does not exist in the system. Please provide a valid gateway id..."); + throw new AppCatalogException( + "Given gateway profile does not exist in the system. Please provide a valid gateway id..."); + } + StoragePreference storagePreference = + gwyResourceProfileRepository.getStoragePreference(gatewayID, storageId); + logger.debug("Airavata retrieved storage resource preference with gateway id : " + gatewayID + + " and for storage resource id : " + storageId); + return storagePreference; + } catch (Throwable e) { + logger.error("Error while retrieving gateway storage preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving gateway storage preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllGatewayComputeResourcePreferences(String gatewayID) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + return gwyResourceProfileRepository.getGatewayProfile(gatewayID).getComputeResourcePreferences(); + } catch (Throwable e) { + logger.error("Error while retrieving all gateway compute resource preferences", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving all gateway compute resource preferences More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllGatewayStoragePreferences(String gatewayID) throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + return gwyResourceProfileRepository.getGatewayProfile(gatewayID).getStoragePreferences(); + } catch (Throwable e) { + logger.error("Error while retrieving all gateway storage preferences", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving all gateway storage preferences More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllGatewayResourceProfiles() throws RegistryServiceException { + try { + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + return gwyResourceProfileRepository.getAllGatewayProfiles(); + } catch (Throwable e) { + logger.error("Error while retrieving all gateway resource profiles", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving all gateway resource profiles More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteGatewayComputeResourcePreference(String gatewayID, String computeResourceId) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + return gwyResourceProfileRepository.removeComputeResourcePreferenceFromGateway( + gatewayID, computeResourceId); + } catch (Throwable e) { + logger.error("Error while deleting gateway compute resource preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while deleting gateway compute resource preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteGatewayStoragePreference(String gatewayID, String storageId) throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + return gwyResourceProfileRepository.removeDataStoragePreferenceFromGateway(gatewayID, storageId); + } catch (Throwable e) { + logger.error("Error while deleting gateway storage preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting gateway storage preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public DataProductModel getDataProduct(String productUri) throws RegistryServiceException { + try { + DataProductModel dataProductModel = dataProductRepository.getDataProduct(productUri); + return dataProductModel; + } catch (Throwable e) { + logger.error("Error while retrieving data product", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving data product More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public DataProductModel getParentDataProduct(String productUri) throws RegistryServiceException { + try { + DataProductModel dataProductModel = dataProductRepository.getParentDataProduct(productUri); + return dataProductModel; + } catch (Throwable e) { + logger.error("Error while retrieving parent data product", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving parent data product More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getChildDataProducts(String productUri) throws RegistryServiceException { + try { + List dataProductModels = dataProductRepository.getChildDataProducts(productUri); + return dataProductModels; + } catch (Throwable e) { + logger.error("Error while retrieving child data products", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving child data products More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List searchDataProductsByName( + String gatewayId, String userId, String productName, int limit, int offset) + throws RegistryServiceException { + try { + List dataProductModels = + dataProductRepository.searchDataProductsByName(gatewayId, userId, productName, limit, offset); + return dataProductModels; + } catch (Throwable e) { + logger.error("Error while searching data products by name", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while searching data products by name More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String createGroupResourceProfile(GroupResourceProfile groupResourceProfile) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(groupResourceProfile.getGatewayId())) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + String groupResourceProfileId = + groupResourceProfileRepository.addGroupResourceProfile(groupResourceProfile); + logger.debug("New Group Resource Profile Created: " + groupResourceProfileId); + return groupResourceProfileId; + } catch (Throwable e) { + logger.error("Error while creating group resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while creating group resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void updateGroupResourceProfile(GroupResourceProfile groupResourceProfile) throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + if (!groupResourceProfileRepository.isGroupResourceProfileExists( + groupResourceProfile.getGroupResourceProfileId())) { + logger.error( + "Cannot update. No group resource profile found with matching gatewayId and groupResourceProfileId"); + throw new AppCatalogException( + "Cannot update. No group resource profile found with matching gatewayId and groupResourceProfileId"); + } + String groupResourceProfileId = + groupResourceProfileRepository.updateGroupResourceProfile(groupResourceProfile); + logger.debug(" Group Resource Profile updated: " + groupResourceProfileId); + } catch (Throwable e) { + logger.error("Error while updating group resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating group resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public GroupResourceProfile getGroupResourceProfile(String groupResourceProfileId) throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + if (!groupResourceProfileRepository.isGroupResourceProfileExists(groupResourceProfileId)) { + logger.error("No group resource profile found with matching gatewayId and groupResourceProfileId"); + throw new AppCatalogException( + "No group resource profile found with matching gatewayId and groupResourceProfileId"); + } + return groupResourceProfileRepository.getGroupResourceProfile(groupResourceProfileId); + } catch (Throwable e) { + logger.error("Error while retrieving group resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving group resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean isGroupResourceProfileExists(String groupResourceProfileId) throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + return groupResourceProfileRepository.isGroupResourceProfileExists(groupResourceProfileId); + } catch (Throwable e) { + logger.error("Error while checking if group resource profile exists", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while checking if group resource profile exists More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean removeGroupResourceProfile(String groupResourceProfileId) throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + if (!groupResourceProfileRepository.isGroupResourceProfileExists(groupResourceProfileId)) { + logger.error( + "Cannot Remove. No group resource profile found with matching gatewayId and groupResourceProfileId"); + throw new AppCatalogException( + "Cannot Remove. No group resource profile found with matching gatewayId and groupResourceProfileId"); + } + return groupResourceProfileRepository.removeGroupResourceProfile(groupResourceProfileId); + } catch (Throwable e) { + logger.error("Error while removing group resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while removing group resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getGroupResourceList(String gatewayId, List accessibleGroupResProfileIds) + throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + return groupResourceProfileRepository.getAllGroupResourceProfiles(gatewayId, accessibleGroupResProfileIds); + } catch (Throwable e) { + logger.error("Error while retrieving group resource list", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving group resource list More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean removeGroupComputePrefs(String computeResourceId, String groupResourceProfileId) + throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + groupResourceProfileRepository.removeGroupComputeResourcePreference( + computeResourceId, groupResourceProfileId); + logger.debug("Removed compute resource preferences with compute resource ID: " + computeResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while removing group compute preferences", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while removing group compute preferences More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean removeGroupComputeResourcePolicy(String resourcePolicyId) throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + groupResourceProfileRepository.removeComputeResourcePolicy(resourcePolicyId); + logger.debug("Removed compute resource policy with resource policy ID: " + resourcePolicyId); + return true; + } catch (Throwable e) { + logger.error("Error while removing group compute resource policy", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while removing group compute resource policy More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean removeGroupBatchQueueResourcePolicy(String resourcePolicyId) throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + groupResourceProfileRepository.removeBatchQueueResourcePolicy(resourcePolicyId); + logger.debug("Removed batch resource policy with resource policy ID: " + resourcePolicyId); + return true; + } catch (Throwable e) { + logger.error("Error while removing group batch queue resource policy", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while removing group batch queue resource policy More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public GroupComputeResourcePreference getGroupComputeResourcePreference( + String computeResourceId, String groupResourceProfileId) throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + GroupComputeResourcePreference groupComputeResourcePreference = + groupResourceProfileRepository.getGroupComputeResourcePreference( + computeResourceId, groupResourceProfileId); + if (!(groupComputeResourcePreference != null)) { + logger.error("GroupComputeResourcePreference not found"); + throw new AppCatalogException("GroupComputeResourcePreference not found "); + } + return groupComputeResourcePreference; + } catch (Throwable e) { + logger.error("Error while retrieving group compute resource preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving group compute resource preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean isGroupComputeResourcePreferenceExists(String computeResourceId, String groupResourceProfileId) + throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + return groupResourceProfileRepository.isGroupComputeResourcePreferenceExists( + computeResourceId, groupResourceProfileId); + } catch (Throwable e) { + logger.error("Error while checking if group compute resource preference exists", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while checking if group compute resource preference exists More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ComputeResourcePolicy getGroupComputeResourcePolicy(String resourcePolicyId) + throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + ComputeResourcePolicy computeResourcePolicy = + groupResourceProfileRepository.getComputeResourcePolicy(resourcePolicyId); + if (!(computeResourcePolicy != null)) { + logger.error("Group Compute Resource policy not found"); + throw new AppCatalogException("Group Compute Resource policy not found "); + } + return computeResourcePolicy; + } catch (Throwable e) { + logger.error("Error while retrieving group compute resource policy", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving group compute resource policy More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public BatchQueueResourcePolicy getBatchQueueResourcePolicy(String resourcePolicyId) + throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + BatchQueueResourcePolicy batchQueueResourcePolicy = + groupResourceProfileRepository.getBatchQueueResourcePolicy(resourcePolicyId); + if (!(batchQueueResourcePolicy != null)) { + logger.error("Group Batch Queue Resource policy not found"); + throw new AppCatalogException("Group Batch Queue Resource policy not found "); + } + return batchQueueResourcePolicy; + } catch (Throwable e) { + logger.error("Error while retrieving batch queue resource policy", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving batch queue resource policy More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getGroupComputeResourcePrefList(String groupResourceProfileId) + throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + return groupResourceProfileRepository.getAllGroupComputeResourcePreferences(groupResourceProfileId); + } catch (Throwable e) { + logger.error("Error while retrieving group compute resource preference list", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving group compute resource preference list More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getGroupBatchQueueResourcePolicyList(String groupResourceProfileId) + throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + return groupResourceProfileRepository.getAllGroupBatchQueueResourcePolicies(groupResourceProfileId); + } catch (Throwable e) { + logger.error("Error while retrieving group batch queue resource policy list", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving group batch queue resource policy list More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getGroupComputeResourcePolicyList(String groupResourceProfileId) + throws RegistryServiceException { + try { + GroupResourceProfileRepository groupResourceProfileRepository = new GroupResourceProfileRepository(); + return groupResourceProfileRepository.getAllGroupComputeResourcePolicies(groupResourceProfileId); + } catch (Throwable e) { + logger.error("Error while retrieving group compute resource policy list", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving group compute resource policy list More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String registerReplicaLocation(DataReplicaLocationModel replicaLocationModel) + throws RegistryServiceException { + try { + String replicaId = dataReplicaLocationRepository.registerReplicaLocation(replicaLocationModel); + return replicaId; + } catch (Throwable e) { + logger.error("Error in retreiving the replica " + replicaLocationModel.getReplicaName(), e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error in retreiving the replica " + replicaLocationModel.getReplicaName() + + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String registerDataProduct(DataProductModel dataProductModel) throws RegistryServiceException { + try { + String productUrl = dataProductRepository.registerDataProduct(dataProductModel); + return productUrl; + } catch (Throwable e) { + logger.error("Error in registering the data resource" + dataProductModel.getProductName(), e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error in registering the data resource" + dataProductModel.getProductName() + + " More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public LOCALDataMovement getLocalDataMovement(String dataMovementId) throws RegistryServiceException { + try { + LOCALDataMovement localDataMovement = new ComputeResourceRepository().getLocalDataMovement(dataMovementId); + logger.debug("Airavata retrieved local data movement with data movement id: " + dataMovementId); + return localDataMovement; + } catch (Throwable e) { + logger.error("Error while retrieving local data movement", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving local data movement More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public SCPDataMovement getSCPDataMovement(String dataMovementId) throws RegistryServiceException { + try { + SCPDataMovement scpDataMovement = new ComputeResourceRepository().getSCPDataMovement(dataMovementId); + logger.debug("Airavata retrieved SCP data movement with data movement id: " + dataMovementId); + return scpDataMovement; + } catch (Throwable e) { + logger.error("Error while retrieving SCP data movement", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving SCP data movement More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public UnicoreDataMovement getUnicoreDataMovement(String dataMovementId) throws RegistryServiceException { + try { + UnicoreDataMovement unicoreDataMovement = + new ComputeResourceRepository().getUNICOREDataMovement(dataMovementId); + logger.debug("Airavata retrieved UNICORE data movement with data movement id: " + dataMovementId); + return unicoreDataMovement; + } catch (Throwable e) { + logger.error("Error while retrieving UNICORE data movement", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving UNICORE data movement More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public GridFTPDataMovement getGridFTPDataMovement(String dataMovementId) throws RegistryServiceException { + try { + GridFTPDataMovement gridFTPDataMovement = + new ComputeResourceRepository().getGridFTPDataMovement(dataMovementId); + logger.debug("Airavata retrieved GRIDFTP data movement with data movement id: " + dataMovementId); + return gridFTPDataMovement; + } catch (Throwable e) { + logger.error("Error while retrieving GRIDFTP data movement", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving GRIDFTP data movement More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Experiment operations + public String createExperiment(String gatewayId, ExperimentModel experiment) throws RegistryServiceException { + try { + if (!validateString(experiment.getExperimentName())) { + logger.error("Cannot create experiments with empty experiment name"); + throw new RegistryException("Cannot create experiments with empty experiment name"); + } + logger.info("Creating experiment with name " + experiment.getExperimentName()); + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new RegistryException("Gateway does not exist.Please provide a valid gateway id..."); + } + + if (experiment.getUserConfigurationData() != null + && experiment.getUserConfigurationData().getComputationalResourceScheduling() != null + && experiment + .getUserConfigurationData() + .getComputationalResourceScheduling() + .getResourceHostId() + != null) { + + String compResourceId = experiment + .getUserConfigurationData() + .getComputationalResourceScheduling() + .getResourceHostId(); + try { + ComputeResourceDescription computeResourceDescription = + new ComputeResourceRepository().getComputeResource(compResourceId); + if (!computeResourceDescription.isEnabled()) { + logger.error("Compute Resource is not enabled by the Admin!"); + throw new RegistryException("Compute Resource is not enabled by the Admin!"); + } + } catch (AppCatalogException e) { + throw new RegistryException("Error checking compute resource: " + e.getMessage(), e); + } + } else if (experiment.getUserConfigurationData() != null + && !experiment + .getUserConfigurationData() + .getAutoScheduledCompResourceSchedulingList() + .isEmpty()) { + for (ComputationalResourceSchedulingModel computationalResourceScheduling : + experiment.getUserConfigurationData().getAutoScheduledCompResourceSchedulingList()) { + try { + ComputeResourceDescription computeResourceDescription = new ComputeResourceRepository() + .getComputeResource(computationalResourceScheduling.getResourceHostId()); + if (!computeResourceDescription.isEnabled()) { + logger.error( + "Compute Resource with id" + computationalResourceScheduling.getResourceHostId() + + "" + " is not enabled by the Admin!"); + throw new RegistryException( + "Compute Resource with id" + computationalResourceScheduling.getResourceHostId() + + "" + " is not enabled by the Admin!"); + } + } catch (AppCatalogException e) { + throw new RegistryException("Error checking compute resource: " + e.getMessage(), e); + } + } + } + + experiment.setGatewayId(gatewayId); + String experimentId = experimentRepository.addExperiment(experiment); + if (experiment.getExperimentType() == ExperimentType.WORKFLOW) { + try { + workflowRepository.registerWorkflow(experiment.getWorkflow(), experimentId); + } catch (WorkflowCatalogException e) { + throw new RegistryException("Error registering workflow: " + e.getMessage(), e); + } + } + logger.debug( + experimentId, "Created new experiment with experiment name {}", experiment.getExperimentName()); + return experimentId; + } catch (Throwable e) { + logger.error("Error while creating experiment", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while creating experiment More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List searchExperiments( + String gatewayId, + String userName, + List accessibleExpIds, + Map filters, + int limit, + int offset) + throws RegistryServiceException { + try { + if (!validateString(userName)) { + logger.error("Username cannot be empty. Please provide a valid user.."); + throw new RegistryException("Username cannot be empty. Please provide a valid user.."); + } + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new RegistryException("Gateway does not exist.Please provide a valid gateway id..."); + } + if (!userRepository.isUserExists(gatewayId, userName)) { + logger.error("User does not exist in the system. Please provide a valid user.."); + throw new RegistryException("User does not exist in the system. Please provide a valid user.."); + } + List summaries = new ArrayList(); + Map regFilters = new HashMap(); + regFilters.put(Constants.FieldConstants.ExperimentConstants.GATEWAY_ID, gatewayId); + for (Map.Entry entry : filters.entrySet()) { + if (entry.getKey().equals(ExperimentSearchFields.EXPERIMENT_NAME)) { + regFilters.put(Constants.FieldConstants.ExperimentConstants.EXPERIMENT_NAME, entry.getValue()); + } else if (entry.getKey().equals(ExperimentSearchFields.EXPERIMENT_DESC)) { + regFilters.put(Constants.FieldConstants.ExperimentConstants.DESCRIPTION, entry.getValue()); + } else if (entry.getKey().equals(ExperimentSearchFields.APPLICATION_ID)) { + regFilters.put(Constants.FieldConstants.ExperimentConstants.EXECUTION_ID, entry.getValue()); + } else if (entry.getKey().equals(ExperimentSearchFields.STATUS)) { + regFilters.put(Constants.FieldConstants.ExperimentConstants.EXPERIMENT_STATUS, entry.getValue()); + } else if (entry.getKey().equals(ExperimentSearchFields.FROM_DATE)) { + regFilters.put(Constants.FieldConstants.ExperimentConstants.FROM_DATE, entry.getValue()); + } else if (entry.getKey().equals(ExperimentSearchFields.TO_DATE)) { + regFilters.put(Constants.FieldConstants.ExperimentConstants.TO_DATE, entry.getValue()); + } else if (entry.getKey().equals(ExperimentSearchFields.PROJECT_ID)) { + regFilters.put(Constants.FieldConstants.ExperimentConstants.PROJECT_ID, entry.getValue()); + } else if (entry.getKey().equals(ExperimentSearchFields.USER_NAME)) { + regFilters.put(Constants.FieldConstants.ExperimentConstants.USER_NAME, entry.getValue()); + } else if (entry.getKey().equals(ExperimentSearchFields.JOB_ID)) { + regFilters.put(Constants.FieldConstants.JobConstants.JOB_ID, entry.getValue()); + } + } + + try { + if (accessibleExpIds.size() == 0 && !ServerSettings.isEnableSharing()) { + if (!regFilters.containsKey(DBConstants.Experiment.USER_NAME)) { + regFilters.put(DBConstants.Experiment.USER_NAME, userName); + } + } + } catch (Exception e) { + logger.warn("Error checking sharing settings, continuing without filter", e); + } + summaries = experimentSummaryRepository.searchAllAccessibleExperiments( + accessibleExpIds, + regFilters, + limit, + offset, + Constants.FieldConstants.ExperimentConstants.CREATION_TIME, + ResultOrderType.DESC); + logger.debug("Airavata retrieved experiments for user : " + userName + " and gateway id : " + gatewayId); + return summaries; + } catch (Throwable e) { + logger.error("Error while searching experiments", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while searching experiments More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void updateExperiment(String airavataExperimentId, ExperimentModel experiment) + throws RegistryServiceException { + try { + if (!experimentRepository.isExperimentExist(airavataExperimentId)) { + logger.error( + airavataExperimentId, + "Update request failed, Experiment {} doesn't exist.", + airavataExperimentId); + throw new RegistryException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + + ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); + if (experimentStatus != null) { + ExperimentState experimentState = experimentStatus.getState(); + switch (experimentState) { + case CREATED: + case SCHEDULED: + case VALIDATED: + if (experiment.getUserConfigurationData() != null + && experiment.getUserConfigurationData().getComputationalResourceScheduling() != null + && experiment + .getUserConfigurationData() + .getComputationalResourceScheduling() + .getResourceHostId() + != null) { + String compResourceId = experiment + .getUserConfigurationData() + .getComputationalResourceScheduling() + .getResourceHostId(); + try { + ComputeResourceDescription computeResourceDescription = + new ComputeResourceRepository().getComputeResource(compResourceId); + if (!computeResourceDescription.isEnabled()) { + logger.error("Compute Resource is not enabled by the Admin!"); + throw new RegistryException("Compute Resource is not enabled by the Admin!"); + } + } catch (AppCatalogException e) { + throw new RegistryException("Error checking compute resource: " + e.getMessage(), e); + } + } + experimentRepository.updateExperiment(experiment, airavataExperimentId); + logger.debug( + airavataExperimentId, + "Successfully updated experiment {} ", + experiment.getExperimentName()); + break; + default: + logger.error( + airavataExperimentId, + "Error while updating experiment. Update experiment is only valid for experiments " + + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + + "experiment is in one of above statuses... "); + throw new RegistryException( + "Error while updating experiment. Update experiment is only valid for experiments " + + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + + "experiment is in one of above statuses... "); + } + } + } catch (Throwable e) { + logger.error("Error while updating experiment", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating experiment More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void updateExperimentConfiguration(String airavataExperimentId, UserConfigurationDataModel userConfiguration) + throws RegistryServiceException { + try { + if (!experimentRepository.isExperimentExist(airavataExperimentId)) { + logger.error( + airavataExperimentId, + "Update experiment configuration failed, experiment {} doesn't exist.", + airavataExperimentId); + throw new RegistryException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); + if (experimentStatus != null) { + ExperimentState experimentState = experimentStatus.getState(); + switch (experimentState) { + case CREATED: + case VALIDATED: + case CANCELED: + case FAILED: + experimentRepository.addUserConfigurationData(userConfiguration, airavataExperimentId); + logger.debug( + airavataExperimentId, + "Successfully updated experiment configuration for experiment {}.", + airavataExperimentId); + break; + default: + logger.error( + airavataExperimentId, + "Error while updating experiment {}. Update experiment is only valid for experiments " + + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + + "experiment is in one of above statuses... ", + airavataExperimentId); + throw new RegistryException( + "Error while updating experiment. Update experiment is only valid for experiments " + + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + + "experiment is in one of above statuses... "); + } + } + } catch (Throwable e) { + logger.error("Error while updating experiment configuration", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating experiment configuration More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getIntermediateOutputs(String airavataExperimentId) + throws RegistryServiceException { + try { + if (!experimentRepository.isExperimentExist(airavataExperimentId)) { + logger.error( + airavataExperimentId, + "Error while retrieving intermediate outputs, experiment {} doesn't exist.", + airavataExperimentId); + throw new RegistryException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + List processModels = processRepository.getProcessList( + Constants.FieldConstants.ExperimentConstants.EXPERIMENT_ID, airavataExperimentId); + List intermediateOutputs = new ArrayList<>(); + if (processModels != null && !processModels.isEmpty()) { + for (ProcessModel processModel : processModels) { + List processOutputs = + processOutputRepository.getProcessOutputs(processModel.getProcessId()); + if (processOutputs != null && !processOutputs.isEmpty()) { + intermediateOutputs.addAll(processOutputs); + } + } + } + logger.debug("Airavata retrieved intermediate outputs for experiment with experiment id : " + + airavataExperimentId); + return intermediateOutputs; + } catch (Throwable e) { + logger.error("Error while retrieving intermediate outputs", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving intermediate outputs More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public Map getJobStatuses(String airavataExperimentId) throws RegistryServiceException { + try { + if (!experimentRepository.isExperimentExist(airavataExperimentId)) { + logger.error( + airavataExperimentId, + "Error while retrieving job statuses, experiment {} doesn't exist.", + airavataExperimentId); + throw new RegistryException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + Map jobStatus = new HashMap<>(); + List processModels = processRepository.getProcessList( + Constants.FieldConstants.ExperimentConstants.EXPERIMENT_ID, airavataExperimentId); + if (processModels != null && !processModels.isEmpty()) { + for (ProcessModel processModel : processModels) { + List tasks = processModel.getTasks(); + if (tasks != null && !tasks.isEmpty()) { + for (TaskModel taskModel : tasks) { + String taskId = taskModel.getTaskId(); + List taskJobs = + jobRepository.getJobList(Constants.FieldConstants.JobConstants.TASK_ID, taskId); + if (taskJobs != null && !taskJobs.isEmpty()) { + for (JobModel jobModel : taskJobs) { + JobPK jobPK = new JobPK(); + jobPK.setJobId(jobModel.getJobId()); + jobPK.setTaskId(taskId); + JobStatus status = jobStatusRepository.getJobStatus(jobPK); + if (status != null) { + jobStatus.put(jobModel.getJobId(), status); + } + } + } + } + } + } + } + logger.debug("Airavata retrieved job statuses for experiment with experiment id : " + airavataExperimentId); + return jobStatus; + } catch (Throwable e) { + logger.error("Error while retrieving the job statuses", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving the job statuses More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void addExperimentProcessOutputs(String outputType, List outputs, String id) + throws RegistryServiceException { + try { + if (ExpCatChildDataType.PROCESS_OUTPUT.equals(ExpCatChildDataType.valueOf(outputType))) { + processOutputRepository.addProcessOutputs(outputs, id); + } else if (ExpCatChildDataType.EXPERIMENT_OUTPUT.equals(ExpCatChildDataType.valueOf(outputType))) { + experimentOutputRepository.addExperimentOutputs(outputs, id); + } + } catch (Throwable e) { + logger.error("Error while adding outputs", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding outputs More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void addErrors(String errorType, ErrorModel errorModel, String id) throws RegistryServiceException { + try { + if (ExpCatChildDataType.EXPERIMENT_ERROR.equals(ExpCatChildDataType.valueOf(errorType))) { + experimentErrorRepository.addExperimentError(errorModel, id); + } else if (ExpCatChildDataType.TASK_ERROR.equals(ExpCatChildDataType.valueOf(errorType))) { + taskErrorRepository.addTaskError(errorModel, id); + } else if (ExpCatChildDataType.PROCESS_ERROR.equals(ExpCatChildDataType.valueOf(errorType))) { + processErrorRepository.addProcessError(errorModel, id); + } + } catch (Throwable e) { + logger.error("Error while adding errors", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding errors More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void addTaskStatus(TaskStatus taskStatus, String taskId) throws RegistryServiceException { + try { + taskStatusRepository.addTaskStatus(taskStatus, taskId); + } catch (Throwable e) { + logger.error("Error while adding task status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding task status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void addProcessStatus(ProcessStatus processStatus, String processId) throws RegistryServiceException { + try { + processStatusRepository.addProcessStatus(processStatus, processId); + } catch (Throwable e) { + logger.error("Error while adding process status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding process status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void updateProcessStatus(ProcessStatus processStatus, String processId) throws RegistryServiceException { + try { + processStatusRepository.updateProcessStatus(processStatus, processId); + } catch (Throwable e) { + logger.error("Error while updating process status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating process status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void updateExperimentStatus(ExperimentStatus experimentStatus, String experimentId) + throws RegistryServiceException { + try { + experimentStatusRepository.updateExperimentStatus(experimentStatus, experimentId); + } catch (Throwable e) { + logger.error("Error while updating experiment status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating experiment status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void addJobStatus(JobStatus jobStatus, String taskId, String jobId) throws RegistryServiceException { + try { + JobPK jobPK = new JobPK(); + jobPK.setJobId(jobId); + jobPK.setTaskId(taskId); + jobStatusRepository.addJobStatus(jobStatus, jobPK); + } catch (Throwable e) { + logger.error("Error while adding job status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding job status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void deleteJobs(String processId) throws RegistryServiceException { + try { + List jobs = jobRepository.getJobList(Constants.FieldConstants.JobConstants.PROCESS_ID, processId); + for (JobModel jobModel : jobs) { + jobRepository.removeJob(jobModel); + } + } catch (Throwable e) { + logger.error("Error while deleting jobs", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting jobs More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Project operations + public String createProject(String gatewayId, Project project) throws RegistryServiceException { + try { + if (!validateString(project.getName()) || !validateString(project.getOwner())) { + logger.error("Project name and owner cannot be empty..."); + throw new RegistryException("Project name and owner cannot be empty..."); + } + if (!validateString(gatewayId)) { + logger.error("Gateway ID cannot be empty..."); + throw new RegistryException("Gateway ID cannot be empty..."); + } + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new RegistryException("Gateway does not exist.Please provide a valid gateway id..."); + } + String projectId = projectRepository.addProject(project, gatewayId); + return projectId; + } catch (Throwable e) { + logger.error("Error while creating project", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while creating project More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void updateProject(String projectId, Project updatedProject) throws RegistryServiceException { + try { + if (!validateString(projectId)) { + logger.error("Project id cannot be empty..."); + throw new RegistryException("Project id cannot be empty..."); + } + if (!projectRepository.isProjectExist(projectId)) { + logger.error("Project does not exist in the system. Please provide a valid project ID..."); + throw new RegistryException( + "Project does not exist in the system. Please provide a valid project ID..."); + } + projectRepository.updateProject(updatedProject, projectId); + logger.debug("Airavata updated project with project Id : " + projectId); + } catch (Throwable e) { + logger.error("Error while updating project", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating project More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List searchProjects( + String gatewayId, + String userName, + List accessibleProjIds, + Map filters, + int limit, + int offset) + throws RegistryServiceException { + try { + if (!validateString(userName)) { + logger.error("Username cannot be empty. Please provide a valid user.."); + throw new RegistryException("Username cannot be empty. Please provide a valid user.."); + } + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new RegistryException("Gateway does not exist.Please provide a valid gateway id..."); + } + if (!userRepository.isUserExists(gatewayId, userName)) { + logger.error("User does not exist in the system. Please provide a valid user.."); + throw new RegistryException("User does not exist in the system. Please provide a valid user.."); + } + List projects = new ArrayList<>(); + Map regFilters = new HashMap<>(); + regFilters.put(Constants.FieldConstants.ProjectConstants.GATEWAY_ID, gatewayId); + for (Map.Entry entry : filters.entrySet()) { + if (entry.getKey().equals(ProjectSearchFields.PROJECT_NAME)) { + regFilters.put(Constants.FieldConstants.ProjectConstants.PROJECT_NAME, entry.getValue()); + } else if (entry.getKey().equals(ProjectSearchFields.PROJECT_DESCRIPTION)) { + regFilters.put(Constants.FieldConstants.ProjectConstants.DESCRIPTION, entry.getValue()); + } + } + + try { + if (accessibleProjIds.size() == 0 && !ServerSettings.isEnableSharing()) { + if (!regFilters.containsKey(DBConstants.Project.OWNER)) { + regFilters.put(DBConstants.Project.OWNER, userName); + } + } + } catch (Exception e) { + logger.warn("Error checking sharing settings, continuing without filter", e); + } + + projects = projectRepository.searchAllAccessibleProjects( + accessibleProjIds, + regFilters, + limit, + offset, + Constants.FieldConstants.ProjectConstants.CREATION_TIME, + ResultOrderType.DESC); + logger.debug("Airavata retrieved projects for user : " + userName + " and gateway id : " + gatewayId); + return projects; + } catch (Throwable e) { + logger.error("Error while searching projects", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while searching projects More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Gateway Resource Profile operations + public String registerGatewayResourceProfile(GatewayResourceProfile gatewayResourceProfile) + throws RegistryServiceException { + try { + if (!validateString(gatewayResourceProfile.getGatewayID())) { + logger.error("Cannot create gateway profile with empty gateway id"); + throw new AppCatalogException("Cannot create gateway profile with empty gateway id"); + } + if (!isGatewayExistInternal(gatewayResourceProfile.getGatewayID())) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + String resourceProfile = gwyResourceProfileRepository.addGatewayResourceProfile(gatewayResourceProfile); + logger.debug( + "Airavata registered gateway profile with gateway id : " + gatewayResourceProfile.getGatewayID()); + return resourceProfile; + } catch (Throwable e) { + logger.error("Error while registering gateway resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while registering gateway resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateGatewayResourceProfile(String gatewayID, GatewayResourceProfile gatewayResourceProfile) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + gwyResourceProfileRepository.updateGatewayResourceProfile(gatewayResourceProfile); + logger.debug("Airavata updated gateway profile with gateway id : " + gatewayID); + return true; + } catch (Throwable e) { + logger.error("Error while updating gateway resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating gateway resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean addGatewayComputeResourcePreference( + String gatewayID, String computeResourceId, ComputeResourcePreference computeResourcePreference) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + if (!(gwyResourceProfileRepository.isExists(gatewayID))) { + throw new AppCatalogException("Gateway resource profile '" + gatewayID + "' does not exist!!!"); + } + GatewayResourceProfile profile = gwyResourceProfileRepository.getGatewayProfile(gatewayID); + profile.addToComputeResourcePreferences(computeResourcePreference); + gwyResourceProfileRepository.updateGatewayResourceProfile(profile); + logger.debug("Airavata added gateway compute resource preference with gateway id : " + gatewayID + + " and for compute resource id : " + computeResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while adding gateway compute resource preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while adding gateway compute resource preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateGatewayComputeResourcePreference( + String gatewayID, String computeResourceId, ComputeResourcePreference computeResourcePreference) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + GatewayResourceProfile profile = gwyResourceProfileRepository.getGatewayProfile(gatewayID); + List computeResourcePreferences = profile.getComputeResourcePreferences(); + ComputeResourcePreference preferenceToRemove = null; + for (ComputeResourcePreference preference : computeResourcePreferences) { + if (preference.getComputeResourceId().equals(computeResourceId)) { + preferenceToRemove = preference; + break; + } + } + if (preferenceToRemove != null) { + profile.getComputeResourcePreferences().remove(preferenceToRemove); + } + profile.getComputeResourcePreferences().add(computeResourcePreference); + gwyResourceProfileRepository.updateGatewayResourceProfile(profile); + logger.debug("Airavata updated compute resource preference with gateway id : " + gatewayID + + " and for compute resource id : " + computeResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating gateway compute resource preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while updating gateway compute resource preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean addGatewayStoragePreference( + String gatewayID, String storageResourceId, StoragePreference dataStoragePreference) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + if (!(gwyResourceProfileRepository.isExists(gatewayID))) { + throw new AppCatalogException("Gateway resource profile '" + gatewayID + "' does not exist!!!"); + } + GatewayResourceProfile profile = gwyResourceProfileRepository.getGatewayProfile(gatewayID); + dataStoragePreference.setStorageResourceId(storageResourceId); + profile.addToStoragePreferences(dataStoragePreference); + gwyResourceProfileRepository.updateGatewayResourceProfile(profile); + logger.debug("Airavata added storage resource preference with gateway id : " + gatewayID + + " and for storage resource id : " + storageResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while adding gateway storage preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding gateway storage preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateGatewayStoragePreference( + String gatewayID, String storageId, StoragePreference storagePreference) throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayID)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + GwyResourceProfileRepository gwyResourceProfileRepository = new GwyResourceProfileRepository(); + GatewayResourceProfile profile = gwyResourceProfileRepository.getGatewayProfile(gatewayID); + List dataStoragePreferences = profile.getStoragePreferences(); + StoragePreference preferenceToRemove = null; + for (StoragePreference preference : dataStoragePreferences) { + if (preference.getStorageResourceId().equals(storageId)) { + preferenceToRemove = preference; + break; + } + } + if (preferenceToRemove != null) { + profile.getStoragePreferences().remove(preferenceToRemove); + } + profile.getStoragePreferences().add(storagePreference); + gwyResourceProfileRepository.updateGatewayResourceProfile(profile); + logger.debug("Airavata updated storage resource preference with gateway id : " + gatewayID + + " and for storage resource id : " + storageId); + return true; + } catch (Throwable e) { + logger.error("Error while updating gateway storage preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating gateway storage preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Compute Resource operations + public String registerComputeResource(ComputeResourceDescription computeResourceDescription) + throws RegistryServiceException { + try { + String computeResource = new ComputeResourceRepository().addComputeResource(computeResourceDescription); + logger.debug("Airavata registered compute resource with compute resource Id : " + computeResource); + return computeResource; + } catch (Throwable e) { + logger.error("Error while registering compute resource", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while registering compute resource More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateComputeResource( + String computeResourceId, ComputeResourceDescription computeResourceDescription) + throws RegistryServiceException { + try { + new ComputeResourceRepository().updateComputeResource(computeResourceId, computeResourceDescription); + logger.debug("Airavata updated compute resource with compute resource Id : " + computeResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating compute resource", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating compute resource More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String registerResourceJobManager(ResourceJobManager resourceJobManager) throws RegistryServiceException { + try { + return new ComputeResourceRepository().addResourceJobManager(resourceJobManager); + } catch (Throwable e) { + logger.error("Error while registering resource job manager", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while registering resource job manager More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateResourceJobManager(String resourceJobManagerId, ResourceJobManager updatedResourceJobManager) + throws RegistryServiceException { + try { + new ComputeResourceRepository().updateResourceJobManager(resourceJobManagerId, updatedResourceJobManager); + return true; + } catch (Throwable e) { + logger.error("Error while updating resource job manager", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating resource job manager More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteDataMovementInterface(String resourceId, String dataMovementInterfaceId, DMType dmType) + throws RegistryServiceException { + try { + switch (dmType) { + case COMPUTE_RESOURCE: + new ComputeResourceRepository().removeDataMovementInterface(resourceId, dataMovementInterfaceId); + logger.debug( + "Airavata deleted data movement interface with interface id : " + dataMovementInterfaceId); + return true; + case STORAGE_RESOURCE: + storageResourceRepository.removeDataMovementInterface(resourceId, dataMovementInterfaceId); + logger.debug( + "Airavata deleted data movement interface with interface id : " + dataMovementInterfaceId); + return true; + default: + logger.error( + "Unsupported data movement type specifies.. Please provide the correct data movement type... "); + return false; + } + } catch (Throwable e) { + logger.error("Error while deleting data movement interface", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting data movement interface More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateGridFTPDataMovementDetails( + String dataMovementInterfaceId, GridFTPDataMovement gridFTPDataMovement) throws RegistryServiceException { + try { + throw new AppCatalogException("updateGridFTPDataMovementDetails is not yet implemented"); + } catch (Throwable e) { + logger.error("Error while updating GridFTP data movement details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating GridFTP data movement details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addGridFTPDataMovementDetails( + String computeResourceId, DMType dmType, int priorityOrder, GridFTPDataMovement gridFTPDataMovement) + throws RegistryServiceException { + try { + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + String addDataMovementInterface = addDataMovementInterface( + computeResourceRepository, + computeResourceId, + dmType, + computeResourceRepository.addGridFTPDataMovement(gridFTPDataMovement), + DataMovementProtocol.GridFTP, + priorityOrder); + logger.debug("Airavata registered GridFTP data movement for resource Id: " + computeResourceId); + return addDataMovementInterface; + } catch (Throwable e) { + logger.error("Error while adding GridFTP data movement details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding GridFTP data movement details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateUnicoreDataMovementDetails( + String dataMovementInterfaceId, UnicoreDataMovement unicoreDataMovement) throws RegistryServiceException { + try { + throw new AppCatalogException("updateUnicoreDataMovementDetails is not yet implemented"); + } catch (Throwable e) { + logger.error("Error while updating Unicore data movement details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating Unicore data movement details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addUnicoreDataMovementDetails( + String resourceId, DMType dmType, int priorityOrder, UnicoreDataMovement unicoreDataMovement) + throws RegistryServiceException { + try { + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + String movementInterface = addDataMovementInterface( + computeResourceRepository, + resourceId, + dmType, + computeResourceRepository.addUnicoreDataMovement(unicoreDataMovement), + DataMovementProtocol.UNICORE_STORAGE_SERVICE, + priorityOrder); + logger.debug("Airavata registered UNICORE data movement for resource Id: " + resourceId); + return movementInterface; + } catch (Throwable e) { + logger.error("Error while adding Unicore data movement details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding Unicore data movement details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateSCPDataMovementDetails(String dataMovementInterfaceId, SCPDataMovement scpDataMovement) + throws RegistryServiceException { + try { + new ComputeResourceRepository().updateScpDataMovement(scpDataMovement); + logger.debug("Airavata updated SCP data movement with data movement id: " + dataMovementInterfaceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating SCP data movement details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating SCP data movement details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addSCPDataMovementDetails( + String resourceId, DMType dmType, int priorityOrder, SCPDataMovement scpDataMovement) + throws RegistryServiceException { + try { + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + String movementInterface = addDataMovementInterface( + computeResourceRepository, + resourceId, + dmType, + computeResourceRepository.addScpDataMovement(scpDataMovement), + DataMovementProtocol.SCP, + priorityOrder); + logger.debug("Airavata registered SCP data movement for resource Id: " + resourceId); + return movementInterface; + } catch (Throwable e) { + logger.error("Error while adding SCP data movement details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding SCP data movement details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateLocalDataMovementDetails(String dataMovementInterfaceId, LOCALDataMovement localDataMovement) + throws RegistryServiceException { + try { + new ComputeResourceRepository().updateLocalDataMovement(localDataMovement); + logger.debug("Airavata updated local data movement with data movement id: " + dataMovementInterfaceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating local data movement details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating local data movement details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addLocalDataMovementDetails( + String resourceId, DMType dataMoveType, int priorityOrder, LOCALDataMovement localDataMovement) + throws RegistryServiceException { + try { + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + String movementInterface = addDataMovementInterface( + computeResourceRepository, + resourceId, + dataMoveType, + computeResourceRepository.addLocalDataMovement(localDataMovement), + DataMovementProtocol.LOCAL, + priorityOrder); + logger.debug("Airavata registered local data movement for resource Id: " + resourceId); + return movementInterface; + } catch (Throwable e) { + logger.error("Error while adding local data movement details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding local data movement details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Storage Resource operations + public String registerStorageResource(StorageResourceDescription storageResourceDescription) + throws RegistryServiceException { + try { + String storageResource = storageResourceRepository.addStorageResource(storageResourceDescription); + logger.debug("Airavata registered storage resource with storage resource Id : " + storageResource); + return storageResource; + } catch (Throwable e) { + logger.error("Error while registering storage resource", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while registering storage resource More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateStorageResource( + String storageResourceId, StorageResourceDescription storageResourceDescription) + throws RegistryServiceException { + try { + storageResourceRepository.updateStorageResource(storageResourceId, storageResourceDescription); + logger.debug("Airavata updated storage resource with storage resource Id : " + storageResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating storage resource", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating storage resource More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Helper methods for job submission and data movement interfaces + private String addJobSubmissionInterface( + ComputeResourceRepository computeResourceRepository, + String computeResourceId, + String jobSubmissionInterfaceId, + JobSubmissionProtocol protocolType, + int priorityOrder) + throws RegistryServiceException { + try { + JobSubmissionInterface jobSubmissionInterface = new JobSubmissionInterface(); + jobSubmissionInterface.setJobSubmissionInterfaceId(jobSubmissionInterfaceId); + jobSubmissionInterface.setPriorityOrder(priorityOrder); + jobSubmissionInterface.setJobSubmissionProtocol(protocolType); + return computeResourceRepository.addJobSubmissionProtocol(computeResourceId, jobSubmissionInterface); + } catch (Throwable e) { + logger.error("Error while adding job submission interface", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding job submission interface More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private String addDataMovementInterface( + ComputeResourceRepository computeResourceRepository, + String computeResourceId, + DMType dmType, + String dataMovementInterfaceId, + DataMovementProtocol protocolType, + int priorityOrder) + throws RegistryServiceException { + try { + DataMovementInterface dataMovementInterface = new DataMovementInterface(); + dataMovementInterface.setDataMovementInterfaceId(dataMovementInterfaceId); + dataMovementInterface.setPriorityOrder(priorityOrder); + dataMovementInterface.setDataMovementProtocol(protocolType); + if (dmType.equals(DMType.COMPUTE_RESOURCE)) { + return computeResourceRepository.addDataMovementProtocol( + computeResourceId, dmType, dataMovementInterface); + } else if (dmType.equals(DMType.STORAGE_RESOURCE)) { + dataMovementInterface.setStorageResourceId(computeResourceId); + return storageResourceRepository.addDataMovementInterface(dataMovementInterface); + } + return null; + } catch (Throwable e) { + logger.error("Error while adding data movement interface", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding data movement interface More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Job Submission Interface operations + public String addSSHJobSubmissionDetails( + String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission) + throws RegistryServiceException { + try { + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + String submissionInterface = addJobSubmissionInterface( + computeResourceRepository, + computeResourceId, + computeResourceRepository.addSSHJobSubmission(sshJobSubmission), + JobSubmissionProtocol.SSH, + priorityOrder); + logger.debug("Airavata registered SSH job submission for compute resource id: " + computeResourceId); + return submissionInterface; + } catch (Throwable e) { + logger.error("Error while adding SSH job submission details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding SSH job submission details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addSSHForkJobSubmissionDetails( + String computeResourceId, int priorityOrder, SSHJobSubmission sshJobSubmission) + throws RegistryServiceException { + try { + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + String submissionDetails = addJobSubmissionInterface( + computeResourceRepository, + computeResourceId, + computeResourceRepository.addSSHJobSubmission(sshJobSubmission), + JobSubmissionProtocol.SSH_FORK, + priorityOrder); + logger.debug("Airavata registered Fork job submission for compute resource id: " + computeResourceId); + return submissionDetails; + } catch (Throwable e) { + logger.error("Error while adding SSH Fork job submission details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding SSH Fork job submission details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addLocalSubmissionDetails( + String computeResourceId, int priorityOrder, LOCALSubmission localSubmission) + throws RegistryServiceException { + try { + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + String submissionInterface = addJobSubmissionInterface( + computeResourceRepository, + computeResourceId, + computeResourceRepository.addLocalJobSubmission(localSubmission), + JobSubmissionProtocol.LOCAL, + priorityOrder); + logger.debug("Airavata added local job submission for compute resource id: " + computeResourceId); + return submissionInterface; + } catch (Throwable e) { + logger.error("Error while adding local submission details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding local submission details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateLocalSubmissionDetails(String jobSubmissionInterfaceId, LOCALSubmission localSubmission) + throws RegistryServiceException { + try { + new ComputeResourceRepository().updateLocalJobSubmission(localSubmission); + logger.debug("Airavata updated local job submission for job submission interface id: " + + jobSubmissionInterfaceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating local submission details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating local submission details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addCloudJobSubmissionDetails( + String computeResourceId, int priorityOrder, CloudJobSubmission cloudSubmission) + throws RegistryServiceException { + try { + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + String submissionInterface = addJobSubmissionInterface( + computeResourceRepository, + computeResourceId, + computeResourceRepository.addCloudJobSubmission(cloudSubmission), + JobSubmissionProtocol.CLOUD, + priorityOrder); + logger.debug("Airavata registered Cloud job submission for compute resource id: " + computeResourceId); + return submissionInterface; + } catch (Throwable e) { + logger.error("Error while adding cloud job submission details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding cloud job submission details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addUNICOREJobSubmissionDetails( + String computeResourceId, int priorityOrder, UnicoreJobSubmission unicoreJobSubmission) + throws RegistryServiceException { + try { + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + String submissionInterface = addJobSubmissionInterface( + computeResourceRepository, + computeResourceId, + computeResourceRepository.addUNICOREJobSubmission(unicoreJobSubmission), + JobSubmissionProtocol.UNICORE, + priorityOrder); + logger.debug("Airavata registered UNICORE job submission for compute resource id: " + computeResourceId); + return submissionInterface; + } catch (Throwable e) { + logger.error("Error while adding UNICORE job submission details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding UNICORE job submission details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Application Interface/Module/Deployment operations + public String registerApplicationInterface(String gatewayId, ApplicationInterfaceDescription applicationInterface) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + String interfaceId = + applicationInterfaceRepository.addApplicationInterface(applicationInterface, gatewayId); + logger.debug("Airavata registered application interface for gateway id : " + gatewayId); + return interfaceId; + } catch (Throwable e) { + logger.error("Error while registering application interface", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while registering application interface More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateApplicationInterface( + String appInterfaceId, ApplicationInterfaceDescription applicationInterface) + throws RegistryServiceException { + try { + applicationInterfaceRepository.updateApplicationInterface(appInterfaceId, applicationInterface); + logger.debug("Airavata updated application interface with interface id : " + appInterfaceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating application interface", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating application interface More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String registerApplicationModule(String gatewayId, ApplicationModule applicationModule) + throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + String module = applicationInterfaceRepository.addApplicationModule(applicationModule, gatewayId); + logger.debug("Airavata registered application module for gateway id : " + gatewayId); + return module; + } catch (Throwable e) { + logger.error("Error while registering application module", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while registering application module More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateApplicationModule(String appModuleId, ApplicationModule applicationModule) + throws RegistryServiceException { + try { + applicationInterfaceRepository.updateApplicationModule(appModuleId, applicationModule); + logger.debug("Airavata updated application module with module id: " + appModuleId); + return true; + } catch (Throwable e) { + logger.error("Error while updating application module", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating application module More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String registerApplicationDeployment( + String gatewayId, ApplicationDeploymentDescription applicationDeployment) throws RegistryServiceException { + try { + if (!isGatewayExistInternal(gatewayId)) { + logger.error("Gateway does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + String deployment = + applicationDeploymentRepository.addApplicationDeployment(applicationDeployment, gatewayId); + logger.debug("Airavata registered application deployment for gateway id : " + gatewayId); + return deployment; + } catch (Throwable e) { + logger.error("Error while registering application deployment", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while registering application deployment More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateApplicationDeployment( + String appDeploymentId, ApplicationDeploymentDescription applicationDeployment) + throws RegistryServiceException { + try { + applicationDeploymentRepository.updateApplicationDeployment(appDeploymentId, applicationDeployment); + logger.debug("Airavata updated application deployment for deployment id : " + appDeploymentId); + return true; + } catch (Throwable e) { + logger.error("Error while updating application deployment", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating application deployment More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // User Resource Profile operations + public String registerUserResourceProfile(UserResourceProfile userResourceProfile) throws RegistryServiceException { + try { + if (!validateString(userResourceProfile.getUserId())) { + logger.error("Cannot create user resource profile with empty user id"); + throw new AppCatalogException("Cannot create user resource profile with empty user id"); + } + if (!validateString(userResourceProfile.getGatewayID())) { + logger.error("Cannot create user resource profile with empty gateway id"); + throw new AppCatalogException("Cannot create user resource profile with empty gateway id"); + } + if (!userRepository.isUserExists(userResourceProfile.getGatewayID(), userResourceProfile.getUserId())) { + logger.error("User does not exist.Please provide a valid user ID..."); + throw new AppCatalogException("User does not exist.Please provide a valid user ID..."); + } + String resourceProfile = userResourceProfileRepository.addUserResourceProfile(userResourceProfile); + logger.debug("Airavata registered user resource profile with gateway id : " + + userResourceProfile.getGatewayID() + "and user id : " + userResourceProfile.getUserId()); + return resourceProfile; + } catch (Throwable e) { + logger.error("Error while registering user resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while registering user resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean isUserResourceProfileExists(String userId, String gatewayId) throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayId, userId)) { + logger.error("user does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("user does not exist.Please provide a valid gateway id..."); + } + return userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayId); + } catch (Throwable e) { + logger.error("Error while checking if user resource profile exists", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while checking if user resource profile exists More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public UserResourceProfile getUserResourceProfile(String userId, String gatewayId) throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayId, userId)) { + logger.error("user does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("user does not exist.Please provide a valid gateway id..."); + } + UserResourceProfile userResourceProfile = + userResourceProfileRepository.getUserResourceProfile(userId, gatewayId); + logger.debug("Airavata retrieved User resource profile with user id : " + userId); + return userResourceProfile; + } catch (Throwable e) { + logger.error("Error while getting user resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting user resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateUserResourceProfile(String userId, String gatewayID, UserResourceProfile userResourceProfile) + throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("User does not exist.Please provide a valid user id..."); + throw new AppCatalogException("user does not exist.Please provide a valid user id..."); + } + userResourceProfileRepository.updateUserResourceProfile(userId, gatewayID, userResourceProfile); + logger.debug("Airavata updated gateway profile with gateway id : " + userId); + return true; + } catch (Throwable e) { + logger.error("Error while updating user resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating user resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteUserResourceProfile(String userId, String gatewayID) throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("user does not exist.Please provide a valid user id..."); + throw new AppCatalogException("user does not exist.Please provide a valid user id..."); + } + userResourceProfileRepository.removeUserResourceProfile(userId, gatewayID); + logger.debug("Airavata deleted User profile with gateway id : " + gatewayID + " and user id : " + userId); + return true; + } catch (Throwable e) { + logger.error("Error while deleting user resource profile", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting user resource profile More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Resource Scheduling operations + public void updateResourceScheduleing( + String airavataExperimentId, ComputationalResourceSchedulingModel resourceScheduling) + throws RegistryServiceException { + try { + if (!experimentRepository.isExperimentExist(airavataExperimentId)) { + logger.debug( + airavataExperimentId, + "Update resource scheduling failed, experiment {} doesn't exist.", + airavataExperimentId); + throw new RegistryException( + "Requested experiment id " + airavataExperimentId + " does not exist in the system.."); + } + ExperimentStatus experimentStatus = getExperimentStatusInternal(airavataExperimentId); + if (experimentStatus != null) { + ExperimentState experimentState = experimentStatus.getState(); + switch (experimentState) { + case CREATED: + case VALIDATED: + case CANCELED: + case FAILED: + processRepository.addProcessResourceSchedule(resourceScheduling, airavataExperimentId); + logger.debug( + airavataExperimentId, + "Successfully updated resource scheduling for the experiment {}.", + airavataExperimentId); + break; + default: + logger.error( + airavataExperimentId, + "Error while updating scheduling info. Update experiment is only valid for experiments " + + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + + "experiment is in one of above statuses... "); + throw new RegistryException( + "Error while updating experiment. Update experiment is only valid for experiments " + + "with status CREATED, VALIDATED, CANCELLED, FAILED and UNKNOWN. Make sure the given " + + "experiment is in one of above statuses... "); + } + } + } catch (Throwable e) { + logger.error("Error while updating resource scheduling", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating resource scheduling More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // User operations + public String addUser(UserProfile userProfile) throws RegistryServiceException { + try { + logger.info("Adding User in Registry: " + userProfile); + if (userRepository.isUserExists(userProfile.getGatewayId(), userProfile.getUserId())) { + throw new RegistryException("User already exists, with userId: " + userProfile.getUserId() + + ", and gatewayId: " + userProfile.getGatewayId()); + } + UserProfile savedUser = userRepository.addUser(userProfile); + return savedUser.getUserId(); + } catch (Throwable e) { + logger.error("Error while adding user", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding user More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // User Compute/Storage Preference operations + public boolean addUserComputeResourcePreference( + String userId, + String gatewayID, + String computeResourceId, + UserComputeResourcePreference userComputeResourcePreference) + throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("user does not exist.Please provide a valid user id..."); + throw new AppCatalogException("user does not exist.Please provide a valid user id..."); + } + if (!userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { + throw new AppCatalogException("User resource profile with user id'" + userId + " & gateway Id" + + gatewayID + "' does not exist!!!"); + } + UserResourceProfile profile = userResourceProfileRepository.getUserResourceProfile(userId, gatewayID); + profile.addToUserComputeResourcePreferences(userComputeResourcePreference); + userResourceProfileRepository.updateUserResourceProfile(userId, gatewayID, profile); + logger.debug("Airavata added User compute resource preference with gateway id : " + gatewayID + + " and for compute resource id : " + computeResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while adding user compute resource preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding user compute resource preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean isUserComputeResourcePreferenceExists(String userId, String gatewayID, String computeResourceId) + throws RegistryServiceException { + try { + if (userRepository.isUserExists(gatewayID, userId) + && userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { + return userResourceProfileRepository.isUserComputeResourcePreferenceExists( + userId, gatewayID, computeResourceId); + } + return false; + } catch (Throwable e) { + logger.error("Error while checking if user compute resource preference exists", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while checking if user compute resource preference exists More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public UserComputeResourcePreference getUserComputeResourcePreference( + String userId, String gatewayID, String userComputeResourceId) throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("user does not exist.Please provide a valid user id..."); + throw new AppCatalogException("user does not exist.Please provide a valid user id..."); + } + if (!userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { + throw new AppCatalogException("User resource profile with user id'" + userId + " & gateway Id" + + gatewayID + "' does not exist!!!"); + } + ComputeResourceRepository computeResourceRepository = new ComputeResourceRepository(); + if (!computeResourceRepository.isComputeResourceExists(userComputeResourceId)) { + logger.error( + userComputeResourceId, + "Given compute resource does not exist in the system. Please provide a valid compute resource id..."); + throw new AppCatalogException( + "Given compute resource does not exist in the system. Please provide a valid compute resource id..."); + } + UserComputeResourcePreference userComputeResourcePreference = + userResourceProfileRepository.getUserComputeResourcePreference( + userId, gatewayID, userComputeResourceId); + logger.debug("Airavata retrieved user compute resource preference with gateway id : " + gatewayID + + " and for compute resoruce id : " + userComputeResourceId); + return userComputeResourcePreference; + } catch (Throwable e) { + logger.error("Error while getting user compute resource preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting user compute resource preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateUserComputeResourcePreference( + String userId, + String gatewayID, + String computeResourceId, + UserComputeResourcePreference userComputeResourcePreference) + throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("user does not exist.Please provide a valid user id..."); + throw new AppCatalogException("user does not exist.Please provide a valid user id..."); + } + UserResourceProfile profile = userResourceProfileRepository.getUserResourceProfile(userId, gatewayID); + List userComputeResourcePreferences = + profile.getUserComputeResourcePreferences(); + UserComputeResourcePreference preferenceToRemove = null; + for (UserComputeResourcePreference preference : userComputeResourcePreferences) { + if (preference.getComputeResourceId().equals(computeResourceId)) { + preferenceToRemove = preference; + break; + } + } + if (preferenceToRemove != null) { + profile.getUserComputeResourcePreferences().remove(preferenceToRemove); + } + profile.getUserComputeResourcePreferences().add(userComputeResourcePreference); + userResourceProfileRepository.updateUserResourceProfile(userId, gatewayID, profile); + logger.debug("Airavata updated compute resource preference with gateway id : " + gatewayID + + " and for compute resource id : " + computeResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating user compute resource preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating user compute resource preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean addUserStoragePreference( + String userId, String gatewayID, String storageResourceId, UserStoragePreference dataStoragePreference) + throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("user does not exist.Please provide a valid user id..."); + throw new AppCatalogException("user does not exist.Please provide a valid user id..."); + } + if (!userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { + throw new AppCatalogException("User resource profile with user id'" + userId + " & gateway Id" + + gatewayID + "' does not exist!!!"); + } + UserResourceProfile profile = userResourceProfileRepository.getUserResourceProfile(userId, gatewayID); + dataStoragePreference.setStorageResourceId(storageResourceId); + profile.addToUserStoragePreferences(dataStoragePreference); + userResourceProfileRepository.updateUserResourceProfile(userId, gatewayID, profile); + logger.debug("Airavata added storage resource preference with gateway id : " + gatewayID + + " and for storage resource id : " + storageResourceId); + return true; + } catch (Throwable e) { + logger.error("Error while adding user storage preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding user storage preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public UserStoragePreference getUserStoragePreference(String userId, String gatewayID, String storageId) + throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("user does not exist.Please provide a valid user id..."); + throw new AppCatalogException("user does not exist.Please provide a valid user id..."); + } + if (!userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { + throw new AppCatalogException("User resource profile with user id'" + userId + " & gateway Id" + + gatewayID + "' does not exist!!!"); + } + + UserStoragePreference storagePreference = + userResourceProfileRepository.getUserStoragePreference(userId, gatewayID, storageId); + logger.debug("Airavata retrieved user storage resource preference with gateway id : " + gatewayID + + " and for storage resource id : " + storageId); + return storagePreference; + } catch (Throwable e) { + logger.error("Error while getting user storage preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting user storage preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllUserResourceProfiles() throws RegistryServiceException { + try { + return userResourceProfileRepository.getAllUserResourceProfiles(); + } catch (Throwable e) { + logger.error("Error while getting all user resource profiles", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting all user resource profiles More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Gateway Groups operations + public GatewayGroups getGatewayGroups(String gatewayId) throws RegistryServiceException { + try { + if (!gatewayGroupsRepository.isExists(gatewayId)) { + final String message = "No GatewayGroups entry exists for " + gatewayId; + logger.error(message); + throw new RegistryException(message); + } + return gatewayGroupsRepository.get(gatewayId); + } catch (Throwable e) { + logger.error("Error while getting gateway groups", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting gateway groups More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Parser operations + public Parser getParser(String parserId, String gatewayId) throws RegistryServiceException { + try { + if (!parserRepository.isExists(parserId)) { + final String message = "No Parser Info entry exists for " + parserId; + logger.error(message); + throw new RegistryException(message); + } + return parserRepository.get(parserId); + } catch (Throwable e) { + logger.error("Error while getting parser", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting parser More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String saveParser(Parser parser) throws RegistryServiceException { + try { + Parser saved = parserRepository.saveParser(parser); + return saved.getId(); + } catch (Throwable e) { + logger.error("Error while saving parser", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while saving parser More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void removeParser(String parserId, String gatewayId) throws RegistryServiceException { + try { + boolean exists = parserRepository.isExists(parserId); + if (!exists || gatewayId.equals(parserRepository.get(parserId).getGatewayId())) { + throw new RegistryException("Parser " + parserId + " does not exist"); + } + parserRepository.delete(parserId); + } catch (Throwable e) { + logger.error("Error while removing parser", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while removing parser More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ParserInput getParserInput(String parserInputId, String gatewayId) throws RegistryServiceException { + if (!parserInputRepository.isExists(parserInputId)) { + try { + final String message = "No ParserInput entry exists for " + parserInputId; + logger.error(message); + throw new RegistryException(message); + } catch (Throwable e) { + logger.error("Error in getParserInput", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error in getParserInput More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + return parserInputRepository.get(parserInputId); + } + + public String saveParserInput(ParserInput parserInput) throws RegistryServiceException { + ParserInput saved = parserInputRepository.create(parserInput); + return saved.getId(); + } + + public void removeParserInput(String parserInputId, String gatewayId) throws RegistryServiceException { + try { + boolean exists = parserInputRepository.isExists(parserInputId); + if (!exists) { + throw new RegistryException("ParserInput " + parserInputId + " does not exist"); + } + ParserInput parserInput = parserInputRepository.get(parserInputId); + Parser parser = parserRepository.get(parserInput.getParserId()); + if (!gatewayId.equals(parser.getGatewayId())) { + throw new RegistryException( + "ParserInput " + parserInputId + " does not belong to gateway " + gatewayId); + } + parserInputRepository.delete(parserInputId); + } catch (Throwable e) { + logger.error("Error in removeParserInput", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error in removeParserInput More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ParserOutput getParserOutput(String parserOutputId, String gatewayId) throws RegistryServiceException { + try { + if (!parserOutputRepository.isExists(parserOutputId)) { + final String message = "No ParserOutput entry exists for " + parserOutputId; + logger.error(message); + throw new RegistryException(message); + } + return parserOutputRepository.get(parserOutputId); + } catch (Throwable e) { + logger.error("Error in getParserOutput", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error in getParserOutput More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String saveParserOutput(ParserOutput parserOutput) throws RegistryServiceException { + try { + ParserOutput saved = parserOutputRepository.create(parserOutput); + return saved.getId(); + } catch (Throwable e) { + logger.error("Error while saving parser output", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while saving parser output More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void removeParserOutput(String parserOutputId, String gatewayId) throws RegistryServiceException { + try { + boolean exists = parserOutputRepository.isExists(parserOutputId); + if (!exists) { + throw new RegistryException("ParserOutput " + parserOutputId + " does not exist"); + } + ParserOutput parserOutput = parserOutputRepository.get(parserOutputId); + Parser parser = parserRepository.get(parserOutput.getParserId()); + if (!gatewayId.equals(parser.getGatewayId())) { + throw new RegistryException( + "ParserOutput " + parserOutputId + " does not belong to gateway " + gatewayId); + } + parserOutputRepository.delete(parserOutputId); + } catch (Throwable e) { + logger.error("Error in removeParserOutput", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error in removeParserOutput More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public ParsingTemplate getParsingTemplate(String templateId, String gatewayId) throws RegistryServiceException { + try { + if (!parsingTemplateRepository.isExists(templateId)) { + final String message = "No ParsingTemplate entry exists for " + templateId; + logger.error(message); + throw new RegistryException(message); + } + return parsingTemplateRepository.get(templateId); + } catch (Throwable e) { + logger.error("Error in getParsingTemplate", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error in getParsingTemplate More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String saveParsingTemplate(ParsingTemplate parsingTemplate) throws RegistryServiceException { + try { + ParsingTemplate saved = parsingTemplateRepository.create(parsingTemplate); + return saved.getId(); + } catch (Throwable e) { + logger.error("Error while saving parsing template", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while saving parsing template More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void removeParsingTemplate(String templateId, String gatewayId) throws RegistryServiceException { + try { + boolean exists = parsingTemplateRepository.isExists(templateId); + if (!exists + || gatewayId.equals( + parsingTemplateRepository.get(templateId).getGatewayId())) { + throw new RegistryException("Parsing template " + templateId + " does not exist"); + } + parsingTemplateRepository.delete(templateId); + } catch (Throwable e) { + logger.error("Error in removeParsingTemplate", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error in removeParsingTemplate More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + // Gateway Usage Reporting operations + public boolean isGatewayUsageReportingAvailable(String gatewayId, String computeResourceId) + throws RegistryServiceException { + try { + return usageReportingCommandRepository.isGatewayUsageReportingCommandExists(gatewayId, computeResourceId); + } catch (Throwable e) { + logger.error("Error while checking if gateway usage reporting is available", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while checking if gateway usage reporting is available More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public GatewayUsageReportingCommand getGatewayReportingCommand(String gatewayId, String computeResourceId) + throws RegistryServiceException { + try { + if (!usageReportingCommandRepository.isGatewayUsageReportingCommandExists(gatewayId, computeResourceId)) { + String message = "No usage reporting information for the gateway " + gatewayId + + " and compute resource " + computeResourceId; + logger.error(message); + throw new RegistryException(message); + } + return usageReportingCommandRepository.getGatewayUsageReportingCommand(gatewayId, computeResourceId); + } catch (Throwable e) { + logger.error("Error while getting gateway reporting command", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while getting gateway reporting command More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void addGatewayUsageReportingCommand(GatewayUsageReportingCommand command) throws RegistryServiceException { + try { + usageReportingCommandRepository.addGatewayUsageReportingCommand(command); + } catch (Throwable e) { + logger.error("Error while adding gateway usage reporting command", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding gateway usage reporting command More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void removeGatewayUsageReportingCommand(String gatewayId, String computeResourceId) + throws RegistryServiceException { + try { + usageReportingCommandRepository.removeGatewayUsageReportingCommand(gatewayId, computeResourceId); + } catch (Throwable e) { + logger.error("Error while removing gateway usage reporting command", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while removing gateway usage reporting command More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateCloudJobSubmissionDetails( + String jobSubmissionInterfaceId, CloudJobSubmission cloudJobSubmission) throws RegistryServiceException { + try { + cloudJobSubmission.setJobSubmissionInterfaceId(jobSubmissionInterfaceId); + computeResourceRepository.updateCloudJobSubmission(cloudJobSubmission); + logger.debug("Airavata updated Cloud job submission for job submission interface id: " + + jobSubmissionInterfaceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating cloud job submission details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating cloud job submission details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateSSHJobSubmissionDetails(String jobSubmissionInterfaceId, SSHJobSubmission sshJobSubmission) + throws RegistryServiceException { + try { + sshJobSubmission.setJobSubmissionInterfaceId(jobSubmissionInterfaceId); + computeResourceRepository.updateSSHJobSubmission(sshJobSubmission); + logger.debug( + "Airavata updated SSH job submission for job submission interface id: " + jobSubmissionInterfaceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating SSH job submission details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating SSH job submission details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateUnicoreJobSubmissionDetails( + String jobSubmissionInterfaceId, UnicoreJobSubmission unicoreJobSubmission) + throws RegistryServiceException { + try { + unicoreJobSubmission.setJobSubmissionInterfaceId(jobSubmissionInterfaceId); + computeResourceRepository.updateUNICOREJobSubmission(unicoreJobSubmission); + logger.debug("Airavata updated UNICORE job submission for job submission interface id: " + + jobSubmissionInterfaceId); + return true; + } catch (Throwable e) { + logger.error("Error while updating Unicore job submission details", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating Unicore job submission details More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateNotification(Notification notification) throws RegistryServiceException { + try { + notificationRepository.updateNotification(notification); + logger.debug("Airavata updated notification with notification id: " + notification.getNotificationId()); + return true; + } catch (Throwable e) { + logger.error("Error while updating notification", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating notification More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String createNotification(Notification notification) throws RegistryServiceException { + try { + String notificationId = notificationRepository.createNotification(notification); + logger.debug("Airavata created notification with notification id: " + notificationId); + return notificationId; + } catch (Throwable e) { + logger.error("Error while creating notification", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while creating notification More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateGateway(String gatewayId, Gateway updatedGateway) throws RegistryServiceException { + try { + if (!gatewayRepository.isGatewayExist(gatewayId)) { + logger.error("Gateway does not exist in the system. Please provide a valid gateway ID..."); + throw new RegistryException( + "Gateway does not exist in the system. Please provide a valid gateway ID..."); + } + updatedGateway.setGatewayId(gatewayId); + gatewayRepository.updateGateway(gatewayId, updatedGateway); + logger.debug("Airavata updated gateway with gateway id: " + gatewayId); + return true; + } catch (Throwable e) { + logger.error("Error while updating gateway", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating gateway More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addGateway(Gateway gateway) throws RegistryServiceException { + try { + if (gatewayRepository.isGatewayExist(gateway.getGatewayId())) { + logger.error("Gateway already exists in the system. Please provide a different gateway ID..."); + throw new AppCatalogException( + "Gateway already exists in the system. Please provide a different gateway ID..."); + } + String gatewayId = gatewayRepository.addGateway(gateway); + logger.debug("Airavata registered gateway with gateway id: " + gatewayId); + return gatewayId; + } catch (Throwable e) { + logger.error("Error while adding gateway", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while adding gateway More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateUserStoragePreference( + String userId, String gatewayID, String storageId, UserStoragePreference userStoragePreference) + throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("user does not exist.Please provide a valid user id..."); + throw new AppCatalogException("user does not exist.Please provide a valid user id..."); + } + if (!userResourceProfileRepository.isUserResourceProfileExists(userId, gatewayID)) { + throw new AppCatalogException("User resource profile with user id'" + userId + " & gateway Id" + + gatewayID + "' does not exist!!!"); + } + UserResourceProfile profile = userResourceProfileRepository.getUserResourceProfile(userId, gatewayID); + List userStoragePreferences = profile.getUserStoragePreferences(); + UserStoragePreference preferenceToRemove = null; + for (UserStoragePreference preference : userStoragePreferences) { + if (preference.getStorageResourceId().equals(storageId)) { + preferenceToRemove = preference; + break; + } + } + if (preferenceToRemove != null) { + profile.getUserStoragePreferences().remove(preferenceToRemove); + } + userStoragePreference.setStorageResourceId(storageId); + profile.getUserStoragePreferences().add(userStoragePreference); + userResourceProfileRepository.updateUserResourceProfile(userId, gatewayID, profile); + logger.debug("Airavata updated storage resource preference with gateway id : " + gatewayID + + " and for storage resource id : " + storageId); + return true; + } catch (Throwable e) { + logger.error("Error while updating user storage preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating user storage preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteUserComputeResourcePreference(String userId, String gatewayID, String computeResourceId) + throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("user does not exist.Please provide a valid user id..."); + throw new AppCatalogException("user does not exist.Please provide a valid user id..."); + } + return userResourceProfileRepository.removeUserComputeResourcePreferenceFromGateway( + userId, gatewayID, computeResourceId); + } catch (Throwable e) { + logger.error("Error while deleting user compute resource preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting user compute resource preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteUserStoragePreference(String userId, String gatewayID, String storageId) + throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("user does not exist.Please provide a valid user id..."); + throw new AppCatalogException("user does not exist.Please provide a valid user id..."); + } + return userResourceProfileRepository.removeUserDataStoragePreferenceFromGateway( + userId, gatewayID, storageId); + } catch (Throwable e) { + logger.error("Error while deleting user storage preference", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while deleting user storage preference More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getLatestQueueStatuses() throws RegistryServiceException { + try { + return queueStatusRepository.getLatestQueueStatuses(); + } catch (Throwable e) { + logger.error("Error while retrieving latest queue statuses", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving latest queue statuses More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void registerQueueStatuses(List queueStatuses) throws RegistryServiceException { + try { + queueStatusRepository.createQueueStatuses(queueStatuses); + } catch (Throwable e) { + logger.error("Error while registering queue statuses", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while registering queue statuses More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public QueueStatusModel getQueueStatus(String hostName, String queueName) throws RegistryServiceException { + try { + Optional optionalQueueStatusModel = + queueStatusRepository.getQueueStatus(hostName, queueName); + if (optionalQueueStatusModel.isPresent()) { + return optionalQueueStatusModel.get(); + } else { + QueueStatusModel queueStatusModel = new QueueStatusModel(); + queueStatusModel.setHostName(hostName); + queueStatusModel.setQueueName(queueName); + queueStatusModel.setQueueUp(false); + queueStatusModel.setRunningJobs(0); + queueStatusModel.setQueuedJobs(0); + queueStatusModel.setTime(0); + return queueStatusModel; + } + } catch (Throwable e) { + logger.error("Error while retrieving queue status", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving queue status More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void createGatewayGroups(GatewayGroups gatewayGroups) throws RegistryServiceException { + try { + if (gatewayGroupsRepository.isExists(gatewayGroups.getGatewayId())) { + logger.error("GatewayGroups already exists for " + gatewayGroups.getGatewayId()); + throw new RegistryException( + "GatewayGroups for gatewayId: " + gatewayGroups.getGatewayId() + " already exists."); + } + gatewayGroupsRepository.create(gatewayGroups); + } catch (Throwable e) { + logger.error("Error while creating gateway groups", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while creating gateway groups More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public void updateGatewayGroups(GatewayGroups gatewayGroups) throws RegistryServiceException { + try { + if (!gatewayGroupsRepository.isExists(gatewayGroups.getGatewayId())) { + final String message = "No GatewayGroups entry exists for " + gatewayGroups.getGatewayId(); + logger.error(message); + throw new RegistryException(message); + } + gatewayGroupsRepository.update(gatewayGroups); + } catch (Throwable e) { + logger.error("Error while updating gateway groups", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while updating gateway groups More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean isGatewayGroupsExists(String gatewayId) throws RegistryServiceException { + try { + return gatewayGroupsRepository.isExists(gatewayId); + } catch (Throwable e) { + logger.error("Error while checking if gateway groups exist", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while checking if gateway groups exist More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List listAllParsers(String gatewayId) throws RegistryServiceException { + try { + return parserRepository.getAllParsers(gatewayId); + } catch (Throwable e) { + logger.error("Error while listing all parsers", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while listing all parsers More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getParsingTemplatesForApplication(String applicationInterfaceId) + throws RegistryServiceException { + try { + return parsingTemplateRepository.getParsingTemplatesForApplication(applicationInterfaceId); + } catch (Throwable e) { + logger.error("Error while retrieving parsing templates for application", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving parsing templates for application More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getParsingTemplatesForExperiment(String experimentId, String gatewayId) + throws RegistryServiceException { + try { + ExperimentModel experiment = experimentRepository.getExperiment(experimentId); + List processes = experiment.getProcesses(); + if (processes != null && processes.size() > 0) { + return parsingTemplateRepository.getParsingTemplatesForApplication( + processes.get(processes.size() - 1).getApplicationInterfaceId()); + } + return Collections.emptyList(); + } catch (Throwable e) { + logger.error("Error while retrieving parsing templates for experiment", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving parsing templates for experiment More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List listAllParsingTemplates(String gatewayId) throws RegistryServiceException { + try { + return parsingTemplateRepository.getAllParsingTemplates(gatewayId); + } catch (Throwable e) { + logger.error("Error while listing all parsing templates", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while listing all parsing templates More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllUserComputeResourcePreferences(String userId, String gatewayID) + throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("User Resource Profile does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException( + "User Resource Profile does not exist.Please provide a valid gateway id..."); + } + return userResourceProfileRepository + .getUserResourceProfile(userId, gatewayID) + .getUserComputeResourcePreferences(); + } catch (Throwable e) { + logger.error("Error while retrieving all user compute resource preferences", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage( + "Error while retrieving all user compute resource preferences More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllUserStoragePreferences(String userId, String gatewayID) + throws RegistryServiceException { + try { + if (!userRepository.isUserExists(gatewayID, userId)) { + logger.error("User does not exist.Please provide a valid gateway id..."); + throw new AppCatalogException("Gateway does not exist.Please provide a valid gateway id..."); + } + return userResourceProfileRepository + .getUserResourceProfile(userId, gatewayID) + .getUserStoragePreferences(); + } catch (Throwable e) { + logger.error("Error while retrieving all user storage preferences", e); + RegistryServiceException exception = new RegistryServiceException(); + exception.setMessage("Error while retrieving all user storage preferences More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } +} diff --git a/airavata-api/src/main/java/org/apache/airavata/service/SharingRegistryService.java b/airavata-api/src/main/java/org/apache/airavata/service/SharingRegistryService.java new file mode 100644 index 0000000000..1595cff025 --- /dev/null +++ b/airavata-api/src/main/java/org/apache/airavata/service/SharingRegistryService.java @@ -0,0 +1,1517 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.airavata.service; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.*; +import org.apache.airavata.sharing.registry.db.entities.*; +import org.apache.airavata.sharing.registry.db.repositories.*; +import org.apache.airavata.sharing.registry.db.utils.DBConstants; +import org.apache.airavata.sharing.registry.models.*; +import org.apache.commons.lang3.exception.ExceptionUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SharingRegistryService { + private static final Logger logger = LoggerFactory.getLogger(SharingRegistryService.class); + + public static String OWNER_PERMISSION_NAME = "OWNER"; + + /** + * * Domain Operations + * * + */ + public String createDomain(Domain domain) throws SharingRegistryException, DuplicateEntryException { + try { + if ((new DomainRepository()).get(domain.getDomainId()) != null) + throw new DuplicateEntryException("There exist domain with given domain id"); + + domain.setCreatedTime(System.currentTimeMillis()); + domain.setUpdatedTime(System.currentTimeMillis()); + (new DomainRepository()).create(domain); + + // create the global permission for the domain + PermissionType permissionType = new PermissionType(); + permissionType.setPermissionTypeId(domain.getDomainId() + ":" + OWNER_PERMISSION_NAME); + permissionType.setDomainId(domain.getDomainId()); + permissionType.setName(OWNER_PERMISSION_NAME); + permissionType.setDescription("GLOBAL permission to " + domain.getDomainId()); + permissionType.setCreatedTime(System.currentTimeMillis()); + permissionType.setUpdatedTime(System.currentTimeMillis()); + (new PermissionTypeRepository()).create(permissionType); + + return domain.getDomainId(); + } catch (SharingRegistryException | DuplicateEntryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while creating domain: domainId=" + domain.getDomainId() + ", " + ex.getMessage(); + logger.error(msg, ex); + SharingRegistryException exception = + new SharingRegistryException(msg + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); + exception.initCause(ex); + throw exception; + } + } + + public boolean updateDomain(Domain domain) throws SharingRegistryException { + try { + Domain oldDomain = (new DomainRepository()).get(domain.getDomainId()); + domain.setCreatedTime(oldDomain.getCreatedTime()); + domain.setUpdatedTime(System.currentTimeMillis()); + domain = getUpdatedObject(oldDomain, domain); + (new DomainRepository()).update(domain); + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while updating domain: domainId=" + domain.getDomainId() + ", " + ex.getMessage(); + logger.error(msg, ex); + SharingRegistryException exception = + new SharingRegistryException(msg + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); + exception.initCause(ex); + throw exception; + } + } + + public boolean isDomainExists(String domainId) throws SharingRegistryException { + try { + return (new DomainRepository()).isExists(domainId); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while checking if domain exists: domainId=" + domainId + ", " + ex.getMessage(); + logger.error(msg, ex); + SharingRegistryException exception = + new SharingRegistryException(msg + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); + exception.initCause(ex); + throw exception; + } + } + + public boolean deleteDomain(String domainId) throws SharingRegistryException { + try { + (new DomainRepository()).delete(domainId); + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while deleting domain: domainId=" + domainId + ", " + ex.getMessage(); + logger.error(msg, ex); + SharingRegistryException exception = + new SharingRegistryException(msg + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); + exception.initCause(ex); + throw exception; + } + } + + public Domain getDomain(String domainId) throws SharingRegistryException { + try { + return (new DomainRepository()).get(domainId); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while getting domain: domainId=" + domainId + ", " + ex.getMessage(); + logger.error(msg, ex); + SharingRegistryException exception = + new SharingRegistryException(msg + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); + exception.initCause(ex); + throw exception; + } + } + + public List getDomains(int offset, int limit) throws SharingRegistryException { + try { + return (new DomainRepository()).select(new HashMap<>(), offset, limit); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while getting domains: offset=" + offset + ", limit=" + limit + ", " + ex.getMessage(); + logger.error(msg, ex); + SharingRegistryException exception = + new SharingRegistryException(msg + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); + exception.initCause(ex); + throw exception; + } + } + + /** + * * User Operations + * * + */ + public String createUser(User user) throws SharingRegistryException { + try { + UserPK userPK = new UserPK(); + userPK.setUserId(user.getUserId()); + userPK.setDomainId(user.getDomainId()); + if ((new UserRepository()).get(userPK) != null) + throw new SharingRegistryException("There exist user with given user id"); + + user.setCreatedTime(System.currentTimeMillis()); + user.setUpdatedTime(System.currentTimeMillis()); + (new UserRepository()).create(user); + + UserGroup userGroup = new UserGroup(); + userGroup.setGroupId(user.getUserId()); + userGroup.setDomainId(user.getDomainId()); + userGroup.setName(user.getUserName()); + userGroup.setDescription("user " + user.getUserName() + " group"); + userGroup.setOwnerId(user.getUserId()); + userGroup.setGroupType(GroupType.USER_LEVEL_GROUP); + userGroup.setGroupCardinality(GroupCardinality.SINGLE_USER); + (new UserGroupRepository()).create(userGroup); + + Domain domain = new DomainRepository().get(user.getDomainId()); + if (domain.getInitialUserGroupId() != null) { + addUsersToGroup( + user.getDomainId(), + Collections.singletonList(user.getUserId()), + domain.getInitialUserGroupId()); + } + + return user.getUserId(); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while creating user: userId=" + user.getUserId() + ", domainId=" + user.getDomainId() + + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean updatedUser(User user) throws SharingRegistryException { + try { + UserPK userPK = new UserPK(); + userPK.setUserId(user.getUserId()); + userPK.setDomainId(user.getDomainId()); + User oldUser = (new UserRepository()).get(userPK); + user.setCreatedTime(oldUser.getCreatedTime()); + user.setUpdatedTime(System.currentTimeMillis()); + user = getUpdatedObject(oldUser, user); + (new UserRepository()).update(user); + + UserGroupPK userGroupPK = new UserGroupPK(); + userGroupPK.setGroupId(user.getUserId()); + userGroupPK.setDomainId(user.getDomainId()); + UserGroup userGroup = (new UserGroupRepository()).get(userGroupPK); + userGroup.setName(user.getUserName()); + userGroup.setDescription("user " + user.getUserName() + " group"); + updateGroup(userGroup); + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while updating user: userId=" + user.getUserId() + ", domainId=" + user.getDomainId() + + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean isUserExists(String domainId, String userId) throws SharingRegistryException { + try { + UserPK userPK = new UserPK(); + userPK.setDomainId(domainId); + userPK.setUserId(userId); + return (new UserRepository()).isExists(userPK); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while checking if user exists: domainId=" + domainId + ", userId=" + userId + ", " + + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean deleteUser(String domainId, String userId) throws SharingRegistryException { + try { + UserPK userPK = new UserPK(); + userPK.setUserId(userId); + userPK.setDomainId(domainId); + (new UserRepository()).delete(userPK); + + UserGroupPK userGroupPK = new UserGroupPK(); + userGroupPK.setGroupId(userId); + userGroupPK.setDomainId(domainId); + (new UserGroupRepository()).delete(userGroupPK); + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = + "Error while deleting user: domainId=" + domainId + ", userId=" + userId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public User getUser(String domainId, String userId) throws SharingRegistryException { + try { + UserPK userPK = new UserPK(); + userPK.setUserId(userId); + userPK.setDomainId(domainId); + return (new UserRepository()).get(userPK); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = + "Error while getting user: domainId=" + domainId + ", userId=" + userId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getUsers(String domain, int offset, int limit) throws SharingRegistryException { + try { + HashMap filters = new HashMap<>(); + filters.put(DBConstants.UserTable.DOMAIN_ID, domain); + return (new UserRepository()).select(filters, offset, limit); + } catch (Throwable ex) { + String msg = "Error while getting users: domain=" + domain + ", offset=" + offset + ", limit=" + limit + + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + /** + * * Group Operations + * * + */ + public String createGroup(UserGroup group) throws SharingRegistryException { + try { + UserGroupPK userGroupPK = new UserGroupPK(); + userGroupPK.setGroupId(group.getGroupId()); + userGroupPK.setDomainId(group.getDomainId()); + if ((new UserGroupRepository()).get(userGroupPK) != null) + throw new SharingRegistryException("There exist group with given group id"); + // Client created groups are always of type MULTI_USER + group.setGroupCardinality(GroupCardinality.MULTI_USER); + group.setCreatedTime(System.currentTimeMillis()); + group.setUpdatedTime(System.currentTimeMillis()); + // Add group admins once the group is created + group.unsetGroupAdmins(); + (new UserGroupRepository()).create(group); + + addUsersToGroup(group.getDomainId(), Arrays.asList(group.getOwnerId()), group.getGroupId()); + return group.getGroupId(); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while creating group: groupId=" + group.getGroupId() + ", domainId=" + + group.getDomainId() + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean updateGroup(UserGroup group) throws SharingRegistryException { + try { + group.setUpdatedTime(System.currentTimeMillis()); + UserGroupPK userGroupPK = new UserGroupPK(); + userGroupPK.setGroupId(group.getGroupId()); + userGroupPK.setDomainId(group.getDomainId()); + UserGroup oldGroup = (new UserGroupRepository()).get(userGroupPK); + group.setGroupCardinality(oldGroup.getGroupCardinality()); + group.setCreatedTime(oldGroup.getCreatedTime()); + group = getUpdatedObject(oldGroup, group); + + if (!group.getOwnerId().equals(oldGroup.getOwnerId())) + throw new SharingRegistryException("Group owner cannot be changed"); + + (new UserGroupRepository()).update(group); + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while updating group: groupId=" + group.getGroupId() + ", domainId=" + + group.getDomainId() + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean isGroupExists(String domainId, String groupId) throws SharingRegistryException { + try { + UserGroupPK userGroupPK = new UserGroupPK(); + userGroupPK.setDomainId(domainId); + userGroupPK.setGroupId(groupId); + return (new UserGroupRepository()).isExists(userGroupPK); + } catch (Throwable ex) { + String msg = "Error while checking if group exists: domainId=" + domainId + ", groupId=" + groupId + ", " + + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean deleteGroup(String domainId, String groupId) throws SharingRegistryException { + try { + UserGroupPK userGroupPK = new UserGroupPK(); + userGroupPK.setGroupId(groupId); + userGroupPK.setDomainId(domainId); + (new UserGroupRepository()).delete(userGroupPK); + return true; + } catch (Throwable ex) { + String msg = "Error while deleting group: domainId=" + domainId + ", groupId=" + groupId + ", " + + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public UserGroup getGroup(String domainId, String groupId) throws SharingRegistryException { + try { + UserGroupPK userGroupPK = new UserGroupPK(); + userGroupPK.setGroupId(groupId); + userGroupPK.setDomainId(domainId); + return (new UserGroupRepository()).get(userGroupPK); + } catch (Throwable ex) { + String msg = + "Error while getting group: domainId=" + domainId + ", groupId=" + groupId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getGroups(String domain, int offset, int limit) throws SharingRegistryException { + try { + HashMap filters = new HashMap<>(); + filters.put(DBConstants.UserGroupTable.DOMAIN_ID, domain); + // Only return groups with MULTI_USER cardinality which is the only type of cardinality allowed for client + // created groups + filters.put(DBConstants.UserGroupTable.GROUP_CARDINALITY, GroupCardinality.MULTI_USER.name()); + return (new UserGroupRepository()).select(filters, offset, limit); + } catch (Throwable ex) { + String msg = "Error while getting groups: domain=" + domain + ", offset=" + offset + ", limit=" + limit + + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean addUsersToGroup(String domainId, List userIds, String groupId) + throws SharingRegistryException { + try { + for (int i = 0; i < userIds.size(); i++) { + GroupMembership groupMembership = new GroupMembership(); + groupMembership.setParentId(groupId); + groupMembership.setChildId(userIds.get(i)); + groupMembership.setChildType(GroupChildType.USER); + groupMembership.setDomainId(domainId); + groupMembership.setCreatedTime(System.currentTimeMillis()); + groupMembership.setUpdatedTime(System.currentTimeMillis()); + (new GroupMembershipRepository()).create(groupMembership); + } + return true; + } catch (Throwable ex) { + String msg = "Error while adding users to group: domainId=" + domainId + ", userIds=" + userIds + + ", groupId=" + groupId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean removeUsersFromGroup(String domainId, List userIds, String groupId) + throws SharingRegistryException { + try { + for (String userId : userIds) { + if (hasOwnerAccess(domainId, groupId, userId)) { + throw new SharingRegistryException( + "List of User Ids contains Owner Id. Cannot remove owner from the group"); + } + } + + for (int i = 0; i < userIds.size(); i++) { + GroupMembershipPK groupMembershipPK = new GroupMembershipPK(); + groupMembershipPK.setParentId(groupId); + groupMembershipPK.setChildId(userIds.get(i)); + groupMembershipPK.setDomainId(domainId); + (new GroupMembershipRepository()).delete(groupMembershipPK); + } + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while removing users from group: domainId=" + domainId + ", userIds=" + userIds + + ", groupId=" + groupId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean transferGroupOwnership(String domainId, String groupId, String newOwnerId) + throws SharingRegistryException { + try { + List groupUser = getGroupMembersOfTypeUser(domainId, groupId, 0, -1); + if (!isUserBelongsToGroup(groupUser, newOwnerId)) { + throw new SharingRegistryException("New group owner is not part of the group"); + } + + if (hasOwnerAccess(domainId, groupId, newOwnerId)) { + throw new DuplicateEntryException("User already the current owner of the group"); + } + // remove the new owner as Admin if present + if (hasAdminAccess(domainId, groupId, newOwnerId)) { + removeGroupAdmins(domainId, groupId, Arrays.asList(newOwnerId)); + } + + UserGroupPK userGroupPK = new UserGroupPK(); + userGroupPK.setGroupId(groupId); + userGroupPK.setDomainId(domainId); + UserGroup userGroup = (new UserGroupRepository()).get(userGroupPK); + UserGroup newUserGroup = new UserGroup(); + newUserGroup.setUpdatedTime(System.currentTimeMillis()); + newUserGroup.setOwnerId(newOwnerId); + newUserGroup.setGroupCardinality(GroupCardinality.MULTI_USER); + newUserGroup.setCreatedTime(userGroup.getCreatedTime()); + newUserGroup = getUpdatedObject(userGroup, newUserGroup); + + (new UserGroupRepository()).update(newUserGroup); + + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while transferring group ownership: domainId=" + domainId + ", groupId=" + groupId + + ", newOwnerId=" + newOwnerId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + private boolean isUserBelongsToGroup(List groupUser, String newOwnerId) { + for (User user : groupUser) { + if (user.getUserId().equals(newOwnerId)) { + return true; + } + } + return false; + } + + public boolean addGroupAdmins(String domainId, String groupId, List adminIds) + throws SharingRegistryException { + try { + List groupUser = getGroupMembersOfTypeUser(domainId, groupId, 0, -1); + + for (String adminId : adminIds) { + if (!isUserBelongsToGroup(groupUser, adminId)) { + throw new SharingRegistryException( + "Admin not the user of the group. GroupId : " + groupId + ", AdminId : " + adminId); + } + GroupAdminPK groupAdminPK = new GroupAdminPK(); + groupAdminPK.setGroupId(groupId); + groupAdminPK.setAdminId(adminId); + groupAdminPK.setDomainId(domainId); + + if ((new GroupAdminRepository()).get(groupAdminPK) != null) + throw new DuplicateEntryException("User already an admin for the group"); + + GroupAdmin admin = new GroupAdmin(); + admin.setAdminId(adminId); + admin.setDomainId(domainId); + admin.setGroupId(groupId); + (new GroupAdminRepository()).create(admin); + } + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while adding group admins: domainId=" + domainId + ", groupId=" + groupId + + ", adminIds=" + adminIds + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean removeGroupAdmins(String domainId, String groupId, List adminIds) + throws SharingRegistryException { + try { + for (String adminId : adminIds) { + GroupAdminPK groupAdminPK = new GroupAdminPK(); + groupAdminPK.setAdminId(adminId); + groupAdminPK.setDomainId(domainId); + groupAdminPK.setGroupId(groupId); + (new GroupAdminRepository()).delete(groupAdminPK); + } + return true; + } catch (Throwable ex) { + String msg = "Error while removing group admins: domainId=" + domainId + ", groupId=" + groupId + + ", adminIds=" + adminIds + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean hasAdminAccess(String domainId, String groupId, String adminId) throws SharingRegistryException { + try { + GroupAdminPK groupAdminPK = new GroupAdminPK(); + groupAdminPK.setGroupId(groupId); + groupAdminPK.setAdminId(adminId); + groupAdminPK.setDomainId(domainId); + + if ((new GroupAdminRepository()).get(groupAdminPK) != null) return true; + return false; + } catch (Throwable ex) { + String msg = "Error while checking admin access: domainId=" + domainId + ", groupId=" + groupId + + ", adminId=" + adminId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean hasOwnerAccess(String domainId, String groupId, String ownerId) throws SharingRegistryException { + try { + UserGroupPK userGroupPK = new UserGroupPK(); + userGroupPK.setGroupId(groupId); + userGroupPK.setDomainId(domainId); + UserGroup getGroup = (new UserGroupRepository()).get(userGroupPK); + + if (getGroup.getOwnerId().equals(ownerId)) return true; + return false; + } catch (Throwable ex) { + String msg = "Error while checking owner access: domainId=" + domainId + ", groupId=" + groupId + + ", ownerId=" + ownerId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getGroupMembersOfTypeUser(String domainId, String groupId, int offset, int limit) + throws SharingRegistryException { + try { + // TODO limit offset + List groupMemberUsers = (new GroupMembershipRepository()).getAllChildUsers(domainId, groupId); + return groupMemberUsers; + } catch (Throwable ex) { + String msg = "Error while getting group members of type user: domainId=" + domainId + ", groupId=" + groupId + + ", offset=" + offset + ", limit=" + limit + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getGroupMembersOfTypeGroup(String domainId, String groupId, int offset, int limit) + throws SharingRegistryException { + try { + // TODO limit offset + List groupMemberGroups = (new GroupMembershipRepository()).getAllChildGroups(domainId, groupId); + return groupMemberGroups; + } catch (Throwable ex) { + String msg = "Error while getting group members of type group: domainId=" + domainId + ", groupId=" + + groupId + ", offset=" + offset + ", limit=" + limit + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean addChildGroupsToParentGroup(String domainId, List childIds, String groupId) + throws SharingRegistryException { + try { + for (String childId : childIds) { + // Todo check for cyclic dependencies + GroupMembership groupMembership = new GroupMembership(); + groupMembership.setParentId(groupId); + groupMembership.setChildId(childId); + groupMembership.setChildType(GroupChildType.GROUP); + groupMembership.setDomainId(domainId); + groupMembership.setCreatedTime(System.currentTimeMillis()); + groupMembership.setUpdatedTime(System.currentTimeMillis()); + (new GroupMembershipRepository()).create(groupMembership); + } + return true; + } catch (Throwable ex) { + String msg = "Error while adding child groups to parent group: domainId=" + domainId + ", childIds=" + + childIds + ", groupId=" + groupId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean removeChildGroupFromParentGroup(String domainId, String childId, String groupId) + throws SharingRegistryException { + try { + GroupMembershipPK groupMembershipPK = new GroupMembershipPK(); + groupMembershipPK.setParentId(groupId); + groupMembershipPK.setChildId(childId); + groupMembershipPK.setDomainId(domainId); + (new GroupMembershipRepository()).delete(groupMembershipPK); + return true; + } catch (Throwable ex) { + String msg = "Error while removing child group from parent group: domainId=" + domainId + ", childId=" + + childId + ", groupId=" + groupId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getAllMemberGroupsForUser(String domainId, String userId) throws SharingRegistryException { + try { + GroupMembershipRepository groupMembershipRepository = new GroupMembershipRepository(); + return groupMembershipRepository.getAllMemberGroupsForUser(domainId, userId); + } catch (Throwable ex) { + String msg = "Error while getting all member groups for user: domainId=" + domainId + ", userId=" + userId + + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + /** + * * EntityType Operations + * * + */ + public String createEntityType(EntityType entityType) throws SharingRegistryException, DuplicateEntryException { + try { + EntityTypePK entityTypePK = new EntityTypePK(); + entityTypePK.setDomainId(entityType.getDomainId()); + entityTypePK.setEntityTypeId(entityType.getEntityTypeId()); + if ((new EntityTypeRepository()).get(entityTypePK) != null) + throw new DuplicateEntryException("There exist EntityType with given EntityType id"); + + entityType.setCreatedTime(System.currentTimeMillis()); + entityType.setUpdatedTime(System.currentTimeMillis()); + (new EntityTypeRepository()).create(entityType); + return entityType.getEntityTypeId(); + } catch (SharingRegistryException | DuplicateEntryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while creating entity type: entityTypeId=" + entityType.getEntityTypeId() + + ", domainId=" + entityType.getDomainId() + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean updateEntityType(EntityType entityType) throws SharingRegistryException { + try { + entityType.setUpdatedTime(System.currentTimeMillis()); + EntityTypePK entityTypePK = new EntityTypePK(); + entityTypePK.setDomainId(entityType.getDomainId()); + entityTypePK.setEntityTypeId(entityType.getEntityTypeId()); + EntityType oldEntityType = (new EntityTypeRepository()).get(entityTypePK); + entityType.setCreatedTime(oldEntityType.getCreatedTime()); + entityType = getUpdatedObject(oldEntityType, entityType); + (new EntityTypeRepository()).update(entityType); + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while updating entity type: entityTypeId=" + entityType.getEntityTypeId() + + ", domainId=" + entityType.getDomainId() + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean isEntityTypeExists(String domainId, String entityTypeId) throws SharingRegistryException { + try { + EntityTypePK entityTypePK = new EntityTypePK(); + entityTypePK.setDomainId(domainId); + entityTypePK.setEntityTypeId(entityTypeId); + return (new EntityTypeRepository()).isExists(entityTypePK); + } catch (Throwable ex) { + String msg = "Error while checking if entity type exists: domainId=" + domainId + ", entityTypeId=" + + entityTypeId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean deleteEntityType(String domainId, String entityTypeId) throws SharingRegistryException { + try { + EntityTypePK entityTypePK = new EntityTypePK(); + entityTypePK.setDomainId(domainId); + entityTypePK.setEntityTypeId(entityTypeId); + (new EntityTypeRepository()).delete(entityTypePK); + return true; + } catch (Throwable ex) { + String msg = "Error while deleting entity type: domainId=" + domainId + ", entityTypeId=" + entityTypeId + + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public EntityType getEntityType(String domainId, String entityTypeId) throws SharingRegistryException { + try { + EntityTypePK entityTypePK = new EntityTypePK(); + entityTypePK.setDomainId(domainId); + entityTypePK.setEntityTypeId(entityTypeId); + return (new EntityTypeRepository()).get(entityTypePK); + } catch (Throwable ex) { + String msg = "Error while getting entity type: domainId=" + domainId + ", entityTypeId=" + entityTypeId + + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getEntityTypes(String domain, int offset, int limit) throws SharingRegistryException { + try { + HashMap filters = new HashMap<>(); + filters.put(DBConstants.EntityTypeTable.DOMAIN_ID, domain); + return (new EntityTypeRepository()).select(filters, offset, limit); + } catch (Throwable ex) { + String msg = "Error while getting entity types: domain=" + domain + ", offset=" + offset + ", limit=" + + limit + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + /** + * * Permission Operations + * * + */ + public String createPermissionType(PermissionType permissionType) + throws SharingRegistryException, DuplicateEntryException { + try { + PermissionTypePK permissionTypePK = new PermissionTypePK(); + permissionTypePK.setDomainId(permissionType.getDomainId()); + permissionTypePK.setPermissionTypeId(permissionType.getPermissionTypeId()); + if ((new PermissionTypeRepository()).get(permissionTypePK) != null) + throw new DuplicateEntryException("There exist PermissionType with given PermissionType id"); + permissionType.setCreatedTime(System.currentTimeMillis()); + permissionType.setUpdatedTime(System.currentTimeMillis()); + (new PermissionTypeRepository()).create(permissionType); + return permissionType.getPermissionTypeId(); + } catch (SharingRegistryException | DuplicateEntryException e) { + throw e; + } catch (Throwable ex) { + String msg = + "Error while creating permission type: permissionTypeId=" + permissionType.getPermissionTypeId() + + ", domainId=" + permissionType.getDomainId() + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean updatePermissionType(PermissionType permissionType) throws SharingRegistryException { + try { + permissionType.setUpdatedTime(System.currentTimeMillis()); + PermissionTypePK permissionTypePK = new PermissionTypePK(); + permissionTypePK.setDomainId(permissionType.getDomainId()); + permissionTypePK.setPermissionTypeId(permissionType.getPermissionTypeId()); + PermissionType oldPermissionType = (new PermissionTypeRepository()).get(permissionTypePK); + permissionType = getUpdatedObject(oldPermissionType, permissionType); + (new PermissionTypeRepository()).update(permissionType); + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = + "Error while updating permission type: permissionTypeId=" + permissionType.getPermissionTypeId() + + ", domainId=" + permissionType.getDomainId() + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean isPermissionExists(String domainId, String permissionId) throws SharingRegistryException { + try { + PermissionTypePK permissionTypePK = new PermissionTypePK(); + permissionTypePK.setDomainId(domainId); + permissionTypePK.setPermissionTypeId(permissionId); + return (new PermissionTypeRepository()).isExists(permissionTypePK); + } catch (Throwable ex) { + String msg = "Error while checking if permission exists: domainId=" + domainId + ", permissionId=" + + permissionId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean deletePermissionType(String domainId, String permissionTypeId) throws SharingRegistryException { + try { + PermissionTypePK permissionTypePK = new PermissionTypePK(); + permissionTypePK.setDomainId(domainId); + permissionTypePK.setPermissionTypeId(permissionTypeId); + (new PermissionTypeRepository()).delete(permissionTypePK); + return true; + } catch (Throwable ex) { + String msg = "Error while deleting permission type: domainId=" + domainId + ", permissionTypeId=" + + permissionTypeId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public PermissionType getPermissionType(String domainId, String permissionTypeId) throws SharingRegistryException { + try { + PermissionTypePK permissionTypePK = new PermissionTypePK(); + permissionTypePK.setDomainId(domainId); + permissionTypePK.setPermissionTypeId(permissionTypeId); + return (new PermissionTypeRepository()).get(permissionTypePK); + } catch (Throwable ex) { + String msg = "Error while getting permission type: domainId=" + domainId + ", permissionTypeId=" + + permissionTypeId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getPermissionTypes(String domain, int offset, int limit) + throws SharingRegistryException { + try { + HashMap filters = new HashMap<>(); + filters.put(DBConstants.PermissionTypeTable.DOMAIN_ID, domain); + return (new PermissionTypeRepository()).select(filters, offset, limit); + } catch (Throwable ex) { + String msg = "Error while getting permission types: domain=" + domain + ", offset=" + offset + ", limit=" + + limit + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + /** + * * Entity Operations + * * + */ + public String createEntity(Entity entity) throws SharingRegistryException, DuplicateEntryException { + try { + EntityPK entityPK = new EntityPK(); + entityPK.setDomainId(entity.getDomainId()); + entityPK.setEntityId(entity.getEntityId()); + if ((new EntityRepository()).get(entityPK) != null) + throw new DuplicateEntryException("There exist Entity with given Entity id"); + + UserPK userPK = new UserPK(); + userPK.setDomainId(entity.getDomainId()); + userPK.setUserId(entity.getOwnerId()); + if (!(new UserRepository()).isExists(userPK)) { + // Todo this is for Airavata easy integration. Proper thing is to throw an exception here + User user = new User(); + user.setUserId(entity.getOwnerId()); + user.setDomainId(entity.getDomainId()); + user.setUserName(user.getUserId().split("@")[0]); + + createUser(user); + } + entity.setCreatedTime(System.currentTimeMillis()); + entity.setUpdatedTime(System.currentTimeMillis()); + + if (entity.getOriginalEntityCreationTime() == 0) { + entity.setOriginalEntityCreationTime(entity.getCreatedTime()); + } + (new EntityRepository()).create(entity); + + // Assigning global permission for the owner + Sharing newSharing = new Sharing(); + newSharing.setPermissionTypeId( + (new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(entity.getDomainId())); + newSharing.setEntityId(entity.getEntityId()); + newSharing.setGroupId(entity.getOwnerId()); + newSharing.setSharingType(SharingType.DIRECT_CASCADING); + newSharing.setInheritedParentId(entity.getEntityId()); + newSharing.setDomainId(entity.getDomainId()); + newSharing.setCreatedTime(System.currentTimeMillis()); + newSharing.setUpdatedTime(System.currentTimeMillis()); + + (new SharingRepository()).create(newSharing); + + // creating records for inherited permissions + if (entity.getParentEntityId() != null && entity.getParentEntityId() != "") { + addCascadingPermissionsForEntity(entity); + } + + return entity.getEntityId(); + } catch (SharingRegistryException | DuplicateEntryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while creating entity: entityId=" + entity.getEntityId() + ", domainId=" + + entity.getDomainId() + ", ownerId=" + entity.getOwnerId() + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + private void addCascadingPermissionsForEntity(Entity entity) throws SharingRegistryException { + try { + Sharing newSharing; + List sharings = (new SharingRepository()) + .getCascadingPermissionsForEntity(entity.getDomainId(), entity.getParentEntityId()); + for (Sharing sharing : sharings) { + newSharing = new Sharing(); + newSharing.setPermissionTypeId(sharing.getPermissionTypeId()); + newSharing.setEntityId(entity.getEntityId()); + newSharing.setGroupId(sharing.getGroupId()); + newSharing.setInheritedParentId(sharing.getInheritedParentId()); + newSharing.setSharingType(SharingType.INDIRECT_CASCADING); + newSharing.setDomainId(entity.getDomainId()); + newSharing.setCreatedTime(System.currentTimeMillis()); + newSharing.setUpdatedTime(System.currentTimeMillis()); + + (new SharingRepository()).create(newSharing); + } + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while adding cascading permissions for entity: entityId=" + entity.getEntityId() + + ", domainId=" + entity.getDomainId() + ", parentEntityId=" + entity.getParentEntityId() + ", " + + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean updateEntity(Entity entity) throws SharingRegistryException { + try { + // TODO Check for permission changes + entity.setUpdatedTime(System.currentTimeMillis()); + EntityPK entityPK = new EntityPK(); + entityPK.setDomainId(entity.getDomainId()); + entityPK.setEntityId(entity.getEntityId()); + Entity oldEntity = (new EntityRepository()).get(entityPK); + entity.setCreatedTime(oldEntity.getCreatedTime()); + // check if parent entity changed and re-add inherited permissions + if (!Objects.equals(oldEntity.getParentEntityId(), entity.getParentEntityId())) { + logger.debug("Parent entity changed for {}, updating inherited permissions", entity.getEntityId()); + if (oldEntity.getParentEntityId() != null && oldEntity.getParentEntityId() != "") { + logger.debug( + "Removing inherited permissions from {} that were inherited from parent {}", + entity.getEntityId(), + oldEntity.getParentEntityId()); + (new SharingRepository()) + .removeAllIndirectCascadingPermissionsForEntity(entity.getDomainId(), entity.getEntityId()); + } + if (entity.getParentEntityId() != null && entity.getParentEntityId() != "") { + // re-add INDIRECT_CASCADING permissions + logger.debug( + "Adding inherited permissions to {} that are inherited from parent {}", + entity.getEntityId(), + entity.getParentEntityId()); + addCascadingPermissionsForEntity(entity); + } + } + entity = getUpdatedObject(oldEntity, entity); + entity.setSharedCount((new SharingRepository()).getSharedCount(entity.getDomainId(), entity.getEntityId())); + (new EntityRepository()).update(entity); + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while updating entity: entityId=" + entity.getEntityId() + ", domainId=" + + entity.getDomainId() + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean isEntityExists(String domainId, String entityId) throws SharingRegistryException { + try { + EntityPK entityPK = new EntityPK(); + entityPK.setDomainId(domainId); + entityPK.setEntityId(entityId); + return (new EntityRepository()).isExists(entityPK); + } catch (Throwable ex) { + String msg = "Error while checking if entity exists: domainId=" + domainId + ", entityId=" + entityId + ", " + + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean deleteEntity(String domainId, String entityId) throws SharingRegistryException { + try { + // TODO Check for permission changes + EntityPK entityPK = new EntityPK(); + entityPK.setDomainId(domainId); + entityPK.setEntityId(entityId); + (new EntityRepository()).delete(entityPK); + return true; + } catch (Throwable ex) { + String msg = "Error while deleting entity: domainId=" + domainId + ", entityId=" + entityId + ", " + + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public Entity getEntity(String domainId, String entityId) throws SharingRegistryException { + try { + EntityPK entityPK = new EntityPK(); + entityPK.setDomainId(domainId); + entityPK.setEntityId(entityId); + return (new EntityRepository()).get(entityPK); + } catch (Throwable ex) { + String msg = "Error while getting entity: domainId=" + domainId + ", entityId=" + entityId + ", " + + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List searchEntities( + String domainId, String userId, List filters, int offset, int limit) + throws SharingRegistryException { + try { + List groupIds = new ArrayList<>(); + groupIds.add(userId); + (new GroupMembershipRepository()) + .getAllParentMembershipsForChild(domainId, userId).stream() + .forEach(gm -> groupIds.add(gm.getParentId())); + return (new EntityRepository()).searchEntities(domainId, groupIds, filters, offset, limit); + } catch (Throwable ex) { + String msg = "Error while searching entities: domainId=" + domainId + ", userId=" + userId + ", filters=" + + filters + ", offset=" + offset + ", limit=" + limit + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getListOfSharedUsers(String domainId, String entityId, String permissionTypeId) + throws SharingRegistryException { + try { + return (new UserRepository()).getAccessibleUsers(domainId, entityId, permissionTypeId); + } catch (Throwable ex) { + String msg = "Error while getting list of shared users: domainId=" + domainId + ", entityId=" + entityId + + ", permissionTypeId=" + permissionTypeId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getListOfDirectlySharedUsers(String domainId, String entityId, String permissionTypeId) + throws SharingRegistryException { + try { + return (new UserRepository()).getDirectlyAccessibleUsers(domainId, entityId, permissionTypeId); + } catch (Throwable ex) { + String msg = "Error while getting list of directly shared users: domainId=" + domainId + ", entityId=" + + entityId + ", permissionTypeId=" + permissionTypeId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getListOfSharedGroups(String domainId, String entityId, String permissionTypeId) + throws SharingRegistryException { + try { + return (new UserGroupRepository()).getAccessibleGroups(domainId, entityId, permissionTypeId); + } catch (Throwable ex) { + String msg = "Error while getting list of shared groups: domainId=" + domainId + ", entityId=" + entityId + + ", permissionTypeId=" + permissionTypeId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public List getListOfDirectlySharedGroups(String domainId, String entityId, String permissionTypeId) + throws SharingRegistryException { + try { + return (new UserGroupRepository()).getDirectlyAccessibleGroups(domainId, entityId, permissionTypeId); + } catch (Throwable ex) { + String msg = "Error while getting list of directly shared groups: domainId=" + domainId + ", entityId=" + + entityId + ", permissionTypeId=" + permissionTypeId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean shareEntityWithUsers( + String domainId, String entityId, List userList, String permissionTypeId, boolean cascadePermission) + throws SharingRegistryException { + try { + return shareEntity(domainId, entityId, userList, permissionTypeId, cascadePermission); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while sharing entity with users: domainId=" + domainId + ", entityId=" + entityId + + ", userList=" + userList + ", permissionTypeId=" + permissionTypeId + ", cascadePermission=" + + cascadePermission + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean shareEntityWithGroups( + String domainId, + String entityId, + List groupList, + String permissionTypeId, + boolean cascadePermission) + throws SharingRegistryException { + try { + return shareEntity(domainId, entityId, groupList, permissionTypeId, cascadePermission); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while sharing entity with groups: domainId=" + domainId + ", entityId=" + entityId + + ", groupList=" + groupList + ", permissionTypeId=" + permissionTypeId + ", cascadePermission=" + + cascadePermission + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + private boolean shareEntity( + String domainId, + String entityId, + List groupOrUserList, + String permissionTypeId, + boolean cascadePermission) + throws SharingRegistryException { + try { + if (permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))) { + throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be assigned or removed"); + } + + List sharings = new ArrayList<>(); + + // Adding permission for the specified users/groups for the specified entity + LinkedList temp = new LinkedList<>(); + for (String userId : groupOrUserList) { + Sharing sharing = new Sharing(); + sharing.setPermissionTypeId(permissionTypeId); + sharing.setEntityId(entityId); + sharing.setGroupId(userId); + sharing.setInheritedParentId(entityId); + sharing.setDomainId(domainId); + if (cascadePermission) { + sharing.setSharingType(SharingType.DIRECT_CASCADING); + } else { + sharing.setSharingType(SharingType.DIRECT_NON_CASCADING); + } + sharing.setCreatedTime(System.currentTimeMillis()); + sharing.setUpdatedTime(System.currentTimeMillis()); + + sharings.add(sharing); + } + + if (cascadePermission) { + // Adding permission for the specified users/groups for all child entities + (new EntityRepository()) + .getChildEntities(domainId, entityId).stream().forEach(e -> temp.addLast(e)); + while (temp.size() > 0) { + Entity entity = temp.pop(); + String childEntityId = entity.getEntityId(); + for (String userId : groupOrUserList) { + Sharing sharing = new Sharing(); + sharing.setPermissionTypeId(permissionTypeId); + sharing.setEntityId(childEntityId); + sharing.setGroupId(userId); + sharing.setInheritedParentId(entityId); + sharing.setSharingType(SharingType.INDIRECT_CASCADING); + sharing.setInheritedParentId(entityId); + sharing.setDomainId(domainId); + sharing.setCreatedTime(System.currentTimeMillis()); + sharing.setUpdatedTime(System.currentTimeMillis()); + sharings.add(sharing); + (new EntityRepository()) + .getChildEntities(domainId, childEntityId).stream() + .forEach(e -> temp.addLast(e)); + } + } + } + (new SharingRepository()).create(sharings); + + EntityPK entityPK = new EntityPK(); + entityPK.setDomainId(domainId); + entityPK.setEntityId(entityId); + Entity entity = (new EntityRepository()).get(entityPK); + entity.setSharedCount((new SharingRepository()).getSharedCount(domainId, entityId)); + (new EntityRepository()).update(entity); + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while sharing entity: domainId=" + domainId + ", entityId=" + entityId + + ", groupOrUserList=" + groupOrUserList + ", permissionTypeId=" + permissionTypeId + + ", cascadePermission=" + cascadePermission + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean revokeEntitySharingFromUsers( + String domainId, String entityId, List userList, String permissionTypeId) + throws SharingRegistryException { + try { + if (permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))) { + throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be assigned or removed"); + } + return revokeEntitySharing(domainId, entityId, userList, permissionTypeId); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while revoking entity sharing from users: domainId=" + domainId + ", entityId=" + + entityId + ", userList=" + userList + ", permissionTypeId=" + permissionTypeId + ", " + + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean revokeEntitySharingFromGroups( + String domainId, String entityId, List groupList, String permissionTypeId) + throws SharingRegistryException { + try { + if (permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))) { + throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be assigned or removed"); + } + return revokeEntitySharing(domainId, entityId, groupList, permissionTypeId); + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while revoking entity sharing from groups: domainId=" + domainId + ", entityId=" + + entityId + ", groupList=" + groupList + ", permissionTypeId=" + permissionTypeId + ", " + + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean userHasAccess(String domainId, String userId, String entityId, String permissionTypeId) + throws SharingRegistryException { + try { + // check whether the user has permission directly or indirectly + List parentMemberships = + (new GroupMembershipRepository()).getAllParentMembershipsForChild(domainId, userId); + List groupIds = new ArrayList<>(); + parentMemberships.stream().forEach(pm -> groupIds.add(pm.getParentId())); + groupIds.add(userId); + return (new SharingRepository()) + .hasAccess( + domainId, + entityId, + groupIds, + Arrays.asList( + permissionTypeId, + (new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))); + } catch (Throwable ex) { + String msg = "Error while checking user access: domainId=" + domainId + ", userId=" + userId + ", entityId=" + + entityId + ", permissionTypeId=" + permissionTypeId + ", " + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + public boolean revokeEntitySharing( + String domainId, String entityId, List groupOrUserList, String permissionTypeId) + throws SharingRegistryException { + try { + if (permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))) { + throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be removed"); + } + + // revoking permission for the entity + for (String groupId : groupOrUserList) { + SharingPK sharingPK = new SharingPK(); + sharingPK.setEntityId(entityId); + sharingPK.setGroupId(groupId); + sharingPK.setPermissionTypeId(permissionTypeId); + sharingPK.setInheritedParentId(entityId); + sharingPK.setDomainId(domainId); + + (new SharingRepository()).delete(sharingPK); + } + + // revoking permission from inheritance + List temp = new ArrayList<>(); + (new SharingRepository()) + .getIndirectSharedChildren(domainId, entityId, permissionTypeId).stream() + .forEach(s -> temp.add(s)); + for (Sharing sharing : temp) { + String childEntityId = sharing.getEntityId(); + for (String groupId : groupOrUserList) { + SharingPK sharingPK = new SharingPK(); + sharingPK.setEntityId(childEntityId); + sharingPK.setGroupId(groupId); + sharingPK.setPermissionTypeId(permissionTypeId); + sharingPK.setInheritedParentId(entityId); + sharingPK.setDomainId(domainId); + + (new SharingRepository()).delete(sharingPK); + } + } + + EntityPK entityPK = new EntityPK(); + entityPK.setDomainId(domainId); + entityPK.setEntityId(entityId); + Entity entity = (new EntityRepository()).get(entityPK); + entity.setSharedCount((new SharingRepository()).getSharedCount(domainId, entityId)); + (new EntityRepository()).update(entity); + return true; + } catch (SharingRegistryException e) { + throw e; + } catch (Throwable ex) { + String msg = "Error while revoking entity sharing: domainId=" + domainId + ", entityId=" + entityId + + ", groupOrUserList=" + groupOrUserList + ", permissionTypeId=" + permissionTypeId + ", " + + ex.getMessage(); + logger.error(msg, ex); + var exception = new SharingRegistryException(msg); + exception.initCause(ex); + throw exception; + } + } + + private T getUpdatedObject(T oldEntity, T newEntity) throws SharingRegistryException { + Field[] newEntityFields = newEntity.getClass().getDeclaredFields(); + Hashtable newHT = fieldsToHT(newEntityFields, newEntity); + + Class oldEntityClass = oldEntity.getClass(); + Field[] oldEntityFields = oldEntityClass.getDeclaredFields(); + + for (Field field : oldEntityFields) { + if (!Modifier.isFinal(field.getModifiers())) { + field.setAccessible(true); + Object o = newHT.get(field.getName()); + if (o != null) { + Field f = null; + try { + f = oldEntityClass.getDeclaredField(field.getName()); + f.setAccessible(true); + logger.debug("setting " + f.getName()); + f.set(oldEntity, o); + } catch (Exception e) { + throw new SharingRegistryException(e.getMessage()); + } + } + } + } + return oldEntity; + } + + private static Hashtable fieldsToHT(Field[] fields, Object obj) { + Hashtable hashtable = new Hashtable<>(); + for (Field field : fields) { + field.setAccessible(true); + try { + Object retrievedObject = field.get(obj); + if (retrievedObject != null) { + logger.debug("scanning " + field.getName()); + hashtable.put(field.getName(), field.get(obj)); + } + } catch (IllegalAccessException e) { + e.printStackTrace(); + } + } + return hashtable; + } +} diff --git a/airavata-api/src/main/java/org/apache/airavata/service/TenantProfileService.java b/airavata-api/src/main/java/org/apache/airavata/service/TenantProfileService.java new file mode 100644 index 0000000000..f9d9e72272 --- /dev/null +++ b/airavata-api/src/main/java/org/apache/airavata/service/TenantProfileService.java @@ -0,0 +1,247 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.airavata.service; + +import java.util.List; +import java.util.UUID; +import org.apache.airavata.common.exception.ApplicationSettingsException; +import org.apache.airavata.common.utils.Constants; +import org.apache.airavata.common.utils.DBEventService; +import org.apache.airavata.messaging.core.util.DBEventPublisherUtils; +import org.apache.airavata.model.credential.store.PasswordCredential; +import org.apache.airavata.model.dbevent.CrudType; +import org.apache.airavata.model.dbevent.EntityType; +import org.apache.airavata.model.security.AuthzToken; +import org.apache.airavata.model.workspace.Gateway; +import org.apache.airavata.model.workspace.GatewayApprovalStatus; +import org.apache.airavata.service.profile.commons.tenant.entities.GatewayEntity; +import org.apache.airavata.service.profile.tenant.core.repositories.TenantProfileRepository; +import org.apache.airavata.service.profile.tenant.cpi.exception.TenantProfileServiceException; +import org.apache.thrift.TException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class TenantProfileService { + private static final Logger logger = LoggerFactory.getLogger(TenantProfileService.class); + + private TenantProfileRepository tenantProfileRepository; + private DBEventPublisherUtils dbEventPublisherUtils = new DBEventPublisherUtils(DBEventService.TENANT); + private CredentialStoreService credentialStoreService; + + public TenantProfileService() throws TenantProfileServiceException { + logger.debug("Initializing TenantProfileService"); + this.tenantProfileRepository = new TenantProfileRepository(Gateway.class, GatewayEntity.class); + try { + this.credentialStoreService = new CredentialStoreService(); + } catch (ApplicationSettingsException + | IllegalAccessException + | ClassNotFoundException + | InstantiationException e) { + String msg = "Error initializing TenantProfileService, reason: " + e.getMessage(); + logger.error(msg, e); + var exception = new TenantProfileServiceException(msg); + exception.initCause(e); + throw exception; + } + } + + public String addGateway(AuthzToken authzToken, Gateway gateway) throws TenantProfileServiceException { + try { + // Assign UUID to gateway + gateway.setAiravataInternalGatewayId(UUID.randomUUID().toString()); + if (!checkDuplicateGateway(gateway)) { + // If admin password, copy it in the credential store under the requested gateway's gatewayId + if (gateway.getIdentityServerPasswordToken() != null) { + copyAdminPasswordToGateway(authzToken, gateway); + } + gateway = tenantProfileRepository.create(gateway); + if (gateway != null) { + logger.info("Added Airavata Gateway with Id: " + gateway.getGatewayId()); + // replicate tenant at end-places only if status is APPROVED + if (gateway.getGatewayApprovalStatus().equals(GatewayApprovalStatus.APPROVED)) { + logger.info( + "Gateway with ID: {}, is now APPROVED, replicating to subscribers.", + gateway.getGatewayId()); + dbEventPublisherUtils.publish(EntityType.TENANT, CrudType.CREATE, gateway); + } + // return internal id + return gateway.getAiravataInternalGatewayId(); + } else { + throw new Exception("Gateway object is null."); + } + } else { + throw new TenantProfileServiceException( + "An approved Gateway already exists with the same GatewayId, Name or URL"); + } + } catch (Exception ex) { + logger.error("Error adding gateway-profile, reason: " + ex.getMessage(), ex); + TenantProfileServiceException exception = new TenantProfileServiceException(); + exception.setMessage("Error adding gateway-profile, reason: " + ex.getMessage()); + exception.initCause(ex); + throw exception; + } + } + + public boolean updateGateway(AuthzToken authzToken, Gateway updatedGateway) throws TenantProfileServiceException { + try { + + // if admin password token changes then copy the admin password and store under this gateway id and then + // update the admin password token + Gateway existingGateway = tenantProfileRepository.getGateway(updatedGateway.getAiravataInternalGatewayId()); + if (updatedGateway.getIdentityServerPasswordToken() != null + && (existingGateway.getIdentityServerPasswordToken() == null + || !existingGateway + .getIdentityServerPasswordToken() + .equals(updatedGateway.getIdentityServerPasswordToken()))) { + copyAdminPasswordToGateway(authzToken, updatedGateway); + } + + if (tenantProfileRepository.update(updatedGateway) != null) { + logger.debug("Updated gateway-profile with ID: " + updatedGateway.getGatewayId()); + // replicate tenant at end-places + dbEventPublisherUtils.publish(EntityType.TENANT, CrudType.UPDATE, updatedGateway); + return true; + } else { + return false; + } + } catch (Exception ex) { + logger.error("Error updating gateway-profile, reason: " + ex.getMessage(), ex); + TenantProfileServiceException exception = new TenantProfileServiceException(); + exception.setMessage("Error updating gateway-profile, reason: " + ex.getMessage()); + exception.initCause(ex); + throw exception; + } + } + + public Gateway getGateway(AuthzToken authzToken, String airavataInternalGatewayId) + throws TenantProfileServiceException { + try { + Gateway gateway = tenantProfileRepository.getGateway(airavataInternalGatewayId); + if (gateway == null) { + throw new Exception("Could not find Gateway with internal ID: " + airavataInternalGatewayId); + } + return gateway; + } catch (Exception ex) { + logger.error("Error getting gateway-profile, reason: " + ex.getMessage(), ex); + TenantProfileServiceException exception = new TenantProfileServiceException(); + exception.setMessage("Error getting gateway-profile, reason: " + ex.getMessage()); + exception.initCause(ex); + throw exception; + } + } + + public boolean deleteGateway(AuthzToken authzToken, String airavataInternalGatewayId, String gatewayId) + throws TenantProfileServiceException { + try { + logger.debug("Deleting Airavata gateway-profile with ID: " + gatewayId + "Internal ID: " + + airavataInternalGatewayId); + boolean deleteSuccess = tenantProfileRepository.delete(airavataInternalGatewayId); + if (deleteSuccess) { + // delete tenant at end-places + dbEventPublisherUtils.publish( + EntityType.TENANT, + CrudType.DELETE, + // pass along gateway datamodel, with correct gatewayId; + // approvalstatus is not used for delete, hence set dummy value + new Gateway(gatewayId, GatewayApprovalStatus.DEACTIVATED)); + } + return deleteSuccess; + } catch (Exception ex) { + logger.error("Error deleting gateway-profile, reason: " + ex.getMessage(), ex); + TenantProfileServiceException exception = new TenantProfileServiceException(); + exception.setMessage("Error deleting gateway-profile, reason: " + ex.getMessage()); + exception.initCause(ex); + throw exception; + } + } + + public List getAllGateways(AuthzToken authzToken) throws TenantProfileServiceException { + try { + return tenantProfileRepository.getAllGateways(); + } catch (Exception ex) { + logger.error("Error getting all gateway-profiles, reason: " + ex.getMessage(), ex); + TenantProfileServiceException exception = new TenantProfileServiceException(); + exception.setMessage("Error getting all gateway-profiles, reason: " + ex.getMessage()); + exception.initCause(ex); + throw exception; + } + } + + public boolean isGatewayExist(AuthzToken authzToken, String gatewayId) throws TenantProfileServiceException { + try { + Gateway gateway = tenantProfileRepository.getGateway(gatewayId); + return (gateway != null); + } catch (Exception ex) { + logger.error("Error checking if gateway-profile exists, reason: " + ex.getMessage(), ex); + TenantProfileServiceException exception = new TenantProfileServiceException(); + exception.setMessage("Error checking if gateway-profile exists, reason: " + ex.getMessage()); + exception.initCause(ex); + throw exception; + } + } + + public List getAllGatewaysForUser(AuthzToken authzToken, String requesterUsername) + throws TenantProfileServiceException { + try { + return tenantProfileRepository.getAllGatewaysForUser(requesterUsername); + } catch (Exception ex) { + logger.error("Error getting user's gateway-profiles, reason: " + ex.getMessage(), ex); + TenantProfileServiceException exception = new TenantProfileServiceException(); + exception.setMessage("Error getting user's gateway-profiles, reason: " + ex.getMessage()); + exception.initCause(ex); + throw exception; + } + } + + private boolean checkDuplicateGateway(Gateway gateway) throws TenantProfileServiceException { + try { + Gateway duplicateGateway = tenantProfileRepository.getDuplicateGateway( + gateway.getGatewayId(), gateway.getGatewayName(), gateway.getGatewayURL()); + return duplicateGateway != null; + } catch (Exception ex) { + logger.error("Error checking if duplicate gateway-profile exists, reason: " + ex.getMessage(), ex); + TenantProfileServiceException exception = new TenantProfileServiceException(); + exception.setMessage("Error checking if duplicate gateway-profiles exists, reason: " + ex.getMessage()); + exception.initCause(ex); + throw exception; + } + } + + // admin passwords are stored in credential store in the super portal gateway and need to be + // copied to a credential that is stored in the requested/newly created gateway + private void copyAdminPasswordToGateway(AuthzToken authzToken, Gateway gateway) + throws TException, ApplicationSettingsException { + try { + String requestGatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + PasswordCredential adminPasswordCredential = credentialStoreService.getPasswordCredential( + gateway.getIdentityServerPasswordToken(), requestGatewayId); + adminPasswordCredential.setGatewayId(gateway.getGatewayId()); + String newAdminPasswordCredentialToken = + credentialStoreService.addPasswordCredential(adminPasswordCredential); + gateway.setIdentityServerPasswordToken(newAdminPasswordCredentialToken); + } catch (Exception ex) { + String msg = "Error copying admin password to gateway, reason: " + ex.getMessage(); + logger.error(msg, ex); + var exception = new TenantProfileServiceException(msg); + exception.initCause(ex); + throw exception; + } + } +} diff --git a/airavata-api/src/main/java/org/apache/airavata/service/UserProfileService.java b/airavata-api/src/main/java/org/apache/airavata/service/UserProfileService.java new file mode 100644 index 0000000000..578574d15c --- /dev/null +++ b/airavata-api/src/main/java/org/apache/airavata/service/UserProfileService.java @@ -0,0 +1,243 @@ +/** +* +* Licensed to the Apache Software Foundation (ASF) under one +* or more contributor license agreements. See the NOTICE file +* distributed with this work for additional information +* regarding copyright ownership. The ASF licenses this file +* to you under the Apache License, Version 2.0 (the +* "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, +* software distributed under the License is distributed on an +* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +* KIND, either express or implied. See the License for the +* specific language governing permissions and limitations +* under the License. +*/ +package org.apache.airavata.service; + +import java.util.List; +import org.apache.airavata.common.utils.AiravataUtils; +import org.apache.airavata.common.utils.Constants; +import org.apache.airavata.common.utils.DBEventService; +import org.apache.airavata.common.utils.ServerSettings; +import org.apache.airavata.messaging.core.util.DBEventPublisherUtils; +import org.apache.airavata.model.dbevent.CrudType; +import org.apache.airavata.model.dbevent.EntityType; +import org.apache.airavata.model.security.AuthzToken; +import org.apache.airavata.model.user.Status; +import org.apache.airavata.model.user.UserProfile; +import org.apache.airavata.security.AiravataSecurityException; +import org.apache.airavata.service.profile.client.ProfileServiceClientFactory; +import org.apache.airavata.service.profile.iam.admin.services.cpi.IamAdminServices; +import org.apache.airavata.service.profile.iam.admin.services.cpi.exception.IamAdminServicesException; +import org.apache.airavata.service.profile.user.core.repositories.UserProfileRepository; +import org.apache.airavata.service.profile.user.cpi.exception.UserProfileServiceException; +import org.apache.airavata.service.security.AiravataSecurityManager; +import org.apache.airavata.service.security.SecurityManagerFactory; +import org.apache.airavata.service.security.UserInfo; +import org.apache.thrift.TException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class UserProfileService { + private static final Logger logger = LoggerFactory.getLogger(UserProfileService.class); + + private UserProfileRepository userProfileRepository; + private DBEventPublisherUtils dbEventPublisherUtils = new DBEventPublisherUtils(DBEventService.USER_PROFILE); + + public UserProfileService() { + userProfileRepository = new UserProfileRepository(); + } + + public String initializeUserProfile(AuthzToken authzToken) throws UserProfileServiceException { + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + try { + // Load UserInfo for the access token and create an initial UserProfile from it + UserInfo userInfo = SecurityManagerFactory.getSecurityManager().getUserInfoFromAuthzToken(authzToken); + final UserProfile existingProfile = + userProfileRepository.getUserProfileByIdAndGateWay(userInfo.getUsername(), gatewayId); + // If a user profile already exists, just return the userId + if (existingProfile != null) { + return existingProfile.getUserId(); + } + UserProfile userProfile = new UserProfile(); + userProfile.setUserId(userInfo.getUsername().toLowerCase()); + userProfile.setGatewayId(gatewayId); + userProfile.setAiravataInternalUserId(userProfile.getUserId() + "@" + gatewayId); + userProfile.addToEmails(userInfo.getEmailAddress()); + userProfile.setFirstName(userInfo.getFirstName()); + userProfile.setLastName(userInfo.getLastName()); + userProfile.setCreationTime(AiravataUtils.getCurrentTimestamp().getTime()); + userProfile.setLastAccessTime(AiravataUtils.getCurrentTimestamp().getTime()); + userProfile.setValidUntil(-1); + userProfile.setState(Status.ACTIVE); + userProfile = userProfileRepository.createUserProfile(userProfile); + if (null != userProfile) { + logger.info("Added UserProfile with userId: " + userProfile.getUserId()); + // replicate userProfile at end-places + dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.CREATE, userProfile); + // return userId + return userProfile.getUserId(); + } else { + throw new Exception("User creation failed. Please try again."); + } + } catch (Exception e) { + logger.error("Error while initializing user profile", e); + UserProfileServiceException exception = new UserProfileServiceException(); + exception.setMessage("Error while initializing user profile. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public String addUserProfile(AuthzToken authzToken, UserProfile userProfile) throws UserProfileServiceException { + try { + // Lowercase user id and internal id + userProfile.setUserId(userProfile.getUserId().toLowerCase()); + userProfile.setAiravataInternalUserId(userProfile.getUserId() + "@" + userProfile.getGatewayId()); + userProfile = userProfileRepository.updateUserProfile( + userProfile, getIAMUserProfileUpdater(authzToken, userProfile)); + if (null != userProfile) { + logger.info("Added UserProfile with userId: " + userProfile.getUserId()); + // replicate userProfile at end-places + dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.CREATE, userProfile); + // return userId + return userProfile.getUserId(); + } else { + throw new Exception("User creation failed. Please try again."); + } + } catch (Exception e) { + logger.error("Error while creating user profile", e); + UserProfileServiceException exception = new UserProfileServiceException(); + exception.setMessage("Error while creating user profile. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean updateUserProfile(AuthzToken authzToken, UserProfile userProfile) + throws UserProfileServiceException { + try { + // After updating the user profile in the database but before committing the transaction, the + // following will update the user profile in the IAM service also. If the update in the IAM service + // fails then the transaction will be rolled back. + Runnable iamUserProfileUpdater = getIAMUserProfileUpdater(authzToken, userProfile); + if (userProfileRepository.updateUserProfile(userProfile, iamUserProfileUpdater) != null) { + logger.info("Updated UserProfile with userId: " + userProfile.getUserId()); + // replicate userProfile at end-places + dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.UPDATE, userProfile); + return true; + } + return false; + } catch (Exception e) { + logger.error("Error while Updating user profile", e); + UserProfileServiceException exception = new UserProfileServiceException(); + exception.setMessage("Error while Updating user profile. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private Runnable getIAMUserProfileUpdater(AuthzToken authzToken, UserProfile userProfile) { + String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); + return () -> { + try { + AiravataSecurityManager securityManager = SecurityManagerFactory.getSecurityManager(); + AuthzToken serviceAccountAuthzToken = + securityManager.getUserManagementServiceAccountAuthzToken(gatewayId); + IamAdminServices.Client iamAdminServicesClient = getIamAdminServicesClient(); + iamAdminServicesClient.updateUserProfile(serviceAccountAuthzToken, userProfile); + } catch (AiravataSecurityException | TException e) { + throw new RuntimeException("Failed to update user profile in IAM service", e); + } + }; + } + + public UserProfile getUserProfileById(AuthzToken authzToken, String userId, String gatewayId) + throws UserProfileServiceException { + try { + UserProfile userProfile = userProfileRepository.getUserProfileByIdAndGateWay(userId, gatewayId); + if (userProfile != null) return userProfile; + else + throw new Exception("User with userId: " + userId + ", in Gateway: " + gatewayId + ", does not exist."); + } catch (Exception e) { + logger.error("Error retrieving user profile by ID", e); + UserProfileServiceException exception = new UserProfileServiceException(); + exception.setMessage("Error retrieving user profile by ID. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean deleteUserProfile(AuthzToken authzToken, String userId, String gatewayId) + throws UserProfileServiceException { + try { + // find user-profile + UserProfile userProfile = userProfileRepository.getUserProfileByIdAndGateWay(userId, gatewayId); + + // delete user + boolean deleteSuccess = userProfileRepository.delete(userId); + logger.info("Delete UserProfile with userId: " + userId + ", " + (deleteSuccess ? "Success!" : "Failed!")); + + if (deleteSuccess) { + // delete userProfile at end-places + dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.DELETE, userProfile); + } + return deleteSuccess; + } catch (Exception e) { + logger.error("Error while deleting user profile", e); + UserProfileServiceException exception = new UserProfileServiceException(); + exception.setMessage("Error while deleting user profile. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public List getAllUserProfilesInGateway(AuthzToken authzToken, String gatewayId, int offset, int limit) + throws UserProfileServiceException { + try { + List usersInGateway = + userProfileRepository.getAllUserProfilesInGateway(gatewayId, offset, limit); + if (usersInGateway != null) return usersInGateway; + else throw new Exception("There are no users for the requested gatewayId: " + gatewayId); + } catch (Exception e) { + logger.error("Error while retrieving user profile List", e); + UserProfileServiceException exception = new UserProfileServiceException(); + exception.setMessage("Error while retrieving user profile List. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + public boolean doesUserExist(AuthzToken authzToken, String userId, String gatewayId) + throws UserProfileServiceException { + try { + UserProfile userProfile = userProfileRepository.getUserProfileByIdAndGateWay(userId, gatewayId); + return null != userProfile; + } catch (Exception e) { + logger.error("Error while finding user profile", e); + UserProfileServiceException exception = new UserProfileServiceException(); + exception.setMessage("Error while finding user profile. More info : " + e.getMessage()); + exception.initCause(e); + throw exception; + } + } + + private IamAdminServices.Client getIamAdminServicesClient() throws UserProfileServiceException { + try { + final int serverPort = Integer.parseInt(ServerSettings.getProfileServiceServerPort()); + final String serverHost = ServerSettings.getProfileServiceServerHost(); + return ProfileServiceClientFactory.createIamAdminServiceClient(serverHost, serverPort); + } catch (IamAdminServicesException | org.apache.airavata.common.exception.ApplicationSettingsException e) { + logger.error("Failed to create IAM Admin Services client", e); + UserProfileServiceException ex = + new UserProfileServiceException("Failed to create IAM Admin Services client"); + ex.initCause(e); + throw ex; + } + } +} diff --git a/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/GroupManagerServiceHandler.java b/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/GroupManagerServiceHandler.java index 9b445aa11b..da507b9815 100644 --- a/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/GroupManagerServiceHandler.java +++ b/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/GroupManagerServiceHandler.java @@ -19,418 +19,118 @@ */ package org.apache.airavata.service.profile.handlers; -import java.util.ArrayList; import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.Constants; -import org.apache.airavata.common.utils.ServerSettings; +import org.apache.airavata.model.error.AiravataSystemException; import org.apache.airavata.model.error.AuthorizationException; import org.apache.airavata.model.group.GroupModel; import org.apache.airavata.model.security.AuthzToken; -import org.apache.airavata.model.user.UserProfile; import org.apache.airavata.service.profile.groupmanager.cpi.GroupManagerService; import org.apache.airavata.service.profile.groupmanager.cpi.exception.GroupManagerServiceException; import org.apache.airavata.service.profile.groupmanager.cpi.group_manager_cpiConstants; -import org.apache.airavata.service.profile.user.core.repositories.UserProfileRepository; import org.apache.airavata.service.security.interceptor.SecurityCheck; -import org.apache.airavata.sharing.registry.client.SharingRegistryServiceClientFactory; -import org.apache.airavata.sharing.registry.models.GroupCardinality; -import org.apache.airavata.sharing.registry.models.GroupType; -import org.apache.airavata.sharing.registry.models.SharingRegistryException; -import org.apache.airavata.sharing.registry.models.User; -import org.apache.airavata.sharing.registry.models.UserGroup; -import org.apache.airavata.sharing.registry.service.cpi.SharingRegistryService; -import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class GroupManagerServiceHandler implements GroupManagerService.Iface { private static final Logger logger = LoggerFactory.getLogger(GroupManagerServiceHandler.class); + private org.apache.airavata.service.GroupManagerService groupManagerService; - private UserProfileRepository userProfileRepository = new UserProfileRepository(); - - public GroupManagerServiceHandler() {} + public GroupManagerServiceHandler() { + groupManagerService = new org.apache.airavata.service.GroupManagerService(); + } @Override - public String getAPIVersion() throws TException { + public String getAPIVersion() throws AiravataSystemException { return group_manager_cpiConstants.GROUP_MANAGER_CPI_VERSION; } @Override @SecurityCheck public String createGroup(AuthzToken authzToken, GroupModel groupModel) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - // TODO Validations for authorization - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - - UserGroup sharingUserGroup = new UserGroup(); - sharingUserGroup.setGroupId(UUID.randomUUID().toString()); - sharingUserGroup.setName(groupModel.getName()); - sharingUserGroup.setDescription(groupModel.getDescription()); - sharingUserGroup.setGroupType(GroupType.USER_LEVEL_GROUP); - sharingUserGroup.setGroupCardinality(GroupCardinality.MULTI_USER); - String gatewayId = getDomainId(authzToken); - sharingUserGroup.setDomainId(gatewayId); - sharingUserGroup.setOwnerId(getUserId(authzToken)); - - String groupId = sharingClient.createGroup(sharingUserGroup); - internalAddUsersToGroup(sharingClient, gatewayId, groupModel.getMembers(), groupId); - addGroupAdmins(authzToken, groupId, groupModel.getAdmins()); - return groupId; - } catch (Exception e) { - String msg = "Error Creating Group"; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.createGroup(authzToken, groupModel); } @Override @SecurityCheck public boolean updateGroup(AuthzToken authzToken, GroupModel groupModel) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - String userId = getUserId(authzToken); - String domainId = getDomainId(authzToken); - if (!(sharingClient.hasOwnerAccess(domainId, groupModel.getId(), userId) - || sharingClient.hasAdminAccess(domainId, groupModel.getId(), userId))) { - throw new GroupManagerServiceException("User does not have permission to update group"); - } - - UserGroup sharingUserGroup = new UserGroup(); - sharingUserGroup.setGroupId(groupModel.getId()); - sharingUserGroup.setName(groupModel.getName()); - sharingUserGroup.setDescription(groupModel.getDescription()); - sharingUserGroup.setGroupType(GroupType.USER_LEVEL_GROUP); - sharingUserGroup.setDomainId(getDomainId(authzToken)); - - // adding and removal of users should be handle separately - sharingClient.updateGroup(sharingUserGroup); - return true; - } catch (Exception e) { - String msg = "Error Updating Group"; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.updateGroup(authzToken, groupModel); } @Override @SecurityCheck public boolean deleteGroup(AuthzToken authzToken, String groupId, String ownerId) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - String userId = getUserId(authzToken); - String domainId = getDomainId(authzToken); - if (!(sharingClient.hasOwnerAccess(domainId, groupId, userId))) { - throw new GroupManagerServiceException("User does not have permission to delete group"); - } - - sharingClient.deleteGroup(getDomainId(authzToken), groupId); - return true; - } catch (Exception e) { - String msg = "Error Deleting Group. Group ID: " + groupId; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.deleteGroup(authzToken, groupId, ownerId); } @Override @SecurityCheck public GroupModel getGroup(AuthzToken authzToken, String groupId) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - final String domainId = getDomainId(authzToken); - UserGroup userGroup = sharingClient.getGroup(domainId, groupId); - - GroupModel groupModel = convertToGroupModel(userGroup, sharingClient); - - return groupModel; - } catch (Exception e) { - String msg = "Error Retreiving Group. Group ID: " + groupId; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.getGroup(authzToken, groupId); } @Override @SecurityCheck public List getGroups(AuthzToken authzToken) - throws GroupManagerServiceException, AuthorizationException, TException { - final String domainId = getDomainId(authzToken); - SharingRegistryService.Client sharingClient = null; - try { - sharingClient = getSharingRegistryServiceClient(); - List userGroups = sharingClient.getGroups(domainId, 0, -1); - - return convertToGroupModels(userGroups, sharingClient); - } catch (Exception e) { - String msg = "Error Retrieving Groups. Domain ID: " + domainId; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } finally { - closeSharingClient(sharingClient); - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.getGroups(authzToken); } @Override @SecurityCheck public List getAllGroupsUserBelongs(AuthzToken authzToken, String userName) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - List groupModels = new ArrayList(); - final String domainId = getDomainId(authzToken); - List userGroups = sharingClient.getAllMemberGroupsForUser(domainId, userName); - - return convertToGroupModels(userGroups, sharingClient); - } catch (Exception e) { - String msg = "Error Retreiving All Groups for User. User ID: " + userName; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.getAllGroupsUserBelongs(authzToken, userName); } @Override public boolean addUsersToGroup(AuthzToken authzToken, List userIds, String groupId) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - String userId = getUserId(authzToken); - String domainId = getDomainId(authzToken); - if (!(sharingClient.hasOwnerAccess(domainId, groupId, userId) - || sharingClient.hasAdminAccess(domainId, groupId, userId))) { - throw new GroupManagerServiceException("User does not have access to add users to the group"); - } - return internalAddUsersToGroup(sharingClient, domainId, userIds, groupId); - - } catch (Exception e) { - String msg = "Error adding users to group. Group ID: " + groupId; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.addUsersToGroup(authzToken, userIds, groupId); } @Override public boolean removeUsersFromGroup(AuthzToken authzToken, List userIds, String groupId) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - String userId = getUserId(authzToken); - String domainId = getDomainId(authzToken); - if (!(sharingClient.hasOwnerAccess(domainId, groupId, userId) - || sharingClient.hasAdminAccess(domainId, groupId, userId))) { - throw new GroupManagerServiceException("User does not have access to remove users to the group"); - } - return sharingClient.removeUsersFromGroup(domainId, userIds, groupId); - } catch (Exception e) { - String msg = "Error remove users to group. Group ID: " + groupId; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.removeUsersFromGroup(authzToken, userIds, groupId); } @Override @SecurityCheck public boolean transferGroupOwnership(AuthzToken authzToken, String groupId, String newOwnerId) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - String userId = getUserId(authzToken); - String domainId = getDomainId(authzToken); - if (!(sharingClient.hasOwnerAccess(domainId, groupId, userId))) { - throw new GroupManagerServiceException( - "User does not have Owner permission to transfer group ownership"); - } - return sharingClient.transferGroupOwnership(getDomainId(authzToken), groupId, newOwnerId); - } catch (Exception e) { - String msg = "Error Transferring Group Ownership"; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.transferGroupOwnership(authzToken, groupId, newOwnerId); } @Override @SecurityCheck public boolean addGroupAdmins(AuthzToken authzToken, String groupId, List adminIds) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - String userId = getUserId(authzToken); - String domainId = getDomainId(authzToken); - if (!(sharingClient.hasOwnerAccess(domainId, groupId, userId))) { - throw new GroupManagerServiceException("User does not have Owner permission to add group admins"); - } - return sharingClient.addGroupAdmins(getDomainId(authzToken), groupId, adminIds); - } catch (Exception e) { - String msg = "Error Adding Admins to Group. Group ID: " + groupId; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.addGroupAdmins(authzToken, groupId, adminIds); } @Override @SecurityCheck public boolean removeGroupAdmins(AuthzToken authzToken, String groupId, List adminIds) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - String userId = getUserId(authzToken); - String domainId = getDomainId(authzToken); - if (!(sharingClient.hasOwnerAccess(domainId, groupId, userId))) { - throw new GroupManagerServiceException("User does not have Owner permission to remove group admins"); - } - return sharingClient.removeGroupAdmins(getDomainId(authzToken), groupId, adminIds); - } catch (Exception e) { - String msg = "Error Removing Admins from the Group. Group ID: " + groupId; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.removeGroupAdmins(authzToken, groupId, adminIds); } @Override @SecurityCheck public boolean hasAdminAccess(AuthzToken authzToken, String groupId, String adminId) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - return sharingClient.hasAdminAccess(getDomainId(authzToken), groupId, adminId); - } catch (Exception e) { - String msg = "Error Checking Admin Access for the Group. Group ID: " + groupId + " Admin ID: " + adminId; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.hasAdminAccess(authzToken, groupId, adminId); } @Override @SecurityCheck public boolean hasOwnerAccess(AuthzToken authzToken, String groupId, String ownerId) - throws GroupManagerServiceException, AuthorizationException, TException { - try { - SharingRegistryService.Client sharingClient = getSharingRegistryServiceClient(); - return sharingClient.hasOwnerAccess(getDomainId(authzToken), groupId, ownerId); - } catch (Exception e) { - String msg = "Error Checking Owner Access for the Group. Group ID: " + groupId + " Owner ID: " + ownerId; - logger.error(msg, e); - GroupManagerServiceException exception = new GroupManagerServiceException(); - exception.setMessage(msg + " More info : " + e.getMessage()); - throw exception; - } - } - - // TODO: replace these methods with ThriftClientPool (see AIRAVATA-2607) - private SharingRegistryService.Client getSharingRegistryServiceClient() - throws TException, ApplicationSettingsException { - final int serverPort = Integer.parseInt(ServerSettings.getSharingRegistryPort()); - final String serverHost = ServerSettings.getSharingRegistryHost(); - try { - return SharingRegistryServiceClientFactory.createSharingRegistryClient(serverHost, serverPort); - } catch (SharingRegistryException e) { - throw new TException("Unable to create sharing registry client...", e); - } - } - - private String getDomainId(AuthzToken authzToken) { - return authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - } - - private String getUserId(AuthzToken authzToken) { - return authzToken.getClaimsMap().get(Constants.USER_NAME) + "@" + getDomainId(authzToken); - } - - private List convertToGroupModels( - List userGroups, SharingRegistryService.Client sharingClient) throws TException { - - List groupModels = new ArrayList<>(); - - for (UserGroup userGroup : userGroups) { - GroupModel groupModel = convertToGroupModel(userGroup, sharingClient); - - groupModels.add(groupModel); - } - return groupModels; - } - - private GroupModel convertToGroupModel(UserGroup userGroup, SharingRegistryService.Client sharingClient) - throws TException { - GroupModel groupModel = new GroupModel(); - groupModel.setId(userGroup.getGroupId()); - groupModel.setName(userGroup.getName()); - groupModel.setDescription(userGroup.getDescription()); - groupModel.setOwnerId(userGroup.getOwnerId()); - final List admins = userGroup.getGroupAdmins().stream() - .map(groupAdmin -> groupAdmin.getAdminId()) - .collect(Collectors.toList()); - groupModel.setAdmins(admins); - - sharingClient.getGroupMembersOfTypeUser(userGroup.getDomainId(), userGroup.getGroupId(), 0, -1).stream() - .forEach(user -> groupModel.addToMembers(user.getUserId())); - return groupModel; - } - - private void closeSharingClient(SharingRegistryService.Client sharingClient) { - if (sharingClient != null) { - if (sharingClient.getInputProtocol().getTransport().isOpen()) { - sharingClient.getInputProtocol().getTransport().close(); - } - if (sharingClient.getOutputProtocol().getTransport().isOpen()) { - sharingClient.getOutputProtocol().getTransport().close(); - } - } - } - - private boolean internalAddUsersToGroup( - SharingRegistryService.Client sharingClient, String domainId, List userIds, String groupId) - throws SharingRegistryException, TException { - - // FIXME: workaround for UserProfiles that failed to sync to the sharing - // registry: create any missing users in the sharing registry - for (String userId : userIds) { - if (!sharingClient.isUserExists(domainId, userId)) { - User user = new User(); - user.setDomainId(domainId); - user.setUserId(userId); - UserProfile userProfile = userProfileRepository.get(userId); - user.setUserName(userProfile.getUserId()); - user.setCreatedTime(userProfile.getCreationTime()); - user.setEmail( - userProfile.getEmailsSize() > 0 - ? userProfile.getEmails().get(0) - : null); - user.setFirstName(userProfile.getFirstName()); - user.setLastName(userProfile.getLastName()); - sharingClient.createUser(user); - } - } - return sharingClient.addUsersToGroup(domainId, userIds, groupId); + throws GroupManagerServiceException, AuthorizationException { + return groupManagerService.hasOwnerAccess(authzToken, groupId, ownerId); } } diff --git a/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/IamAdminServicesHandler.java b/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/IamAdminServicesHandler.java index 2da10e50fe..de517b7358 100644 --- a/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/IamAdminServicesHandler.java +++ b/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/IamAdminServicesHandler.java @@ -20,45 +20,38 @@ package org.apache.airavata.service.profile.handlers; import java.util.List; -import org.apache.airavata.common.exception.AiravataException; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.AiravataUtils; -import org.apache.airavata.common.utils.Constants; -import org.apache.airavata.common.utils.DBEventService; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.credential.store.client.CredentialStoreClientFactory; -import org.apache.airavata.credential.store.cpi.CredentialStoreService; -import org.apache.airavata.credential.store.exception.CredentialStoreException; -import org.apache.airavata.messaging.core.util.DBEventPublisherUtils; -import org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile; -import org.apache.airavata.model.credential.store.PasswordCredential; -import org.apache.airavata.model.dbevent.CrudType; -import org.apache.airavata.model.dbevent.EntityType; +import org.apache.airavata.model.error.AiravataSystemException; import org.apache.airavata.model.error.AuthorizationException; import org.apache.airavata.model.security.AuthzToken; import org.apache.airavata.model.user.UserProfile; import org.apache.airavata.model.workspace.Gateway; -import org.apache.airavata.registry.api.RegistryService; -import org.apache.airavata.registry.api.client.RegistryServiceClientFactory; -import org.apache.airavata.registry.api.exception.RegistryServiceException; -import org.apache.airavata.service.profile.iam.admin.services.core.impl.TenantManagementKeycloakImpl; +import org.apache.airavata.service.IamAdminService; import org.apache.airavata.service.profile.iam.admin.services.cpi.IamAdminServices; import org.apache.airavata.service.profile.iam.admin.services.cpi.exception.IamAdminServicesException; import org.apache.airavata.service.profile.iam.admin.services.cpi.iam_admin_services_cpiConstants; -import org.apache.airavata.service.profile.user.core.repositories.UserProfileRepository; import org.apache.airavata.service.security.interceptor.SecurityCheck; -import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class IamAdminServicesHandler implements IamAdminServices.Iface { private static final Logger logger = LoggerFactory.getLogger(IamAdminServicesHandler.class); - private UserProfileRepository userProfileRepository = new UserProfileRepository(); - private DBEventPublisherUtils dbEventPublisherUtils = new DBEventPublisherUtils(DBEventService.IAM_ADMIN); + private IamAdminService iamAdminService; + + public IamAdminServicesHandler() throws IamAdminServicesException { + try { + iamAdminService = new org.apache.airavata.service.IamAdminService(); + } catch (Throwable e) { + String msg = "Error initializing IamAdminServicesHandler, reason: " + e.getMessage(); + logger.error(msg, e); + var exception = new IamAdminServicesException(msg); + exception.initCause(e); + throw exception; + } + } @Override - public String getAPIVersion() throws TException { + public String getAPIVersion() throws AiravataSystemException { return iam_admin_services_cpiConstants.IAM_ADMIN_SERVICES_CPI_VERSION; } @@ -66,40 +59,16 @@ public String getAPIVersion() throws TException { @SecurityCheck public Gateway setUpGateway(AuthzToken authzToken, Gateway gateway) throws IamAdminServicesException, AuthorizationException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - PasswordCredential isSuperAdminCredentials = getSuperAdminPasswordCredential(); - try { - keycloakclient.addTenant(isSuperAdminCredentials, gateway); - - // Load the tenant admin password stored in gateway request - CredentialStoreService.Client credentialStoreClient = getCredentialStoreServiceClient(); - // Admin password token should already be stored under requested gateway's gatewayId - PasswordCredential tenantAdminPasswordCredential = credentialStoreClient.getPasswordCredential( - gateway.getIdentityServerPasswordToken(), gateway.getGatewayId()); - - if (!keycloakclient.createTenantAdminAccount( - isSuperAdminCredentials, gateway, tenantAdminPasswordCredential.getPassword())) { - logger.error("Admin account creation failed !!, please refer error logs for reason"); - } - Gateway gatewayWithIdAndSecret = keycloakclient.configureClient(isSuperAdminCredentials, gateway); - return gatewayWithIdAndSecret; - } catch (TException | ApplicationSettingsException ex) { - logger.error("Gateway Setup Failed, reason: " + ex.getMessage(), ex); - IamAdminServicesException iamAdminServicesException = new IamAdminServicesException(ex.getMessage()); - throw iamAdminServicesException; - } + return iamAdminService.setUpGateway(authzToken, gateway); } @Override @SecurityCheck public boolean isUsernameAvailable(AuthzToken authzToken, String username) - throws IamAdminServicesException, AuthorizationException, TException { - TenantManagementKeycloakImpl keycloakClient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - return keycloakClient.isUsernameAvailable(authzToken.getAccessToken(), gatewayId, username); + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.isUsernameAvailable(authzToken, username); } - // ToDo: Will only be secure when using SSL between PGA and Airavata @Override @SecurityCheck public boolean registerUser( @@ -110,259 +79,93 @@ public boolean registerUser( String lastName, String newPassword) throws IamAdminServicesException, AuthorizationException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - if (keycloakclient.createUser( - authzToken.getAccessToken(), gatewayId, username, emailAddress, firstName, lastName, newPassword)) - return true; - else return false; - } catch (TException ex) { - String msg = "Error while registering user into Identity Server, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } + return iamAdminService.registerUser(authzToken, username, emailAddress, firstName, lastName, newPassword); } @Override @SecurityCheck public boolean enableUser(AuthzToken authzToken, String username) throws IamAdminServicesException, AuthorizationException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - if (keycloakclient.enableUserAccount(authzToken.getAccessToken(), gatewayId, username)) { - // Check if user profile exists, if not create it - boolean userProfileExists = - userProfileRepository.getUserProfileByIdAndGateWay(username, gatewayId) != null; - if (!userProfileExists) { - // Load basic user profile information from Keycloak and then save in UserProfileRepository - UserProfile userProfile = keycloakclient.getUser(authzToken.getAccessToken(), gatewayId, username); - userProfile.setCreationTime( - AiravataUtils.getCurrentTimestamp().getTime()); - userProfile.setLastAccessTime( - AiravataUtils.getCurrentTimestamp().getTime()); - userProfile.setValidUntil(-1); - userProfileRepository.createUserProfile(userProfile); - // Dispatch IAM_ADMIN service event for a new USER_PROFILE - dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.CREATE, userProfile); - } - return true; - } else { - return false; - } - } catch (TException | AiravataException ex) { - String msg = "Error while enabling user account, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } + return iamAdminService.enableUser(authzToken, username); } @Override @SecurityCheck public boolean isUserEnabled(AuthzToken authzToken, String username) - throws IamAdminServicesException, AuthorizationException, TException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - return keycloakclient.isUserAccountEnabled(authzToken.getAccessToken(), gatewayId, username); - } catch (Exception ex) { - String msg = "Error while checking if user account is enabled, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.isUserEnabled(authzToken, username); } @Override @SecurityCheck public boolean isUserExist(AuthzToken authzToken, String username) - throws IamAdminServicesException, AuthorizationException, TException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - return keycloakclient.isUserExist(authzToken.getAccessToken(), gatewayId, username); - } catch (Exception ex) { - String msg = "Error while checking if user account exists, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.isUserExist(authzToken, username); } @Override @SecurityCheck public UserProfile getUser(AuthzToken authzToken, String username) - throws IamAdminServicesException, AuthorizationException, TException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - return keycloakclient.getUser(authzToken.getAccessToken(), gatewayId, username); - } catch (Exception ex) { - String msg = "Error while retrieving user profile from IAM backend, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.getUser(authzToken, username); } @Override @SecurityCheck public List getUsers(AuthzToken authzToken, int offset, int limit, String search) - throws IamAdminServicesException, AuthorizationException, TException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - return keycloakclient.getUsers(authzToken.getAccessToken(), gatewayId, offset, limit, search); - } catch (Exception ex) { - String msg = "Error while retrieving user profile from IAM backend, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.getUsers(authzToken, offset, limit, search); } @Override @SecurityCheck public boolean resetUserPassword(AuthzToken authzToken, String username, String newPassword) - throws IamAdminServicesException, AuthorizationException, TException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - if (keycloakclient.resetUserPassword(authzToken.getAccessToken(), gatewayId, username, newPassword)) - return true; - else return false; - } catch (TException ex) { - String msg = "Error while resetting user password in Identity Server, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.resetUserPassword(authzToken, username, newPassword); } @Override @SecurityCheck public List findUsers(AuthzToken authzToken, String email, String userId) - throws IamAdminServicesException, AuthorizationException, TException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - return keycloakclient.findUser(authzToken.getAccessToken(), gatewayId, email, userId); - } catch (TException ex) { - String msg = "Error while retrieving users from Identity Server, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.findUsers(authzToken, email, userId); } @Override @SecurityCheck public void updateUserProfile(AuthzToken authzToken, UserProfile userDetails) - throws IamAdminServicesException, AuthorizationException, TException { - - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String username = userDetails.getUserId(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - - keycloakclient.updateUserProfile(authzToken.getAccessToken(), gatewayId, username, userDetails); + throws IamAdminServicesException, AuthorizationException { + iamAdminService.updateUserProfile(authzToken, userDetails); } @Override @SecurityCheck public boolean deleteUser(AuthzToken authzToken, String username) - throws IamAdminServicesException, AuthorizationException, TException { - - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - - return keycloakclient.deleteUser(authzToken.getAccessToken(), gatewayId, username); + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.deleteUser(authzToken, username); } @Override @SecurityCheck @Deprecated public boolean addRoleToUser(AuthzToken authzToken, String username, String roleName) - throws IamAdminServicesException, AuthorizationException, TException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - PasswordCredential isRealmAdminCredentials = getTenantAdminPasswordCredential(gatewayId); - return keycloakclient.addRoleToUser(isRealmAdminCredentials, gatewayId, username, roleName); - } catch (TException | ApplicationSettingsException ex) { - String msg = "Error while adding role to user, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.addRoleToUser(authzToken, username, roleName); } @Override @SecurityCheck @Deprecated public boolean removeRoleFromUser(AuthzToken authzToken, String username, String roleName) - throws IamAdminServicesException, AuthorizationException, TException { - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - PasswordCredential isRealmAdminCredentials = getTenantAdminPasswordCredential(gatewayId); - return keycloakclient.removeRoleFromUser(isRealmAdminCredentials, gatewayId, username, roleName); - } catch (TException | ApplicationSettingsException ex) { - String msg = "Error while removing role from user, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.removeRoleFromUser(authzToken, username, roleName); } @Override @SecurityCheck @Deprecated public List getUsersWithRole(AuthzToken authzToken, String roleName) - throws IamAdminServicesException, AuthorizationException, TException { - - TenantManagementKeycloakImpl keycloakclient = new TenantManagementKeycloakImpl(); - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - PasswordCredential isRealmAdminCredentials = getTenantAdminPasswordCredential(gatewayId); - return keycloakclient.getUsersWithRole(isRealmAdminCredentials, gatewayId, roleName); - } catch (Exception ex) { - String msg = "Error while retrieving users with role, reason: " + ex.getMessage(); - logger.error(msg, ex); - throw new IamAdminServicesException(msg); - } - } - - private PasswordCredential getSuperAdminPasswordCredential() { - PasswordCredential isSuperAdminCredentials = new PasswordCredential(); - try { - isSuperAdminCredentials.setLoginUserName(ServerSettings.getIamServerSuperAdminUsername()); - isSuperAdminCredentials.setPassword(ServerSettings.getIamServerSuperAdminPassword()); - } catch (ApplicationSettingsException e) { - throw new RuntimeException("Unable to get settings for IAM super admin username/password", e); - } - return isSuperAdminCredentials; - } - - private PasswordCredential getTenantAdminPasswordCredential(String tenantId) - throws TException, ApplicationSettingsException { - - GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(tenantId); - - CredentialStoreService.Client csClient = getCredentialStoreServiceClient(); - return csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID()); - } - - private RegistryService.Client getRegistryServiceClient() throws TException, ApplicationSettingsException { - final int serverPort = Integer.parseInt(ServerSettings.getRegistryServerPort()); - final String serverHost = ServerSettings.getRegistryServerHost(); - try { - return RegistryServiceClientFactory.createRegistryClient(serverHost, serverPort); - } catch (RegistryServiceException e) { - throw new TException("Unable to create registry client...", e); - } - } - - private CredentialStoreService.Client getCredentialStoreServiceClient() - throws TException, ApplicationSettingsException { - final int serverPort = Integer.parseInt(ServerSettings.getCredentialStoreServerPort()); - final String serverHost = ServerSettings.getCredentialStoreServerHost(); - try { - return CredentialStoreClientFactory.createAiravataCSClient(serverHost, serverPort); - } catch (CredentialStoreException e) { - throw new TException("Unable to create credential store client...", e); - } + throws IamAdminServicesException, AuthorizationException { + return iamAdminService.getUsersWithRole(authzToken, roleName); } } diff --git a/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/TenantProfileServiceHandler.java b/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/TenantProfileServiceHandler.java index 2f856cc07d..d9d6d0643d 100644 --- a/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/TenantProfileServiceHandler.java +++ b/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/TenantProfileServiceHandler.java @@ -20,29 +20,14 @@ package org.apache.airavata.service.profile.handlers; import java.util.List; -import java.util.UUID; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.Constants; -import org.apache.airavata.common.utils.DBEventService; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.credential.store.client.CredentialStoreClientFactory; -import org.apache.airavata.credential.store.cpi.CredentialStoreService; -import org.apache.airavata.credential.store.exception.CredentialStoreException; -import org.apache.airavata.messaging.core.util.DBEventPublisherUtils; -import org.apache.airavata.model.credential.store.PasswordCredential; -import org.apache.airavata.model.dbevent.CrudType; -import org.apache.airavata.model.dbevent.EntityType; +import org.apache.airavata.model.error.AiravataSystemException; import org.apache.airavata.model.error.AuthorizationException; import org.apache.airavata.model.security.AuthzToken; import org.apache.airavata.model.workspace.Gateway; -import org.apache.airavata.model.workspace.GatewayApprovalStatus; -import org.apache.airavata.service.profile.commons.tenant.entities.GatewayEntity; -import org.apache.airavata.service.profile.tenant.core.repositories.TenantProfileRepository; import org.apache.airavata.service.profile.tenant.cpi.TenantProfileService; import org.apache.airavata.service.profile.tenant.cpi.exception.TenantProfileServiceException; import org.apache.airavata.service.profile.tenant.cpi.profile_tenant_cpiConstants; import org.apache.airavata.service.security.interceptor.SecurityCheck; -import org.apache.thrift.TException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -52,222 +37,72 @@ public class TenantProfileServiceHandler implements TenantProfileService.Iface { private static final Logger logger = LoggerFactory.getLogger(TenantProfileServiceHandler.class); + private org.apache.airavata.service.TenantProfileService tenantProfileService; - private TenantProfileRepository tenantProfileRepository; - private DBEventPublisherUtils dbEventPublisherUtils = new DBEventPublisherUtils(DBEventService.TENANT); - - public TenantProfileServiceHandler() { + public TenantProfileServiceHandler() throws TenantProfileServiceException { logger.debug("Initializing TenantProfileServiceHandler"); - this.tenantProfileRepository = new TenantProfileRepository(Gateway.class, GatewayEntity.class); + try { + tenantProfileService = new org.apache.airavata.service.TenantProfileService(); + } catch (Throwable e) { + String msg = "Error initializing TenantProfileServiceHandler, reason: " + e.getMessage(); + logger.error(msg, e); + var exception = new TenantProfileServiceException(msg); + exception.initCause(e); + throw exception; + } } @Override - public String getAPIVersion() throws TException { + public String getAPIVersion() throws AiravataSystemException { return profile_tenant_cpiConstants.TENANT_PROFILE_CPI_VERSION; } @Override @SecurityCheck public String addGateway(AuthzToken authzToken, Gateway gateway) - throws TenantProfileServiceException, AuthorizationException, TException { - try { - // Assign UUID to gateway - gateway.setAiravataInternalGatewayId(UUID.randomUUID().toString()); - if (!checkDuplicateGateway(gateway)) { - // If admin password, copy it in the credential store under the requested gateway's gatewayId - if (gateway.getIdentityServerPasswordToken() != null) { - copyAdminPasswordToGateway(authzToken, gateway); - } - gateway = tenantProfileRepository.create(gateway); - if (gateway != null) { - logger.info("Added Airavata Gateway with Id: " + gateway.getGatewayId()); - // replicate tenant at end-places only if status is APPROVED - if (gateway.getGatewayApprovalStatus().equals(GatewayApprovalStatus.APPROVED)) { - logger.info( - "Gateway with ID: {}, is now APPROVED, replicating to subscribers.", - gateway.getGatewayId()); - dbEventPublisherUtils.publish(EntityType.TENANT, CrudType.CREATE, gateway); - } - // return internal id - return gateway.getAiravataInternalGatewayId(); - } else { - throw new Exception("Gateway object is null."); - } - } else { - throw new TenantProfileServiceException( - "An approved Gateway already exists with the same GatewayId, Name or URL"); - } - } catch (Exception ex) { - logger.error("Error adding gateway-profile, reason: " + ex.getMessage(), ex); - TenantProfileServiceException exception = new TenantProfileServiceException(); - exception.setMessage("Error adding gateway-profile, reason: " + ex.getMessage()); - throw exception; - } + throws TenantProfileServiceException, AuthorizationException { + return tenantProfileService.addGateway(authzToken, gateway); } @Override @SecurityCheck public boolean updateGateway(AuthzToken authzToken, Gateway updatedGateway) - throws TenantProfileServiceException, AuthorizationException, TException { - try { - - // if admin password token changes then copy the admin password and store under this gateway id and then - // update the admin password token - Gateway existingGateway = tenantProfileRepository.getGateway(updatedGateway.getAiravataInternalGatewayId()); - if (updatedGateway.getIdentityServerPasswordToken() != null - && (existingGateway.getIdentityServerPasswordToken() == null - || !existingGateway - .getIdentityServerPasswordToken() - .equals(updatedGateway.getIdentityServerPasswordToken()))) { - copyAdminPasswordToGateway(authzToken, updatedGateway); - } - - if (tenantProfileRepository.update(updatedGateway) != null) { - logger.debug("Updated gateway-profile with ID: " + updatedGateway.getGatewayId()); - // replicate tenant at end-places - dbEventPublisherUtils.publish(EntityType.TENANT, CrudType.UPDATE, updatedGateway); - return true; - } else { - return false; - } - } catch (Exception ex) { - logger.error("Error updating gateway-profile, reason: " + ex.getMessage(), ex); - TenantProfileServiceException exception = new TenantProfileServiceException(); - exception.setMessage("Error updating gateway-profile, reason: " + ex.getMessage()); - return false; - } + throws TenantProfileServiceException, AuthorizationException { + return tenantProfileService.updateGateway(authzToken, updatedGateway); } @Override @SecurityCheck public Gateway getGateway(AuthzToken authzToken, String airavataInternalGatewayId) - throws TenantProfileServiceException, AuthorizationException, TException { - try { - Gateway gateway = tenantProfileRepository.getGateway(airavataInternalGatewayId); - if (gateway == null) { - throw new Exception("Could not find Gateway with internal ID: " + airavataInternalGatewayId); - } - return gateway; - } catch (Exception ex) { - logger.error("Error getting gateway-profile, reason: " + ex.getMessage(), ex); - TenantProfileServiceException exception = new TenantProfileServiceException(); - exception.setMessage("Error getting gateway-profile, reason: " + ex.getMessage()); - throw exception; - } + throws TenantProfileServiceException, AuthorizationException { + return tenantProfileService.getGateway(authzToken, airavataInternalGatewayId); } @Override @SecurityCheck public boolean deleteGateway(AuthzToken authzToken, String airavataInternalGatewayId, String gatewayId) - throws TenantProfileServiceException, AuthorizationException, TException { - try { - logger.debug("Deleting Airavata gateway-profile with ID: " + gatewayId + "Internal ID: " - + airavataInternalGatewayId); - boolean deleteSuccess = tenantProfileRepository.delete(airavataInternalGatewayId); - if (deleteSuccess) { - // delete tenant at end-places - dbEventPublisherUtils.publish( - EntityType.TENANT, - CrudType.DELETE, - // pass along gateway datamodel, with correct gatewayId; - // approvalstatus is not used for delete, hence set dummy value - new Gateway(gatewayId, GatewayApprovalStatus.DEACTIVATED)); - } - return deleteSuccess; - } catch (Exception ex) { - logger.error("Error deleting gateway-profile, reason: " + ex.getMessage(), ex); - TenantProfileServiceException exception = new TenantProfileServiceException(); - exception.setMessage("Error deleting gateway-profile, reason: " + ex.getMessage()); - throw exception; - } + throws TenantProfileServiceException, AuthorizationException { + return tenantProfileService.deleteGateway(authzToken, airavataInternalGatewayId, gatewayId); } @Override @SecurityCheck public List getAllGateways(AuthzToken authzToken) - throws TenantProfileServiceException, AuthorizationException, TException { - try { - return tenantProfileRepository.getAllGateways(); - } catch (Exception ex) { - logger.error("Error getting all gateway-profiles, reason: " + ex.getMessage(), ex); - TenantProfileServiceException exception = new TenantProfileServiceException(); - exception.setMessage("Error getting all gateway-profiles, reason: " + ex.getMessage()); - throw exception; - } + throws TenantProfileServiceException, AuthorizationException { + return tenantProfileService.getAllGateways(authzToken); } @Override @SecurityCheck public boolean isGatewayExist(AuthzToken authzToken, String gatewayId) - throws TenantProfileServiceException, AuthorizationException, TException { - try { - Gateway gateway = tenantProfileRepository.getGateway(gatewayId); - return (gateway != null); - } catch (Exception ex) { - logger.error("Error checking if gateway-profile exists, reason: " + ex.getMessage(), ex); - TenantProfileServiceException exception = new TenantProfileServiceException(); - exception.setMessage("Error checking if gateway-profile exists, reason: " + ex.getMessage()); - throw exception; - } + throws TenantProfileServiceException, AuthorizationException { + return tenantProfileService.isGatewayExist(authzToken, gatewayId); } @Override @SecurityCheck public List getAllGatewaysForUser(AuthzToken authzToken, String requesterUsername) - throws TenantProfileServiceException, AuthorizationException, TException { - try { - return tenantProfileRepository.getAllGatewaysForUser(requesterUsername); - } catch (Exception ex) { - logger.error("Error getting user's gateway-profiles, reason: " + ex.getMessage(), ex); - TenantProfileServiceException exception = new TenantProfileServiceException(); - exception.setMessage("Error getting user's gateway-profiles, reason: " + ex.getMessage()); - throw exception; - } - } - - private boolean checkDuplicateGateway(Gateway gateway) throws TenantProfileServiceException { - try { - Gateway duplicateGateway = tenantProfileRepository.getDuplicateGateway( - gateway.getGatewayId(), gateway.getGatewayName(), gateway.getGatewayURL()); - return duplicateGateway != null; - } catch (Exception ex) { - logger.error("Error checking if duplicate gateway-profile exists, reason: " + ex.getMessage(), ex); - TenantProfileServiceException exception = new TenantProfileServiceException(); - exception.setMessage("Error checking if duplicate gateway-profiles exists, reason: " + ex.getMessage()); - throw exception; - } - } - - // admin passwords are stored in credential store in the super portal gateway and need to be - // copied to a credential that is stored in the requested/newly created gateway - private void copyAdminPasswordToGateway(AuthzToken authzToken, Gateway gateway) - throws TException, ApplicationSettingsException { - CredentialStoreService.Client csClient = getCredentialStoreServiceClient(); - try { - String requestGatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - PasswordCredential adminPasswordCredential = - csClient.getPasswordCredential(gateway.getIdentityServerPasswordToken(), requestGatewayId); - adminPasswordCredential.setGatewayId(gateway.getGatewayId()); - String newAdminPasswordCredentialToken = csClient.addPasswordCredential(adminPasswordCredential); - gateway.setIdentityServerPasswordToken(newAdminPasswordCredentialToken); - } finally { - if (csClient.getInputProtocol().getTransport().isOpen()) { - csClient.getInputProtocol().getTransport().close(); - } - if (csClient.getOutputProtocol().getTransport().isOpen()) { - csClient.getOutputProtocol().getTransport().close(); - } - } - } - - private CredentialStoreService.Client getCredentialStoreServiceClient() - throws TException, ApplicationSettingsException { - final int serverPort = Integer.parseInt(ServerSettings.getCredentialStoreServerPort()); - final String serverHost = ServerSettings.getCredentialStoreServerHost(); - try { - return CredentialStoreClientFactory.createAiravataCSClient(serverHost, serverPort); - } catch (CredentialStoreException e) { - throw new TException("Unable to create credential store client...", e); - } + throws TenantProfileServiceException, AuthorizationException { + return tenantProfileService.getAllGatewaysForUser(authzToken, requesterUsername); } } diff --git a/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/UserProfileServiceHandler.java b/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/UserProfileServiceHandler.java index 2dec971b1b..2435a16e51 100644 --- a/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/UserProfileServiceHandler.java +++ b/airavata-api/src/main/java/org/apache/airavata/service/profile/handlers/UserProfileServiceHandler.java @@ -20,244 +20,73 @@ package org.apache.airavata.service.profile.handlers; import java.util.List; -import org.apache.airavata.common.exception.ApplicationSettingsException; -import org.apache.airavata.common.utils.AiravataUtils; -import org.apache.airavata.common.utils.Constants; -import org.apache.airavata.common.utils.DBEventService; -import org.apache.airavata.common.utils.ServerSettings; -import org.apache.airavata.messaging.core.util.DBEventPublisherUtils; -import org.apache.airavata.model.dbevent.CrudType; -import org.apache.airavata.model.dbevent.EntityType; +import org.apache.airavata.model.error.AiravataSystemException; import org.apache.airavata.model.error.AuthorizationException; import org.apache.airavata.model.security.AuthzToken; -import org.apache.airavata.model.user.Status; import org.apache.airavata.model.user.UserProfile; -import org.apache.airavata.security.AiravataSecurityException; -import org.apache.airavata.service.profile.client.ProfileServiceClientFactory; -import org.apache.airavata.service.profile.iam.admin.services.cpi.IamAdminServices; -import org.apache.airavata.service.profile.iam.admin.services.cpi.exception.IamAdminServicesException; -import org.apache.airavata.service.profile.user.core.repositories.UserProfileRepository; -import org.apache.airavata.service.profile.user.cpi.UserProfileService; import org.apache.airavata.service.profile.user.cpi.exception.UserProfileServiceException; import org.apache.airavata.service.profile.user.cpi.profile_user_cpiConstants; -import org.apache.airavata.service.security.AiravataSecurityManager; -import org.apache.airavata.service.security.SecurityManagerFactory; -import org.apache.airavata.service.security.UserInfo; import org.apache.airavata.service.security.interceptor.SecurityCheck; -import org.apache.thrift.TException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -public class UserProfileServiceHandler implements UserProfileService.Iface { +public class UserProfileServiceHandler + implements org.apache.airavata.service.profile.user.cpi.UserProfileService.Iface { - private static final Logger logger = LoggerFactory.getLogger(UserProfileServiceHandler.class); - - private UserProfileRepository userProfileRepository; - private DBEventPublisherUtils dbEventPublisherUtils = new DBEventPublisherUtils(DBEventService.USER_PROFILE); + private org.apache.airavata.service.UserProfileService userProfileService; public UserProfileServiceHandler() { - - userProfileRepository = new UserProfileRepository(); + userProfileService = new org.apache.airavata.service.UserProfileService(); } @Override - public String getAPIVersion() throws TException { + public String getAPIVersion() throws AiravataSystemException { return profile_user_cpiConstants.USER_PROFILE_CPI_VERSION; } @Override @SecurityCheck public String initializeUserProfile(AuthzToken authzToken) - throws UserProfileServiceException, AuthorizationException, TException { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - try { - // Load UserInfo for the access token and create an initial UserProfile from it - UserInfo userInfo = SecurityManagerFactory.getSecurityManager().getUserInfoFromAuthzToken(authzToken); - final UserProfile existingProfile = - userProfileRepository.getUserProfileByIdAndGateWay(userInfo.getUsername(), gatewayId); - // If a user profile already exists, just return the userId - if (existingProfile != null) { - return existingProfile.getUserId(); - } - UserProfile userProfile = new UserProfile(); - userProfile.setUserId(userInfo.getUsername().toLowerCase()); - userProfile.setGatewayId(gatewayId); - userProfile.setAiravataInternalUserId(userProfile.getUserId() + "@" + gatewayId); - userProfile.addToEmails(userInfo.getEmailAddress()); - userProfile.setFirstName(userInfo.getFirstName()); - userProfile.setLastName(userInfo.getLastName()); - userProfile.setCreationTime(AiravataUtils.getCurrentTimestamp().getTime()); - userProfile.setLastAccessTime(AiravataUtils.getCurrentTimestamp().getTime()); - userProfile.setValidUntil(-1); - userProfile.setState(Status.ACTIVE); - userProfile = userProfileRepository.createUserProfile(userProfile); - if (null != userProfile) { - logger.info("Added UserProfile with userId: " + userProfile.getUserId()); - // replicate userProfile at end-places - dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.CREATE, userProfile); - // return userId - return userProfile.getUserId(); - } else { - throw new Exception("User creation failed. Please try again."); - } - } catch (Exception e) { - logger.error("Error while initializing user profile", e); - UserProfileServiceException exception = new UserProfileServiceException(); - exception.setMessage("Error while initializing user profile. More info : " + e.getMessage()); - throw exception; - } + throws UserProfileServiceException, AuthorizationException { + return userProfileService.initializeUserProfile(authzToken); } @Override @SecurityCheck public String addUserProfile(AuthzToken authzToken, UserProfile userProfile) - throws UserProfileServiceException, AuthorizationException, TException { - try { - // Lowercase user id and internal id - userProfile.setUserId(userProfile.getUserId().toLowerCase()); - userProfile.setAiravataInternalUserId(userProfile.getUserId() + "@" + userProfile.getGatewayId()); - userProfile = userProfileRepository.updateUserProfile( - userProfile, getIAMUserProfileUpdater(authzToken, userProfile)); - if (null != userProfile) { - logger.info("Added UserProfile with userId: " + userProfile.getUserId()); - // replicate userProfile at end-places - dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.CREATE, userProfile); - // return userId - return userProfile.getUserId(); - } else { - throw new Exception("User creation failed. Please try again."); - } - } catch (Exception e) { - logger.error("Error while creating user profile", e); - UserProfileServiceException exception = new UserProfileServiceException(); - exception.setMessage("Error while creating user profile. More info : " + e.getMessage()); - throw exception; - } + throws UserProfileServiceException, AuthorizationException { + return userProfileService.addUserProfile(authzToken, userProfile); } @Override @SecurityCheck public boolean updateUserProfile(AuthzToken authzToken, UserProfile userProfile) - throws UserProfileServiceException, AuthorizationException, TException { - try { - // After updating the user profile in the database but before committing the transaction, the - // following will update the user profile in the IAM service also. If the update in the IAM service - // fails then the transaction will be rolled back. - Runnable iamUserProfileUpdater = getIAMUserProfileUpdater(authzToken, userProfile); - if (userProfileRepository.updateUserProfile(userProfile, iamUserProfileUpdater) != null) { - logger.info("Updated UserProfile with userId: " + userProfile.getUserId()); - // replicate userProfile at end-places - dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.UPDATE, userProfile); - return true; - } - return false; - } catch (Exception e) { - logger.error("Error while Updating user profile", e); - UserProfileServiceException exception = new UserProfileServiceException(); - exception.setMessage("Error while Updating user profile. More info : " + e.getMessage()); - throw exception; - } - } - - private Runnable getIAMUserProfileUpdater(AuthzToken authzToken, UserProfile userProfile) - throws UserProfileServiceException { - String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID); - return () -> { - try { - AiravataSecurityManager securityManager = SecurityManagerFactory.getSecurityManager(); - AuthzToken serviceAccountAuthzToken = - securityManager.getUserManagementServiceAccountAuthzToken(gatewayId); - IamAdminServices.Client iamAdminServicesClient = getIamAdminServicesClient(); - iamAdminServicesClient.updateUserProfile(serviceAccountAuthzToken, userProfile); - } catch (AiravataSecurityException | TException e) { - throw new RuntimeException("Failed to update user profile in IAM service", e); - } - }; + throws UserProfileServiceException, AuthorizationException { + return userProfileService.updateUserProfile(authzToken, userProfile); } @Override @SecurityCheck public UserProfile getUserProfileById(AuthzToken authzToken, String userId, String gatewayId) - throws UserProfileServiceException, AuthorizationException, TException { - try { - UserProfile userProfile = userProfileRepository.getUserProfileByIdAndGateWay(userId, gatewayId); - if (userProfile != null) return userProfile; - else - throw new Exception("User with userId: " + userId + ", in Gateway: " + gatewayId + ", does not exist."); - } catch (Exception e) { - logger.error("Error retrieving user profile by ID", e); - UserProfileServiceException exception = new UserProfileServiceException(); - exception.setMessage("Error retrieving user profile by ID. More info : " + e.getMessage()); - throw exception; - } + throws UserProfileServiceException, AuthorizationException { + return userProfileService.getUserProfileById(authzToken, userId, gatewayId); } @Override @SecurityCheck public boolean deleteUserProfile(AuthzToken authzToken, String userId, String gatewayId) - throws UserProfileServiceException, AuthorizationException, TException { - try { - // find user-profile - UserProfile userProfile = userProfileRepository.getUserProfileByIdAndGateWay(userId, gatewayId); - - // delete user - boolean deleteSuccess = userProfileRepository.delete(userId); - logger.info("Delete UserProfile with userId: " + userId + ", " + (deleteSuccess ? "Success!" : "Failed!")); - - if (deleteSuccess) { - // delete userProfile at end-places - dbEventPublisherUtils.publish(EntityType.USER_PROFILE, CrudType.DELETE, userProfile); - } - return deleteSuccess; - } catch (Exception e) { - logger.error("Error while deleting user profile", e); - UserProfileServiceException exception = new UserProfileServiceException(); - exception.setMessage("Error while deleting user profile. More info : " + e.getMessage()); - throw exception; - } + throws UserProfileServiceException, AuthorizationException { + return userProfileService.deleteUserProfile(authzToken, userId, gatewayId); } @Override @SecurityCheck public List getAllUserProfilesInGateway(AuthzToken authzToken, String gatewayId, int offset, int limit) - throws UserProfileServiceException, AuthorizationException, TException { - try { - List usersInGateway = - userProfileRepository.getAllUserProfilesInGateway(gatewayId, offset, limit); - if (usersInGateway != null) return usersInGateway; - else throw new Exception("There are no users for the requested gatewayId: " + gatewayId); - } catch (Exception e) { - logger.error("Error while retrieving user profile List", e); - UserProfileServiceException exception = new UserProfileServiceException(); - exception.setMessage("Error while retrieving user profile List. More info : " + e.getMessage()); - throw exception; - } + throws UserProfileServiceException, AuthorizationException { + return userProfileService.getAllUserProfilesInGateway(authzToken, gatewayId, offset, limit); } @Override public boolean doesUserExist(AuthzToken authzToken, String userId, String gatewayId) - throws UserProfileServiceException, AuthorizationException, TException { - try { - UserProfile userProfile = userProfileRepository.getUserProfileByIdAndGateWay(userId, gatewayId); - return null != userProfile; - } catch (Exception e) { - logger.error("Error while finding user profile", e); - UserProfileServiceException exception = new UserProfileServiceException(); - exception.setMessage("Error while finding user profile. More info : " + e.getMessage()); - throw exception; - } - } - - private IamAdminServices.Client getIamAdminServicesClient() throws UserProfileServiceException { - try { - final int serverPort = Integer.parseInt(ServerSettings.getProfileServiceServerPort()); - final String serverHost = ServerSettings.getProfileServiceServerHost(); - return ProfileServiceClientFactory.createIamAdminServiceClient(serverHost, serverPort); - } catch (IamAdminServicesException | ApplicationSettingsException e) { - logger.error("Failed to create IAM Admin Services client", e); - UserProfileServiceException ex = - new UserProfileServiceException("Failed to create IAM Admin Services client"); - throw ex; - } + throws UserProfileServiceException, AuthorizationException { + return userProfileService.doesUserExist(authzToken, userId, gatewayId); } } diff --git a/airavata-api/src/main/java/org/apache/airavata/service/security/SecurityManagerFactory.java b/airavata-api/src/main/java/org/apache/airavata/service/security/SecurityManagerFactory.java index 4d0e46dc06..b0ce1b8479 100644 --- a/airavata-api/src/main/java/org/apache/airavata/service/security/SecurityManagerFactory.java +++ b/airavata-api/src/main/java/org/apache/airavata/service/security/SecurityManagerFactory.java @@ -39,15 +39,15 @@ public static AiravataSecurityManager getSecurityManager() throws AiravataSecuri } catch (ClassNotFoundException e) { String error = "Security Manager class could not be found."; logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); + throw new AiravataSecurityException(error, e); } catch (ApplicationSettingsException e) { String error = "Error in reading the configuration related to Security Manager class."; logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); + throw new AiravataSecurityException(error, e); } catch (InstantiationException | IllegalAccessException e) { String error = "Error in instantiating the Security Manager class."; logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); + throw new AiravataSecurityException(error, e); } } } diff --git a/airavata-api/src/main/java/org/apache/airavata/service/security/authzcache/AuthzCacheManagerFactory.java b/airavata-api/src/main/java/org/apache/airavata/service/security/authzcache/AuthzCacheManagerFactory.java index d14ce5b02c..4404d6fb9a 100644 --- a/airavata-api/src/main/java/org/apache/airavata/service/security/authzcache/AuthzCacheManagerFactory.java +++ b/airavata-api/src/main/java/org/apache/airavata/service/security/authzcache/AuthzCacheManagerFactory.java @@ -39,19 +39,19 @@ public static AuthzCacheManager getAuthzCacheManager() throws AiravataSecurityEx } catch (ClassNotFoundException e) { String error = "Authorization Cache Manager class could not be found."; logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); + throw new AiravataSecurityException(error, e); } catch (ApplicationSettingsException e) { String error = "Error in reading the configuration related to Authorization Cache Manager class."; logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); + throw new AiravataSecurityException(error, e); } catch (InstantiationException e) { String error = "Error in instantiating the Authorization Cache Manager class."; logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); + throw new AiravataSecurityException(error, e); } catch (IllegalAccessException e) { String error = "Error in instantiating the Authorization Cache Manager class."; logger.error(e.getMessage(), e); - throw new AiravataSecurityException(error); + throw new AiravataSecurityException(error, e); } } } diff --git a/airavata-api/src/main/java/org/apache/airavata/service/security/authzcache/DefaultAuthzCacheManager.java b/airavata-api/src/main/java/org/apache/airavata/service/security/authzcache/DefaultAuthzCacheManager.java index 1a2ea0ff53..969f160165 100644 --- a/airavata-api/src/main/java/org/apache/airavata/service/security/authzcache/DefaultAuthzCacheManager.java +++ b/airavata-api/src/main/java/org/apache/airavata/service/security/authzcache/DefaultAuthzCacheManager.java @@ -59,7 +59,7 @@ public void addToAuthzCache(AuthzCacheIndex authzCacheIndex, AuthzCacheEntry aut AuthzCache.getInstance().put(authzCacheIndex, authzCacheEntry); } catch (ApplicationSettingsException e) { logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in obtaining the authorization cache instance."); + throw new AiravataSecurityException("Error in obtaining the authorization cache instance.", e); } } @@ -69,7 +69,7 @@ public boolean isAuthzDecisionCached(AuthzCacheIndex authzCacheIndex) throws Air return AuthzCache.getInstance().containsKey(authzCacheIndex); } catch (ApplicationSettingsException e) { logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in obtaining the authorization cache instance."); + throw new AiravataSecurityException("Error in obtaining the authorization cache instance.", e); } } @@ -79,7 +79,7 @@ public AuthzCacheEntry getAuthzCacheEntry(AuthzCacheIndex authzCacheIndex) throw return AuthzCache.getInstance().get(authzCacheIndex); } catch (ApplicationSettingsException e) { logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in obtaining the authorization cache instance."); + throw new AiravataSecurityException("Error in obtaining the authorization cache instance.", e); } } @@ -89,7 +89,7 @@ public void removeAuthzCacheEntry(AuthzCacheIndex authzCacheIndex) throws Airava AuthzCache.getInstance().remove(authzCacheIndex); } catch (ApplicationSettingsException e) { logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in obtaining the authorization cache instance."); + throw new AiravataSecurityException("Error in obtaining the authorization cache instance.", e); } } @@ -99,7 +99,7 @@ public void clearCache() throws AiravataSecurityException { AuthzCache.getInstance().clear(); } catch (ApplicationSettingsException e) { logger.error(e.getMessage(), e); - throw new AiravataSecurityException("Error in obtaining the authorization cache instance."); + throw new AiravataSecurityException("Error in obtaining the authorization cache instance.", e); } } } diff --git a/airavata-api/src/main/java/org/apache/airavata/service/security/interceptor/SecurityInterceptor.java b/airavata-api/src/main/java/org/apache/airavata/service/security/interceptor/SecurityInterceptor.java index eb328c5cf1..0b07f8e69f 100644 --- a/airavata-api/src/main/java/org/apache/airavata/service/security/interceptor/SecurityInterceptor.java +++ b/airavata-api/src/main/java/org/apache/airavata/service/security/interceptor/SecurityInterceptor.java @@ -74,10 +74,16 @@ private void authorize(AuthzToken authzToken, Map metaData) thro } } catch (AiravataSecurityException e) { logger.error(e.getMessage(), e); - throw new AuthorizationException("Error in authenticating or authorizing user."); + AuthorizationException exception = + new AuthorizationException("Error in authenticating or authorizing user."); + exception.initCause(e); + throw exception; } catch (ApplicationSettingsException e) { logger.error(e.getMessage(), e); - throw new AuthorizationException("Internal error in authenticating or authorizing user."); + AuthorizationException exception = + new AuthorizationException("Internal error in authenticating or authorizing user."); + exception.initCause(e); + throw exception; } } } diff --git a/airavata-api/src/main/java/org/apache/airavata/sharing/registry/messaging/SharingServiceDBEventHandler.java b/airavata-api/src/main/java/org/apache/airavata/sharing/registry/messaging/SharingServiceDBEventHandler.java index 173e809fe3..65261cc0a9 100644 --- a/airavata-api/src/main/java/org/apache/airavata/sharing/registry/messaging/SharingServiceDBEventHandler.java +++ b/airavata-api/src/main/java/org/apache/airavata/sharing/registry/messaging/SharingServiceDBEventHandler.java @@ -35,6 +35,7 @@ import org.apache.airavata.sharing.registry.client.SharingRegistryServiceClientFactory; import org.apache.airavata.sharing.registry.models.Domain; import org.apache.airavata.sharing.registry.models.Entity; +import org.apache.airavata.sharing.registry.models.EntityType; import org.apache.airavata.sharing.registry.models.PermissionType; import org.apache.airavata.sharing.registry.models.SharingRegistryException; import org.apache.airavata.sharing.registry.models.User; @@ -174,8 +175,7 @@ public void onMessage(MessageContext messageContext) { // Creating Entity Types for each domain log.info("Creating entity type. Id : " + domain.getDomainId() + ":PROJECT"); - org.apache.airavata.sharing.registry.models.EntityType entityType = - new org.apache.airavata.sharing.registry.models.EntityType(); + EntityType entityType = new EntityType(); entityType.setEntityTypeId(domain.getDomainId() + ":PROJECT"); entityType.setDomainId(domain.getDomainId()); entityType.setName("PROJECT"); diff --git a/airavata-api/src/main/java/org/apache/airavata/sharing/registry/server/SharingRegistryServerHandler.java b/airavata-api/src/main/java/org/apache/airavata/sharing/registry/server/SharingRegistryServerHandler.java index c171359b7f..7d846d7ac7 100644 --- a/airavata-api/src/main/java/org/apache/airavata/sharing/registry/server/SharingRegistryServerHandler.java +++ b/airavata-api/src/main/java/org/apache/airavata/sharing/registry/server/SharingRegistryServerHandler.java @@ -19,39 +19,32 @@ */ package org.apache.airavata.sharing.registry.server; -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.*; +import java.util.List; import org.apache.airavata.common.exception.ApplicationSettingsException; import org.apache.airavata.common.utils.DBInitializer; -import org.apache.airavata.sharing.registry.db.entities.*; -import org.apache.airavata.sharing.registry.db.repositories.*; -import org.apache.airavata.sharing.registry.db.utils.DBConstants; import org.apache.airavata.sharing.registry.db.utils.SharingRegistryDBInitConfig; import org.apache.airavata.sharing.registry.models.*; import org.apache.airavata.sharing.registry.service.cpi.SharingRegistryService; import org.apache.airavata.sharing.registry.service.cpi.sharing_cpiConstants; -import org.apache.commons.lang3.exception.ExceptionUtils; -import org.apache.thrift.TException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class SharingRegistryServerHandler implements SharingRegistryService.Iface { - private static final Logger logger = LoggerFactory.getLogger(SharingRegistryServerHandler.class); + private org.apache.airavata.service.SharingRegistryService sharingRegistryService; - public static String OWNER_PERMISSION_NAME = "OWNER"; + public static String OWNER_PERMISSION_NAME = + org.apache.airavata.service.SharingRegistryService.OWNER_PERMISSION_NAME; - public SharingRegistryServerHandler() throws ApplicationSettingsException, TException { + public SharingRegistryServerHandler() throws ApplicationSettingsException { this(new SharingRegistryDBInitConfig()); } public SharingRegistryServerHandler(SharingRegistryDBInitConfig sharingRegistryDBInitConfig) - throws ApplicationSettingsException, TException { + throws ApplicationSettingsException { DBInitializer.initializeDB(sharingRegistryDBInitConfig); + sharingRegistryService = new org.apache.airavata.service.SharingRegistryService(); } @Override - public String getAPIVersion() throws TException { + public String getAPIVersion() { return sharing_cpiConstants.SHARING_CPI_VERSION; } @@ -60,45 +53,13 @@ public String getAPIVersion() throws TException { * * */ @Override - public String createDomain(Domain domain) throws SharingRegistryException, DuplicateEntryException, TException { - try { - if ((new DomainRepository()).get(domain.getDomainId()) != null) - throw new DuplicateEntryException("There exist domain with given domain id"); - - domain.setCreatedTime(System.currentTimeMillis()); - domain.setUpdatedTime(System.currentTimeMillis()); - (new DomainRepository()).create(domain); - - // create the global permission for the domain - PermissionType permissionType = new PermissionType(); - permissionType.setPermissionTypeId(domain.getDomainId() + ":" + OWNER_PERMISSION_NAME); - permissionType.setDomainId(domain.getDomainId()); - permissionType.setName(OWNER_PERMISSION_NAME); - permissionType.setDescription("GLOBAL permission to " + domain.getDomainId()); - permissionType.setCreatedTime(System.currentTimeMillis()); - permissionType.setUpdatedTime(System.currentTimeMillis()); - (new PermissionTypeRepository()).create(permissionType); - - return domain.getDomainId(); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public String createDomain(Domain domain) throws SharingRegistryException, DuplicateEntryException { + return sharingRegistryService.createDomain(domain); } @Override - public boolean updateDomain(Domain domain) throws SharingRegistryException, TException { - try { - Domain oldDomain = (new DomainRepository()).get(domain.getDomainId()); - domain.setCreatedTime(oldDomain.getCreatedTime()); - domain.setUpdatedTime(System.currentTimeMillis()); - domain = getUpdatedObject(oldDomain, domain); - (new DomainRepository()).update(domain); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean updateDomain(Domain domain) throws SharingRegistryException { + return sharingRegistryService.updateDomain(domain); } /** @@ -107,44 +68,23 @@ public boolean updateDomain(Domain domain) throws SharingRegistryException, TExc * @param domainId */ @Override - public boolean isDomainExists(String domainId) throws SharingRegistryException, TException { - try { - return (new DomainRepository()).isExists(domainId); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean isDomainExists(String domainId) throws SharingRegistryException { + return sharingRegistryService.isDomainExists(domainId); } @Override - public boolean deleteDomain(String domainId) throws SharingRegistryException, TException { - try { - (new DomainRepository()).delete(domainId); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean deleteDomain(String domainId) throws SharingRegistryException { + return sharingRegistryService.deleteDomain(domainId); } @Override - public Domain getDomain(String domainId) throws SharingRegistryException, TException { - try { - return (new DomainRepository()).get(domainId); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public Domain getDomain(String domainId) throws SharingRegistryException { + return sharingRegistryService.getDomain(domainId); } @Override - public List getDomains(int offset, int limit) throws TException { - try { - return (new DomainRepository()).select(new HashMap<>(), offset, limit); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public List getDomains(int offset, int limit) throws SharingRegistryException { + return sharingRegistryService.getDomains(offset, limit); } /** @@ -152,67 +92,13 @@ public List getDomains(int offset, int limit) throws TException { * * */ @Override - public String createUser(User user) throws SharingRegistryException, DuplicateEntryException, TException { - try { - UserPK userPK = new UserPK(); - userPK.setUserId(user.getUserId()); - userPK.setDomainId(user.getDomainId()); - if ((new UserRepository()).get(userPK) != null) - throw new DuplicateEntryException("There exist user with given user id"); - - user.setCreatedTime(System.currentTimeMillis()); - user.setUpdatedTime(System.currentTimeMillis()); - (new UserRepository()).create(user); - - UserGroup userGroup = new UserGroup(); - userGroup.setGroupId(user.getUserId()); - userGroup.setDomainId(user.getDomainId()); - userGroup.setName(user.getUserName()); - userGroup.setDescription("user " + user.getUserName() + " group"); - userGroup.setOwnerId(user.getUserId()); - userGroup.setGroupType(GroupType.USER_LEVEL_GROUP); - userGroup.setGroupCardinality(GroupCardinality.SINGLE_USER); - (new UserGroupRepository()).create(userGroup); - - Domain domain = new DomainRepository().get(user.getDomainId()); - if (domain.getInitialUserGroupId() != null) { - addUsersToGroup( - user.getDomainId(), - Collections.singletonList(user.getUserId()), - domain.getInitialUserGroupId()); - } - - return user.getUserId(); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public String createUser(User user) throws SharingRegistryException, DuplicateEntryException { + return sharingRegistryService.createUser(user); } @Override - public boolean updatedUser(User user) throws SharingRegistryException, TException { - try { - UserPK userPK = new UserPK(); - userPK.setUserId(user.getUserId()); - userPK.setDomainId(user.getDomainId()); - User oldUser = (new UserRepository()).get(userPK); - user.setCreatedTime(oldUser.getCreatedTime()); - user.setUpdatedTime(System.currentTimeMillis()); - user = getUpdatedObject(oldUser, user); - (new UserRepository()).update(user); - - UserGroupPK userGroupPK = new UserGroupPK(); - userGroupPK.setGroupId(user.getUserId()); - userGroupPK.setDomainId(user.getDomainId()); - UserGroup userGroup = (new UserGroupRepository()).get(userGroupPK); - userGroup.setName(user.getUserName()); - userGroup.setDescription("user " + user.getUserName() + " group"); - updateGroup(userGroup); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean updatedUser(User user) throws SharingRegistryException { + return sharingRegistryService.updatedUser(user); } /** @@ -221,60 +107,23 @@ public boolean updatedUser(User user) throws SharingRegistryException, TExceptio * @param userId */ @Override - public boolean isUserExists(String domainId, String userId) throws SharingRegistryException, TException { - try { - UserPK userPK = new UserPK(); - userPK.setDomainId(domainId); - userPK.setUserId(userId); - return (new UserRepository()).isExists(userPK); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean isUserExists(String domainId, String userId) throws SharingRegistryException { + return sharingRegistryService.isUserExists(domainId, userId); } @Override - public boolean deleteUser(String domainId, String userId) throws SharingRegistryException, TException { - try { - UserPK userPK = new UserPK(); - userPK.setUserId(userId); - userPK.setDomainId(domainId); - (new UserRepository()).delete(userPK); - - UserGroupPK userGroupPK = new UserGroupPK(); - userGroupPK.setGroupId(userId); - userGroupPK.setDomainId(domainId); - (new UserGroupRepository()).delete(userGroupPK); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean deleteUser(String domainId, String userId) throws SharingRegistryException { + return sharingRegistryService.deleteUser(domainId, userId); } @Override - public User getUser(String domainId, String userId) throws SharingRegistryException, TException { - try { - UserPK userPK = new UserPK(); - userPK.setUserId(userId); - userPK.setDomainId(domainId); - return (new UserRepository()).get(userPK); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public User getUser(String domainId, String userId) throws SharingRegistryException { + return sharingRegistryService.getUser(domainId, userId); } @Override - public List getUsers(String domain, int offset, int limit) throws SharingRegistryException, TException { - try { - HashMap filters = new HashMap<>(); - filters.put(DBConstants.UserTable.DOMAIN_ID, domain); - return (new UserRepository()).select(filters, offset, limit); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public List getUsers(String domain, int offset, int limit) throws SharingRegistryException { + return sharingRegistryService.getUsers(domain, offset, limit); } /** @@ -282,50 +131,13 @@ public List getUsers(String domain, int offset, int limit) throws SharingR * * */ @Override - public String createGroup(UserGroup group) throws SharingRegistryException, TException { - try { - UserGroupPK userGroupPK = new UserGroupPK(); - userGroupPK.setGroupId(group.getGroupId()); - userGroupPK.setDomainId(group.getDomainId()); - if ((new UserGroupRepository()).get(userGroupPK) != null) - throw new SharingRegistryException("There exist group with given group id"); - // Client created groups are always of type MULTI_USER - group.setGroupCardinality(GroupCardinality.MULTI_USER); - group.setCreatedTime(System.currentTimeMillis()); - group.setUpdatedTime(System.currentTimeMillis()); - // Add group admins once the group is created - group.unsetGroupAdmins(); - (new UserGroupRepository()).create(group); - - addUsersToGroup(group.getDomainId(), Arrays.asList(group.getOwnerId()), group.getGroupId()); - return group.getGroupId(); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public String createGroup(UserGroup group) throws SharingRegistryException { + return sharingRegistryService.createGroup(group); } @Override - public boolean updateGroup(UserGroup group) throws SharingRegistryException, TException { - try { - group.setUpdatedTime(System.currentTimeMillis()); - UserGroupPK userGroupPK = new UserGroupPK(); - userGroupPK.setGroupId(group.getGroupId()); - userGroupPK.setDomainId(group.getDomainId()); - UserGroup oldGroup = (new UserGroupRepository()).get(userGroupPK); - group.setGroupCardinality(oldGroup.getGroupCardinality()); - group.setCreatedTime(oldGroup.getCreatedTime()); - group = getUpdatedObject(oldGroup, group); - - if (!group.getOwnerId().equals(oldGroup.getOwnerId())) - throw new SharingRegistryException("Group owner cannot be changed"); - - (new UserGroupRepository()).update(group); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean updateGroup(UserGroup group) throws SharingRegistryException { + return sharingRegistryService.updateGroup(group); } /** @@ -334,313 +146,94 @@ public boolean updateGroup(UserGroup group) throws SharingRegistryException, TEx * @param groupId * @return * @throws SharingRegistryException - * @throws TException - */ + * @ */ @Override - public boolean isGroupExists(String domainId, String groupId) throws SharingRegistryException, TException { - try { - UserGroupPK userGroupPK = new UserGroupPK(); - userGroupPK.setDomainId(domainId); - userGroupPK.setGroupId(groupId); - return (new UserGroupRepository()).isExists(userGroupPK); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean isGroupExists(String domainId, String groupId) throws SharingRegistryException { + return sharingRegistryService.isGroupExists(domainId, groupId); } @Override - public boolean deleteGroup(String domainId, String groupId) throws SharingRegistryException, TException { - try { - UserGroupPK userGroupPK = new UserGroupPK(); - userGroupPK.setGroupId(groupId); - userGroupPK.setDomainId(domainId); - (new UserGroupRepository()).delete(userGroupPK); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean deleteGroup(String domainId, String groupId) throws SharingRegistryException { + return sharingRegistryService.deleteGroup(domainId, groupId); } @Override - public UserGroup getGroup(String domainId, String groupId) throws SharingRegistryException, TException { - try { - UserGroupPK userGroupPK = new UserGroupPK(); - userGroupPK.setGroupId(groupId); - userGroupPK.setDomainId(domainId); - return (new UserGroupRepository()).get(userGroupPK); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public UserGroup getGroup(String domainId, String groupId) throws SharingRegistryException { + return sharingRegistryService.getGroup(domainId, groupId); } @Override - public List getGroups(String domain, int offset, int limit) throws TException { - try { - HashMap filters = new HashMap<>(); - filters.put(DBConstants.UserGroupTable.DOMAIN_ID, domain); - // Only return groups with MULTI_USER cardinality which is the only type of cardinality allowed for client - // created groups - filters.put(DBConstants.UserGroupTable.GROUP_CARDINALITY, GroupCardinality.MULTI_USER.name()); - return (new UserGroupRepository()).select(filters, offset, limit); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public List getGroups(String domain, int offset, int limit) throws SharingRegistryException { + return sharingRegistryService.getGroups(domain, offset, limit); } @Override public boolean addUsersToGroup(String domainId, List userIds, String groupId) - throws SharingRegistryException, TException { - try { - for (int i = 0; i < userIds.size(); i++) { - GroupMembership groupMembership = new GroupMembership(); - groupMembership.setParentId(groupId); - groupMembership.setChildId(userIds.get(i)); - groupMembership.setChildType(GroupChildType.USER); - groupMembership.setDomainId(domainId); - groupMembership.setCreatedTime(System.currentTimeMillis()); - groupMembership.setUpdatedTime(System.currentTimeMillis()); - (new GroupMembershipRepository()).create(groupMembership); - } - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.addUsersToGroup(domainId, userIds, groupId); } @Override public boolean removeUsersFromGroup(String domainId, List userIds, String groupId) - throws SharingRegistryException, TException { - try { - for (String userId : userIds) { - if (hasOwnerAccess(domainId, groupId, userId)) { - throw new SharingRegistryException( - "List of User Ids contains Owner Id. Cannot remove owner from the group"); - } - } - - for (int i = 0; i < userIds.size(); i++) { - GroupMembershipPK groupMembershipPK = new GroupMembershipPK(); - groupMembershipPK.setParentId(groupId); - groupMembershipPK.setChildId(userIds.get(i)); - groupMembershipPK.setDomainId(domainId); - (new GroupMembershipRepository()).delete(groupMembershipPK); - } - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.removeUsersFromGroup(domainId, userIds, groupId); } @Override public boolean transferGroupOwnership(String domainId, String groupId, String newOwnerId) - throws SharingRegistryException, TException { - try { - List groupUser = getGroupMembersOfTypeUser(domainId, groupId, 0, -1); - if (!isUserBelongsToGroup(groupUser, newOwnerId)) { - throw new SharingRegistryException("New group owner is not part of the group"); - } - - if (hasOwnerAccess(domainId, groupId, newOwnerId)) { - throw new DuplicateEntryException("User already the current owner of the group"); - } - // remove the new owner as Admin if present - if (hasAdminAccess(domainId, groupId, newOwnerId)) { - removeGroupAdmins(domainId, groupId, Arrays.asList(newOwnerId)); - } - - UserGroupPK userGroupPK = new UserGroupPK(); - userGroupPK.setGroupId(groupId); - userGroupPK.setDomainId(domainId); - UserGroup userGroup = (new UserGroupRepository()).get(userGroupPK); - UserGroup newUserGroup = new UserGroup(); - newUserGroup.setUpdatedTime(System.currentTimeMillis()); - newUserGroup.setOwnerId(newOwnerId); - newUserGroup.setGroupCardinality(GroupCardinality.MULTI_USER); - newUserGroup.setCreatedTime(userGroup.getCreatedTime()); - newUserGroup = getUpdatedObject(userGroup, newUserGroup); - - (new UserGroupRepository()).update(newUserGroup); - - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } - } - - private boolean isUserBelongsToGroup(List groupUser, String newOwnerId) { - for (User user : groupUser) { - if (user.getUserId().equals(newOwnerId)) { - return true; - } - } - return false; + throws SharingRegistryException { + return sharingRegistryService.transferGroupOwnership(domainId, groupId, newOwnerId); } @Override public boolean addGroupAdmins(String domainId, String groupId, List adminIds) - throws SharingRegistryException, TException { - try { - List groupUser = getGroupMembersOfTypeUser(domainId, groupId, 0, -1); - - for (String adminId : adminIds) { - if (!isUserBelongsToGroup(groupUser, adminId)) { - throw new SharingRegistryException( - "Admin not the user of the group. GroupId : " + groupId + ", AdminId : " + adminId); - } - GroupAdminPK groupAdminPK = new GroupAdminPK(); - groupAdminPK.setGroupId(groupId); - groupAdminPK.setAdminId(adminId); - groupAdminPK.setDomainId(domainId); - - if ((new GroupAdminRepository()).get(groupAdminPK) != null) - throw new DuplicateEntryException("User already an admin for the group"); - - GroupAdmin admin = new GroupAdmin(); - admin.setAdminId(adminId); - admin.setDomainId(domainId); - admin.setGroupId(groupId); - (new GroupAdminRepository()).create(admin); - } - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.addGroupAdmins(domainId, groupId, adminIds); } @Override public boolean removeGroupAdmins(String domainId, String groupId, List adminIds) - throws SharingRegistryException, TException { - try { - for (String adminId : adminIds) { - GroupAdminPK groupAdminPK = new GroupAdminPK(); - groupAdminPK.setAdminId(adminId); - groupAdminPK.setDomainId(domainId); - groupAdminPK.setGroupId(groupId); - (new GroupAdminRepository()).delete(groupAdminPK); - } - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.removeGroupAdmins(domainId, groupId, adminIds); } @Override - public boolean hasAdminAccess(String domainId, String groupId, String adminId) - throws SharingRegistryException, TException { - try { - GroupAdminPK groupAdminPK = new GroupAdminPK(); - groupAdminPK.setGroupId(groupId); - groupAdminPK.setAdminId(adminId); - groupAdminPK.setDomainId(domainId); - - if ((new GroupAdminRepository()).get(groupAdminPK) != null) return true; - return false; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean hasAdminAccess(String domainId, String groupId, String adminId) throws SharingRegistryException { + return sharingRegistryService.hasAdminAccess(domainId, groupId, adminId); } @Override - public boolean hasOwnerAccess(String domainId, String groupId, String ownerId) - throws SharingRegistryException, TException { - try { - UserGroupPK userGroupPK = new UserGroupPK(); - userGroupPK.setGroupId(groupId); - userGroupPK.setDomainId(domainId); - UserGroup getGroup = (new UserGroupRepository()).get(userGroupPK); - - if (getGroup.getOwnerId().equals(ownerId)) return true; - return false; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean hasOwnerAccess(String domainId, String groupId, String ownerId) throws SharingRegistryException { + return sharingRegistryService.hasOwnerAccess(domainId, groupId, ownerId); } @Override public List getGroupMembersOfTypeUser(String domainId, String groupId, int offset, int limit) - throws SharingRegistryException, TException { - try { - // TODO limit offset - List groupMemberUsers = (new GroupMembershipRepository()).getAllChildUsers(domainId, groupId); - return groupMemberUsers; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.getGroupMembersOfTypeUser(domainId, groupId, offset, limit); } @Override public List getGroupMembersOfTypeGroup(String domainId, String groupId, int offset, int limit) - throws SharingRegistryException, TException { - try { - // TODO limit offset - List groupMemberGroups = (new GroupMembershipRepository()).getAllChildGroups(domainId, groupId); - return groupMemberGroups; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.getGroupMembersOfTypeGroup(domainId, groupId, offset, limit); } @Override public boolean addChildGroupsToParentGroup(String domainId, List childIds, String groupId) - throws SharingRegistryException, TException { - try { - for (String childId : childIds) { - // Todo check for cyclic dependencies - GroupMembership groupMembership = new GroupMembership(); - groupMembership.setParentId(groupId); - groupMembership.setChildId(childId); - groupMembership.setChildType(GroupChildType.GROUP); - groupMembership.setDomainId(domainId); - groupMembership.setCreatedTime(System.currentTimeMillis()); - groupMembership.setUpdatedTime(System.currentTimeMillis()); - (new GroupMembershipRepository()).create(groupMembership); - } - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.addChildGroupsToParentGroup(domainId, childIds, groupId); } @Override public boolean removeChildGroupFromParentGroup(String domainId, String childId, String groupId) - throws SharingRegistryException, TException { - try { - GroupMembershipPK groupMembershipPK = new GroupMembershipPK(); - groupMembershipPK.setParentId(groupId); - groupMembershipPK.setChildId(childId); - groupMembershipPK.setDomainId(domainId); - (new GroupMembershipRepository()).delete(groupMembershipPK); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.removeChildGroupFromParentGroup(domainId, childId, groupId); } @Override - public List getAllMemberGroupsForUser(String domainId, String userId) - throws SharingRegistryException, TException { - try { - GroupMembershipRepository groupMembershipRepository = new GroupMembershipRepository(); - return groupMembershipRepository.getAllMemberGroupsForUser(domainId, userId); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public List getAllMemberGroupsForUser(String domainId, String userId) throws SharingRegistryException { + return sharingRegistryService.getAllMemberGroupsForUser(domainId, userId); } /** @@ -648,41 +241,13 @@ public List getAllMemberGroupsForUser(String domainId, String userId) * * */ @Override - public String createEntityType(EntityType entityType) - throws SharingRegistryException, DuplicateEntryException, TException { - try { - EntityTypePK entityTypePK = new EntityTypePK(); - entityTypePK.setDomainId(entityType.getDomainId()); - entityTypePK.setEntityTypeId(entityType.getEntityTypeId()); - if ((new EntityTypeRepository()).get(entityTypePK) != null) - throw new DuplicateEntryException("There exist EntityType with given EntityType id"); - - entityType.setCreatedTime(System.currentTimeMillis()); - entityType.setUpdatedTime(System.currentTimeMillis()); - (new EntityTypeRepository()).create(entityType); - return entityType.getEntityTypeId(); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public String createEntityType(EntityType entityType) throws SharingRegistryException, DuplicateEntryException { + return sharingRegistryService.createEntityType(entityType); } @Override - public boolean updateEntityType(EntityType entityType) throws SharingRegistryException, TException { - try { - entityType.setUpdatedTime(System.currentTimeMillis()); - EntityTypePK entityTypePK = new EntityTypePK(); - entityTypePK.setDomainId(entityType.getDomainId()); - entityTypePK.setEntityTypeId(entityType.getEntityTypeId()); - EntityType oldEntityType = (new EntityTypeRepository()).get(entityTypePK); - entityType.setCreatedTime(oldEntityType.getCreatedTime()); - entityType = getUpdatedObject(oldEntityType, entityType); - (new EntityTypeRepository()).update(entityType); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean updateEntityType(EntityType entityType) throws SharingRegistryException { + return sharingRegistryService.updateEntityType(entityType); } /** @@ -691,56 +256,23 @@ public boolean updateEntityType(EntityType entityType) throws SharingRegistryExc * @param entityTypeId */ @Override - public boolean isEntityTypeExists(String domainId, String entityTypeId) - throws SharingRegistryException, TException { - try { - EntityTypePK entityTypePK = new EntityTypePK(); - entityTypePK.setDomainId(domainId); - entityTypePK.setEntityTypeId(entityTypeId); - return (new EntityTypeRepository()).isExists(entityTypePK); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean isEntityTypeExists(String domainId, String entityTypeId) throws SharingRegistryException { + return sharingRegistryService.isEntityTypeExists(domainId, entityTypeId); } @Override - public boolean deleteEntityType(String domainId, String entityTypeId) throws SharingRegistryException, TException { - try { - EntityTypePK entityTypePK = new EntityTypePK(); - entityTypePK.setDomainId(domainId); - entityTypePK.setEntityTypeId(entityTypeId); - (new EntityTypeRepository()).delete(entityTypePK); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean deleteEntityType(String domainId, String entityTypeId) throws SharingRegistryException { + return sharingRegistryService.deleteEntityType(domainId, entityTypeId); } @Override - public EntityType getEntityType(String domainId, String entityTypeId) throws SharingRegistryException, TException { - try { - EntityTypePK entityTypePK = new EntityTypePK(); - entityTypePK.setDomainId(domainId); - entityTypePK.setEntityTypeId(entityTypeId); - return (new EntityTypeRepository()).get(entityTypePK); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public EntityType getEntityType(String domainId, String entityTypeId) throws SharingRegistryException { + return sharingRegistryService.getEntityType(domainId, entityTypeId); } @Override - public List getEntityTypes(String domain, int offset, int limit) throws TException { - try { - HashMap filters = new HashMap<>(); - filters.put(DBConstants.EntityTypeTable.DOMAIN_ID, domain); - return (new EntityTypeRepository()).select(filters, offset, limit); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public List getEntityTypes(String domain, int offset, int limit) throws SharingRegistryException { + return sharingRegistryService.getEntityTypes(domain, offset, limit); } /** @@ -749,38 +281,13 @@ public List getEntityTypes(String domain, int offset, int limit) thr */ @Override public String createPermissionType(PermissionType permissionType) - throws SharingRegistryException, DuplicateEntryException, TException { - try { - PermissionTypePK permissionTypePK = new PermissionTypePK(); - permissionTypePK.setDomainId(permissionType.getDomainId()); - permissionTypePK.setPermissionTypeId(permissionType.getPermissionTypeId()); - if ((new PermissionTypeRepository()).get(permissionTypePK) != null) - throw new DuplicateEntryException("There exist PermissionType with given PermissionType id"); - permissionType.setCreatedTime(System.currentTimeMillis()); - permissionType.setUpdatedTime(System.currentTimeMillis()); - (new PermissionTypeRepository()).create(permissionType); - return permissionType.getPermissionTypeId(); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException, DuplicateEntryException { + return sharingRegistryService.createPermissionType(permissionType); } @Override - public boolean updatePermissionType(PermissionType permissionType) throws SharingRegistryException, TException { - try { - permissionType.setUpdatedTime(System.currentTimeMillis()); - PermissionTypePK permissionTypePK = new PermissionTypePK(); - permissionTypePK.setDomainId(permissionType.getDomainId()); - permissionTypePK.setPermissionTypeId(permissionType.getPermissionTypeId()); - PermissionType oldPermissionType = (new PermissionTypeRepository()).get(permissionTypePK); - permissionType = getUpdatedObject(oldPermissionType, permissionType); - (new PermissionTypeRepository()).update(permissionType); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean updatePermissionType(PermissionType permissionType) throws SharingRegistryException { + return sharingRegistryService.updatePermissionType(permissionType); } /** @@ -789,59 +296,24 @@ public boolean updatePermissionType(PermissionType permissionType) throws Sharin * @param permissionId */ @Override - public boolean isPermissionExists(String domainId, String permissionId) - throws SharingRegistryException, TException { - try { - PermissionTypePK permissionTypePK = new PermissionTypePK(); - permissionTypePK.setDomainId(domainId); - permissionTypePK.setPermissionTypeId(permissionId); - return (new PermissionTypeRepository()).isExists(permissionTypePK); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean isPermissionExists(String domainId, String permissionId) throws SharingRegistryException { + return sharingRegistryService.isPermissionExists(domainId, permissionId); } @Override - public boolean deletePermissionType(String domainId, String permissionTypeId) - throws SharingRegistryException, TException { - try { - PermissionTypePK permissionTypePK = new PermissionTypePK(); - permissionTypePK.setDomainId(domainId); - permissionTypePK.setPermissionTypeId(permissionTypeId); - (new PermissionTypeRepository()).delete(permissionTypePK); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean deletePermissionType(String domainId, String permissionTypeId) throws SharingRegistryException { + return sharingRegistryService.deletePermissionType(domainId, permissionTypeId); } @Override - public PermissionType getPermissionType(String domainId, String permissionTypeId) - throws SharingRegistryException, TException { - try { - PermissionTypePK permissionTypePK = new PermissionTypePK(); - permissionTypePK.setDomainId(domainId); - permissionTypePK.setPermissionTypeId(permissionTypeId); - return (new PermissionTypeRepository()).get(permissionTypePK); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public PermissionType getPermissionType(String domainId, String permissionTypeId) throws SharingRegistryException { + return sharingRegistryService.getPermissionType(domainId, permissionTypeId); } @Override public List getPermissionTypes(String domain, int offset, int limit) - throws SharingRegistryException, TException { - try { - HashMap filters = new HashMap<>(); - filters.put(DBConstants.PermissionTypeTable.DOMAIN_ID, domain); - return (new PermissionTypeRepository()).select(filters, offset, limit); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.getPermissionTypes(domain, offset, limit); } /** @@ -849,119 +321,13 @@ public List getPermissionTypes(String domain, int offset, int li * * */ @Override - public String createEntity(Entity entity) throws SharingRegistryException, DuplicateEntryException, TException { - try { - EntityPK entityPK = new EntityPK(); - entityPK.setDomainId(entity.getDomainId()); - entityPK.setEntityId(entity.getEntityId()); - if ((new EntityRepository()).get(entityPK) != null) - throw new DuplicateEntryException("There exist Entity with given Entity id"); - - UserPK userPK = new UserPK(); - userPK.setDomainId(entity.getDomainId()); - userPK.setUserId(entity.getOwnerId()); - if (!(new UserRepository()).isExists(userPK)) { - // Todo this is for Airavata easy integration. Proper thing is to throw an exception here - User user = new User(); - user.setUserId(entity.getOwnerId()); - user.setDomainId(entity.getDomainId()); - user.setUserName(user.getUserId().split("@")[0]); - - createUser(user); - } - entity.setCreatedTime(System.currentTimeMillis()); - entity.setUpdatedTime(System.currentTimeMillis()); - - if (entity.getOriginalEntityCreationTime() == 0) { - entity.setOriginalEntityCreationTime(entity.getCreatedTime()); - } - (new EntityRepository()).create(entity); - - // Assigning global permission for the owner - Sharing newSharing = new Sharing(); - newSharing.setPermissionTypeId( - (new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(entity.getDomainId())); - newSharing.setEntityId(entity.getEntityId()); - newSharing.setGroupId(entity.getOwnerId()); - newSharing.setSharingType(SharingType.DIRECT_CASCADING); - newSharing.setInheritedParentId(entity.getEntityId()); - newSharing.setDomainId(entity.getDomainId()); - newSharing.setCreatedTime(System.currentTimeMillis()); - newSharing.setUpdatedTime(System.currentTimeMillis()); - - (new SharingRepository()).create(newSharing); - - // creating records for inherited permissions - if (entity.getParentEntityId() != null && entity.getParentEntityId() != "") { - addCascadingPermissionsForEntity(entity); - } - - return entity.getEntityId(); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - SharingRegistryException sharingRegistryException = new SharingRegistryException(); - sharingRegistryException.setMessage(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - throw sharingRegistryException; - } - } - - private void addCascadingPermissionsForEntity(Entity entity) throws SharingRegistryException { - Sharing newSharing; - List sharings = (new SharingRepository()) - .getCascadingPermissionsForEntity(entity.getDomainId(), entity.getParentEntityId()); - for (Sharing sharing : sharings) { - newSharing = new Sharing(); - newSharing.setPermissionTypeId(sharing.getPermissionTypeId()); - newSharing.setEntityId(entity.getEntityId()); - newSharing.setGroupId(sharing.getGroupId()); - newSharing.setInheritedParentId(sharing.getInheritedParentId()); - newSharing.setSharingType(SharingType.INDIRECT_CASCADING); - newSharing.setDomainId(entity.getDomainId()); - newSharing.setCreatedTime(System.currentTimeMillis()); - newSharing.setUpdatedTime(System.currentTimeMillis()); - - (new SharingRepository()).create(newSharing); - } + public String createEntity(Entity entity) throws SharingRegistryException, DuplicateEntryException { + return sharingRegistryService.createEntity(entity); } @Override - public boolean updateEntity(Entity entity) throws SharingRegistryException, TException { - try { - // TODO Check for permission changes - entity.setUpdatedTime(System.currentTimeMillis()); - EntityPK entityPK = new EntityPK(); - entityPK.setDomainId(entity.getDomainId()); - entityPK.setEntityId(entity.getEntityId()); - Entity oldEntity = (new EntityRepository()).get(entityPK); - entity.setCreatedTime(oldEntity.getCreatedTime()); - // check if parent entity changed and re-add inherited permissions - if (!Objects.equals(oldEntity.getParentEntityId(), entity.getParentEntityId())) { - logger.debug("Parent entity changed for {}, updating inherited permissions", entity.getEntityId()); - if (oldEntity.getParentEntityId() != null && oldEntity.getParentEntityId() != "") { - logger.debug( - "Removing inherited permissions from {} that were inherited from parent {}", - entity.getEntityId(), - oldEntity.getParentEntityId()); - (new SharingRepository()) - .removeAllIndirectCascadingPermissionsForEntity(entity.getDomainId(), entity.getEntityId()); - } - if (entity.getParentEntityId() != null && entity.getParentEntityId() != "") { - // re-add INDIRECT_CASCADING permissions - logger.debug( - "Adding inherited permissions to {} that are inherited from parent {}", - entity.getEntityId(), - entity.getParentEntityId()); - addCascadingPermissionsForEntity(entity); - } - } - entity = getUpdatedObject(oldEntity, entity); - entity.setSharedCount((new SharingRepository()).getSharedCount(entity.getDomainId(), entity.getEntityId())); - (new EntityRepository()).update(entity); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean updateEntity(Entity entity) throws SharingRegistryException { + return sharingRegistryService.updateEntity(entity); } /** @@ -970,109 +336,49 @@ public boolean updateEntity(Entity entity) throws SharingRegistryException, TExc * @param entityId */ @Override - public boolean isEntityExists(String domainId, String entityId) throws SharingRegistryException, TException { - try { - EntityPK entityPK = new EntityPK(); - entityPK.setDomainId(domainId); - entityPK.setEntityId(entityId); - return (new EntityRepository()).isExists(entityPK); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean isEntityExists(String domainId, String entityId) throws SharingRegistryException { + return sharingRegistryService.isEntityExists(domainId, entityId); } @Override - public boolean deleteEntity(String domainId, String entityId) throws SharingRegistryException, TException { - try { - // TODO Check for permission changes - EntityPK entityPK = new EntityPK(); - entityPK.setDomainId(domainId); - entityPK.setEntityId(entityId); - (new EntityRepository()).delete(entityPK); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public boolean deleteEntity(String domainId, String entityId) throws SharingRegistryException { + return sharingRegistryService.deleteEntity(domainId, entityId); } @Override - public Entity getEntity(String domainId, String entityId) throws SharingRegistryException, TException { - try { - EntityPK entityPK = new EntityPK(); - entityPK.setDomainId(domainId); - entityPK.setEntityId(entityId); - return (new EntityRepository()).get(entityPK); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + public Entity getEntity(String domainId, String entityId) throws SharingRegistryException { + return sharingRegistryService.getEntity(domainId, entityId); } @Override public List searchEntities( String domainId, String userId, List filters, int offset, int limit) - throws SharingRegistryException, TException { - try { - List groupIds = new ArrayList<>(); - groupIds.add(userId); - (new GroupMembershipRepository()) - .getAllParentMembershipsForChild(domainId, userId).stream() - .forEach(gm -> groupIds.add(gm.getParentId())); - return (new EntityRepository()).searchEntities(domainId, groupIds, filters, offset, limit); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.searchEntities(domainId, userId, filters, offset, limit); } @Override public List getListOfSharedUsers(String domainId, String entityId, String permissionTypeId) - throws SharingRegistryException, TException { - try { - return (new UserRepository()).getAccessibleUsers(domainId, entityId, permissionTypeId); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.getListOfSharedUsers(domainId, entityId, permissionTypeId); } @Override public List getListOfDirectlySharedUsers(String domainId, String entityId, String permissionTypeId) - throws SharingRegistryException, TException { - try { - return (new UserRepository()).getDirectlyAccessibleUsers(domainId, entityId, permissionTypeId); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - SharingRegistryException sharingRegistryException = new SharingRegistryException(); - sharingRegistryException.setMessage(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - throw sharingRegistryException; - } + throws SharingRegistryException { + return sharingRegistryService.getListOfDirectlySharedUsers(domainId, entityId, permissionTypeId); } @Override public List getListOfSharedGroups(String domainId, String entityId, String permissionTypeId) - throws SharingRegistryException, TException { - try { - return (new UserGroupRepository()).getAccessibleGroups(domainId, entityId, permissionTypeId); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.getListOfSharedGroups(domainId, entityId, permissionTypeId); } @Override public List getListOfDirectlySharedGroups(String domainId, String entityId, String permissionTypeId) - throws SharingRegistryException, TException { - try { - return (new UserGroupRepository()).getDirectlyAccessibleGroups(domainId, entityId, permissionTypeId); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - SharingRegistryException sharingRegistryException = new SharingRegistryException(); - sharingRegistryException.setMessage(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - throw sharingRegistryException; - } + throws SharingRegistryException { + return sharingRegistryService.getListOfDirectlySharedGroups(domainId, entityId, permissionTypeId); } /** @@ -1084,18 +390,13 @@ public List getListOfDirectlySharedGroups(String domainId, String ent * @param cascadePermission * @return * @throws SharingRegistryException - * @throws TException - */ + * @ */ @Override public boolean shareEntityWithUsers( String domainId, String entityId, List userList, String permissionTypeId, boolean cascadePermission) - throws SharingRegistryException, TException { - try { - return shareEntity(domainId, entityId, userList, permissionTypeId, cascadePermission); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.shareEntityWithUsers( + domainId, entityId, userList, permissionTypeId, cascadePermission); } @Override @@ -1105,236 +406,28 @@ public boolean shareEntityWithGroups( List groupList, String permissionTypeId, boolean cascadePermission) - throws SharingRegistryException, TException { - try { - return shareEntity(domainId, entityId, groupList, permissionTypeId, cascadePermission); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } - } - - private boolean shareEntity( - String domainId, - String entityId, - List groupOrUserList, - String permissionTypeId, - boolean cascadePermission) - throws SharingRegistryException, TException { - try { - if (permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))) { - throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be assigned or removed"); - } - - List sharings = new ArrayList<>(); - - // Adding permission for the specified users/groups for the specified entity - LinkedList temp = new LinkedList<>(); - for (String userId : groupOrUserList) { - Sharing sharing = new Sharing(); - sharing.setPermissionTypeId(permissionTypeId); - sharing.setEntityId(entityId); - sharing.setGroupId(userId); - sharing.setInheritedParentId(entityId); - sharing.setDomainId(domainId); - if (cascadePermission) { - sharing.setSharingType(SharingType.DIRECT_CASCADING); - } else { - sharing.setSharingType(SharingType.DIRECT_NON_CASCADING); - } - sharing.setCreatedTime(System.currentTimeMillis()); - sharing.setUpdatedTime(System.currentTimeMillis()); - - sharings.add(sharing); - } - - if (cascadePermission) { - // Adding permission for the specified users/groups for all child entities - (new EntityRepository()) - .getChildEntities(domainId, entityId).stream().forEach(e -> temp.addLast(e)); - while (temp.size() > 0) { - Entity entity = temp.pop(); - String childEntityId = entity.getEntityId(); - for (String userId : groupOrUserList) { - Sharing sharing = new Sharing(); - sharing.setPermissionTypeId(permissionTypeId); - sharing.setEntityId(childEntityId); - sharing.setGroupId(userId); - sharing.setInheritedParentId(entityId); - sharing.setSharingType(SharingType.INDIRECT_CASCADING); - sharing.setInheritedParentId(entityId); - sharing.setDomainId(domainId); - sharing.setCreatedTime(System.currentTimeMillis()); - sharing.setUpdatedTime(System.currentTimeMillis()); - sharings.add(sharing); - (new EntityRepository()) - .getChildEntities(domainId, childEntityId).stream() - .forEach(e -> temp.addLast(e)); - } - } - } - (new SharingRepository()).create(sharings); - - EntityPK entityPK = new EntityPK(); - entityPK.setDomainId(domainId); - entityPK.setEntityId(entityId); - Entity entity = (new EntityRepository()).get(entityPK); - entity.setSharedCount((new SharingRepository()).getSharedCount(domainId, entityId)); - (new EntityRepository()).update(entity); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.shareEntityWithGroups( + domainId, entityId, groupList, permissionTypeId, cascadePermission); } @Override public boolean revokeEntitySharingFromUsers( String domainId, String entityId, List userList, String permissionTypeId) - throws SharingRegistryException, TException { - try { - if (permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))) { - throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be assigned or removed"); - } - return revokeEntitySharing(domainId, entityId, userList, permissionTypeId); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.revokeEntitySharingFromUsers(domainId, entityId, userList, permissionTypeId); } @Override public boolean revokeEntitySharingFromGroups( String domainId, String entityId, List groupList, String permissionTypeId) - throws SharingRegistryException, TException { - try { - if (permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))) { - throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be assigned or removed"); - } - return revokeEntitySharing(domainId, entityId, groupList, permissionTypeId); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } + throws SharingRegistryException { + return sharingRegistryService.revokeEntitySharingFromGroups(domainId, entityId, groupList, permissionTypeId); } @Override public boolean userHasAccess(String domainId, String userId, String entityId, String permissionTypeId) - throws SharingRegistryException, TException { - try { - // check whether the user has permission directly or indirectly - List parentMemberships = - (new GroupMembershipRepository()).getAllParentMembershipsForChild(domainId, userId); - List groupIds = new ArrayList<>(); - parentMemberships.stream().forEach(pm -> groupIds.add(pm.getParentId())); - groupIds.add(userId); - return (new SharingRepository()) - .hasAccess( - domainId, - entityId, - groupIds, - Arrays.asList( - permissionTypeId, - (new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } - } - - public boolean revokeEntitySharing( - String domainId, String entityId, List groupOrUserList, String permissionTypeId) throws SharingRegistryException { - try { - if (permissionTypeId.equals((new PermissionTypeRepository()).getOwnerPermissionTypeIdForDomain(domainId))) { - throw new SharingRegistryException(OWNER_PERMISSION_NAME + " permission cannot be removed"); - } - - // revoking permission for the entity - for (String groupId : groupOrUserList) { - SharingPK sharingPK = new SharingPK(); - sharingPK.setEntityId(entityId); - sharingPK.setGroupId(groupId); - sharingPK.setPermissionTypeId(permissionTypeId); - sharingPK.setInheritedParentId(entityId); - sharingPK.setDomainId(domainId); - - (new SharingRepository()).delete(sharingPK); - } - - // revoking permission from inheritance - List temp = new ArrayList<>(); - (new SharingRepository()) - .getIndirectSharedChildren(domainId, entityId, permissionTypeId).stream() - .forEach(s -> temp.add(s)); - for (Sharing sharing : temp) { - String childEntityId = sharing.getEntityId(); - for (String groupId : groupOrUserList) { - SharingPK sharingPK = new SharingPK(); - sharingPK.setEntityId(childEntityId); - sharingPK.setGroupId(groupId); - sharingPK.setPermissionTypeId(permissionTypeId); - sharingPK.setInheritedParentId(entityId); - sharingPK.setDomainId(domainId); - - (new SharingRepository()).delete(sharingPK); - } - } - - EntityPK entityPK = new EntityPK(); - entityPK.setDomainId(domainId); - entityPK.setEntityId(entityId); - Entity entity = (new EntityRepository()).get(entityPK); - entity.setSharedCount((new SharingRepository()).getSharedCount(domainId, entityId)); - (new EntityRepository()).update(entity); - return true; - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - throw new SharingRegistryException(ex.getMessage() + " Stack trace:" + ExceptionUtils.getStackTrace(ex)); - } - } - - private T getUpdatedObject(T oldEntity, T newEntity) throws SharingRegistryException { - Field[] newEntityFields = newEntity.getClass().getDeclaredFields(); - Hashtable newHT = fieldsToHT(newEntityFields, newEntity); - - Class oldEntityClass = oldEntity.getClass(); - Field[] oldEntityFields = oldEntityClass.getDeclaredFields(); - - for (Field field : oldEntityFields) { - if (!Modifier.isFinal(field.getModifiers())) { - field.setAccessible(true); - Object o = newHT.get(field.getName()); - if (o != null) { - Field f = null; - try { - f = oldEntityClass.getDeclaredField(field.getName()); - f.setAccessible(true); - logger.debug("setting " + f.getName()); - f.set(oldEntity, o); - } catch (Exception e) { - throw new SharingRegistryException(e.getMessage()); - } - } - } - } - return oldEntity; - } - - private static Hashtable fieldsToHT(Field[] fields, Object obj) { - Hashtable hashtable = new Hashtable<>(); - for (Field field : fields) { - field.setAccessible(true); - try { - Object retrievedObject = field.get(obj); - if (retrievedObject != null) { - logger.debug("scanning " + field.getName()); - hashtable.put(field.getName(), field.get(obj)); - } - } catch (IllegalAccessException e) { - e.printStackTrace(); - } - } - return hashtable; + return sharingRegistryService.userHasAccess(domainId, userId, entityId, permissionTypeId); } } diff --git a/thrift-interface-descriptions/base-api/base_api.thrift b/thrift-interface-descriptions/base-api/base_api.thrift index 317f97b18a..583f6d1b69 100644 --- a/thrift-interface-descriptions/base-api/base_api.thrift +++ b/thrift-interface-descriptions/base-api/base_api.thrift @@ -5,6 +5,8 @@ namespace perl ApacheAiravataBaseAPI namespace py airavata.base.api namespace js ApacheAiravataBaseAPI +include "../airavata-apis/airavata_errors.thrift" + service BaseAPI { - string getAPIVersion() + string getAPIVersion() throws (1: airavata_errors.AiravataSystemException ase) } \ No newline at end of file diff --git a/thrift-interface-descriptions/service-cpis/orchestrator-cpi.thrift b/thrift-interface-descriptions/service-cpis/orchestrator-cpi.thrift index 7eb90de20c..0e5a021223 100644 --- a/thrift-interface-descriptions/service-cpis/orchestrator-cpi.thrift +++ b/thrift-interface-descriptions/service-cpis/orchestrator-cpi.thrift @@ -42,7 +42,7 @@ service OrchestratorService extends base_api.BaseAPI { * @return sucess/failure * **/ - bool launchExperiment (1: required string experimentId, 2: required string gatewayId), + bool launchExperiment (1: required string experimentId, 2: required string gatewayId) throws (1: airavata_errors.AiravataSystemException ase), /** * In order to run single applications users should create an associating @@ -54,7 +54,7 @@ service OrchestratorService extends base_api.BaseAPI { * @return sucess/failure * **/ - bool launchProcess (1: required string processId, 2: required string airavataCredStoreToken, 3: required string gatewayId), + bool launchProcess (1: required string processId, 2: required string airavataCredStoreToken, 3: required string gatewayId) throws (1: airavata_errors.AiravataSystemException ase), /** * @@ -75,5 +75,5 @@ service OrchestratorService extends base_api.BaseAPI { * @return sucess/failure * **/ - bool terminateExperiment (1: required string experimentId, 2: required string gatewayId) + bool terminateExperiment (1: required string experimentId, 2: required string gatewayId) throws (1: airavata_errors.AiravataSystemException ase) } diff --git a/thrift-interface-descriptions/service-cpis/sharing_cpi.thrift b/thrift-interface-descriptions/service-cpis/sharing_cpi.thrift index d76012219d..e608ee7873 100644 --- a/thrift-interface-descriptions/service-cpis/sharing_cpi.thrift +++ b/thrift-interface-descriptions/service-cpis/sharing_cpi.thrift @@ -105,7 +105,7 @@ service SharingRegistryService extends base_api.BaseAPI { /**

API method to get groups in a domainId.

*/ - list getGroups(1: required string domainId, 2: required i32 offset, 3: required i32 limit) + list getGroups(1: required string domainId, 2: required i32 offset, 3: required i32 limit) throws (1: sharing_models.SharingRegistryException sre) /**

API method to add list of users to a group