use of com.emc.storageos.svcs.errorhandling.resources.APIException in project coprhd-controller by CoprHD.
the class AuthenticationResource method formlogin.
/**
* Authenticates a user with credentials provided in the form data of the request.
* This method is for internal use by formlogin page.
*
* @brief INTERNAL USE
*
* @param request the login request from the client.
* @param servletResponse the response to be sent out to client.
* @param service to be used to redirect on successful authentication.
* @param source to be used to identify if the request is coming from portal
* or some other client.
* @param fragment to used to identify the service catalog to redirect on
* successful authentication.
*
* @return On successful authentication the client will be redirected to the provided service.
* @throws IOException
*/
@POST
@Produces({ MediaType.APPLICATION_XML, MediaType.TEXT_HTML })
@Consumes("application/x-www-form-urlencoded")
@Path("formlogin")
public Response formlogin(@Context HttpServletRequest request, @Context HttpServletResponse servletResponse, @QueryParam("service") String service, @QueryParam("src") String source, @QueryParam("fragment") String fragment, MultivaluedMap<String, String> formData) throws IOException {
boolean isPasswordExpired = false;
String loginError = null;
if (service == null || service.isEmpty()) {
loginError = FORM_LOGIN_POST_NO_SERVICE_ERROR;
}
String updatedService = service;
if (StringUtils.isNotBlank(service) && StringUtils.isNotBlank(fragment)) {
updatedService = updatedService + "#" + fragment;
}
// Check invalid login count from the client IP
boolean updateInvalidLoginCount = true;
String clientIP = _invLoginManager.getClientIP(request);
_log.debug("Client IP: {}", clientIP);
if (_invLoginManager.isTheClientIPBlocked(clientIP) == true) {
_log.error("The client IP is blocked for too many invalid login attempts: " + clientIP);
int minutes = _invLoginManager.getTimeLeftToUnblock(clientIP);
loginError = String.format("%s.<br>Will be cleared within %d minutes", FORM_INVALID_LOGIN_LIMIT_ERROR, minutes);
updateInvalidLoginCount = false;
}
if (null == loginError) {
String rememberMeStr = formData.getFirst("remember");
boolean rememberMe = StringUtils.isNotBlank(rememberMeStr) && rememberMeStr.equalsIgnoreCase("true");
// Look for a token passed in the form. If so, validate it and return it back
// as a cookie if valid. Else, continue with the normal flow of formlogin to validate
// credentials
String tokenFromForm = formData.getFirst(AUTH_FORM_LOGIN_TOKEN_PARAM);
if (StringUtils.isNotBlank(tokenFromForm)) {
try {
StorageOSUserDAO userDAOFromForm = _tokenManager.validateToken(tokenFromForm);
if (userDAOFromForm != null) {
_log.debug("Form login was posted with valid token");
return buildLoginResponse(updatedService, source, true, rememberMe, new LoginStatus(userDAOFromForm.getUserName(), tokenFromForm, false), request);
}
_log.error("Auth token passed to this formlogin could not be validated and returned null user");
loginError = FORM_INVALID_AUTH_TOKEN_ERROR;
} catch (APIException ex) {
// It is possible that validateToken would throw if the passed in token is unparsable
// Unlike the regular use case for validatetoken which is done inside api calls, here we are
// building a response to a web page, so we need to catch this and let the rest of this method
// proceed which will result in requesting new credentials.
loginError = FORM_INVALID_AUTH_TOKEN_ERROR;
_log.error("Auth token passed to this formlogin could not be validated. Exception: ", ex);
} catch (URISyntaxException e) {
loginError = SERVICE_URL_FORMAT_ERROR;
}
}
UsernamePasswordCredentials credentials = getFormCredentials(formData);
if (null == loginError) {
loginError = FORM_LOGIN_BAD_CREDS_ERROR;
}
try {
if (credentials != null) {
StorageOSUserDAO user = authenticateUser(credentials);
if (user != null) {
validateLocalUserExpiration(credentials);
String token = _tokenManager.getToken(user);
if (token == null) {
_log.error("Could not generate token for user: {}", user.getUserName());
auditOp(null, null, OperationTypeEnum.AUTHENTICATION, false, null, credentials.getUserName());
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
_log.debug("Redirecting to the original service: {}", updatedService);
_invLoginManager.removeInvalidRecord(clientIP);
auditOp(URI.create(user.getTenantId()), URI.create(user.getUserName()), OperationTypeEnum.AUTHENTICATION, true, null, credentials.getUserName());
// If remember me check box is on, set the expiration time.
return buildLoginResponse(updatedService, source, true, rememberMe, new LoginStatus(user.getUserName(), token, null != credentials), request);
}
} else {
// Do not update the invalid login count for this client IP if credentials are not provided
updateInvalidLoginCount = false;
}
} catch (APIException e) {
loginError = e.getMessage();
if (loginError.contains("expired")) {
isPasswordExpired = true;
}
} catch (URISyntaxException e) {
loginError = SERVICE_URL_FORMAT_ERROR;
}
}
// Mark this invalid login as a failure in ZK from the client IP
if (updateInvalidLoginCount) {
_invLoginManager.markErrorLogin(clientIP);
}
if (null != loginError) {
_log.error(loginError);
}
String formLP = null;
if (isPasswordExpired) {
formLP = getFormChangePasswordPage(updatedService, source, request.getServerName(), MessageFormat.format(FORM_LOGIN_AUTH_ERROR_ENT, loginError));
} else {
formLP = getFormLoginPage(updatedService, source, request.getServerName(), MessageFormat.format(FORM_LOGIN_AUTH_ERROR_ENT, loginError));
}
auditOp(null, null, OperationTypeEnum.AUTHENTICATION, false, null, getFormCredentials(formData).getUserName());
if (formLP != null) {
return Response.ok(formLP).type(MediaType.TEXT_HTML).cacheControl(_cacheControl).header(HEADER_PRAGMA, HEADER_PRAGMA_VALUE).build();
} else {
_log.error("Could not generate custom (form) login page");
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}
use of com.emc.storageos.svcs.errorhandling.resources.APIException in project coprhd-controller by CoprHD.
the class InternalVirtualArrayApiTest method testInternalVirtualArray.
@Test
public void testInternalVirtualArray() throws Exception {
long timestamp = System.currentTimeMillis();
// 1. CREATE subtenants
String subtenant_url = "/tenants/" + _rootTenantId.toString() + "/subtenants";
TenantCreateParam tenantParam = new TenantCreateParam();
String subtenant_label = "subtenant" + String.valueOf(timestamp);
tenantParam.setLabel(subtenant_label);
tenantParam.setUserMappings(new ArrayList<UserMappingParam>());
UserMappingParam tenantMapping = new UserMappingParam();
// Add an domain to the mapping
tenantMapping.setDomain("sanity.LOCAL");
// Add an attribute scope to the mapping
UserMappingAttributeParam tenantAttr = new UserMappingAttributeParam();
tenantAttr.setKey("OU");
tenantAttr.setValues(Collections.singletonList(subtenant_label));
tenantMapping.setAttributes(Collections.singletonList(tenantAttr));
tenantParam.getUserMappings().add(tenantMapping);
TenantOrgRestRep subtenant = rTAdminGr.path(subtenant_url).header(RequestProcessingUtils.AUTH_TOKEN_HEADER, _rootToken).post(TenantOrgRestRep.class, tenantParam);
Assert.assertTrue(subtenant.getName().equals(subtenant_label));
Assert.assertEquals(1, subtenant.getUserMappings().size());
// 2. create neighborhoods for test
VirtualArrayCreateParam neighborhoodParam = new VirtualArrayCreateParam();
neighborhoodParam.setLabel("nb1" + String.valueOf(timestamp));
VirtualArrayRestRep n1 = rSys.path("/vdc/varrays").post(VirtualArrayRestRep.class, neighborhoodParam);
Assert.assertNotNull(n1.getId());
// 3. set protection type
String sProtectionType = "protectionType1";
VirtualArrayRestRep resp = _internalVarrayClient.setProtectionType(n1.getId(), sProtectionType);
Assert.assertTrue(resp != null);
Assert.assertTrue(resp.getId().equals(n1.getId()));
Assert.assertTrue(resp.getObjectSettings().getProtectionType().equals(sProtectionType));
// 4. get protection type
String rProtectionType = _internalVarrayClient.getProtectionType(n1.getId());
Assert.assertTrue(resp != null);
Assert.assertTrue(rProtectionType.equals(sProtectionType));
// 4.a get protectoin type from an not existed varray
try {
URI tmpvarryId = URI.create(String.format("urn:storageos:VirtualArray:%1$s:%2$s", UUID.randomUUID().toString(), "vdc1"));
rProtectionType = _internalVarrayClient.getProtectionType(tmpvarryId);
} catch (APIException e) {
Assert.assertEquals(ServiceCode.API_URL_ENTITY_NOT_FOUND, e.getServiceCode());
}
// 5. unset protection type
ClientResponse unsetResp = _internalVarrayClient.unsetProtectionType(n1.getId());
Assert.assertTrue(unsetResp != null);
Assert.assertTrue(unsetResp.getStatus() == 200);
// 6. get protection type after unset
rProtectionType = _internalVarrayClient.getProtectionType(n1.getId());
Assert.assertTrue(resp != null);
Assert.assertTrue(rProtectionType.isEmpty());
// 7. set registered status to true
Boolean bDeviceRegistered = true;
VirtualArrayRestRep resp2 = _internalVarrayClient.setDeviceRegistered(n1.getId(), bDeviceRegistered);
Assert.assertTrue(resp2 != null);
Assert.assertTrue(resp2.getId().equals(n1.getId()));
Assert.assertTrue(resp2.getObjectSettings().getDeviceRegistered().equals(bDeviceRegistered));
// 8. get registered status
Boolean rDeviceRegistered = _internalVarrayClient.getDeviceRegistered(n1.getId());
Assert.assertTrue(resp != null);
Assert.assertTrue(bDeviceRegistered == rDeviceRegistered);
// 9. try to delete nh1
ClientResponse deleteResp = rSys.path("/vdc/varrays/" + n1.getId().toString() + "/deactivate").post(ClientResponse.class);
Assert.assertTrue(deleteResp != null);
Assert.assertTrue(deleteResp.getStatus() == 400);
// 9. set registered status to false
bDeviceRegistered = false;
VirtualArrayRestRep resp3 = _internalVarrayClient.setDeviceRegistered(n1.getId(), bDeviceRegistered);
Assert.assertTrue(resp3 != null);
Assert.assertTrue(resp3.getId().equals(n1.getId()));
Assert.assertTrue(resp3.getObjectSettings().getDeviceRegistered().equals(bDeviceRegistered));
// 10. delete nh1
deleteResp = rSys.path("/vdc/varrays/" + n1.getId().toString() + "/deactivate").post(ClientResponse.class);
Assert.assertTrue(deleteResp != null);
Assert.assertTrue(deleteResp.getStatus() == 200);
}
use of com.emc.storageos.svcs.errorhandling.resources.APIException in project coprhd-controller by CoprHD.
the class FileService method createContinuousCopies.
/**
* Create Continuous Copies
*
* @param id
* the URN of a ViPR fileSystem
* @param param
* File Replication Create parameter
* @brief Define continuous copies
* @return TaskResponse
* @throws InternalException
* @throws APIException
*/
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{id}/protection/continuous-copies/create")
@CheckPermission(roles = { Role.TENANT_ADMIN }, acls = { ACL.OWN, ACL.ALL })
public TaskResourceRep createContinuousCopies(@PathParam("id") URI id, FileReplicationCreateParam param) throws InternalException, APIException {
_log.info("Request to create replication copies for filesystem {}", id);
// Validate the FS id.
ArgValidator.checkFieldUriType(id, FileShare.class, "id");
FileShare fs = queryResource(id);
FileShare orgFs = queryResource(id);
String task = UUID.randomUUID().toString();
ArgValidator.checkEntity(fs, id, isIdEmbeddedInURL(id));
TaskList taskList = new TaskList();
// Make sure that we don't have some pending
// operation against the file system!!!
checkForPendingTasks(Arrays.asList(fs.getTenant().getURI()), Arrays.asList(fs));
// Get the project.
URI projectURI = fs.getProject().getURI();
Project project = _permissionsHelper.getObjectById(projectURI, Project.class);
ArgValidator.checkEntity(project, projectURI, false);
_log.info("Found filesystem project {}", projectURI);
VirtualPool currentVpool = _dbClient.queryObject(VirtualPool.class, fs.getVirtualPool());
StringBuffer notSuppReasonBuff = new StringBuffer();
// Verify the file system and its vPool are capable of doing replication!!!
if (!FileSystemReplicationUtils.isSupportedFileReplicationCreate(fs, currentVpool, notSuppReasonBuff)) {
_log.error("create mirror copies is not supported for file system {} due to {}", fs.getId().toString(), notSuppReasonBuff.toString());
throw APIException.badRequests.unableToCreateMirrorCopies(fs.getId(), notSuppReasonBuff.toString());
}
// Get the virtual array!!!
VirtualArray varray = _dbClient.queryObject(VirtualArray.class, fs.getVirtualArray());
// New operation
Operation op = new Operation();
op.setResourceType(ResourceOperationTypeEnum.CREATE_FILE_SYSTEM_MIRROR_COPIES);
op.setDescription("Create file system mirror operation");
op = _dbClient.createTaskOpStatus(FileShare.class, fs.getId(), task, op);
TaskResourceRep fileSystemTask = toTask(fs, task, op);
taskList.getTaskList().add(fileSystemTask);
StorageSystem device = _dbClient.queryObject(StorageSystem.class, fs.getStorageDevice());
// prepare vpool capability values
VirtualPoolCapabilityValuesWrapper capabilities = new VirtualPoolCapabilityValuesWrapper();
capabilities.put(VirtualPoolCapabilityValuesWrapper.SIZE, fs.getCapacity());
capabilities.put(VirtualPoolCapabilityValuesWrapper.RESOURCE_COUNT, new Integer(1));
if (VirtualPool.ProvisioningType.Thin.toString().equalsIgnoreCase(currentVpool.getSupportedProvisioningType())) {
capabilities.put(VirtualPoolCapabilityValuesWrapper.THIN_PROVISIONING, Boolean.TRUE);
}
// Set the source file system details
// source fs details used in finding recommendations for target fs!!
capabilities.put(VirtualPoolCapabilityValuesWrapper.FILE_SYSTEM_CREATE_MIRROR_COPY, Boolean.TRUE);
capabilities.put(VirtualPoolCapabilityValuesWrapper.EXISTING_SOURCE_FILE_SYSTEM, fs);
capabilities.put(VirtualPoolCapabilityValuesWrapper.SOURCE_STORAGE_SYSTEM, device);
StringBuilder errorMsg = new StringBuilder();
if (!FilePolicyServiceUtils.updatePolicyCapabilities(_dbClient, varray, currentVpool, project, null, capabilities, errorMsg)) {
_log.error("File system can not be created, ", errorMsg.toString());
throw APIException.badRequests.unableToProcessRequest(errorMsg.toString());
}
if (param.getCopyName() != null && !param.getCopyName().isEmpty()) {
// No need to generate any name -- Since the requirement is to use the customizing label we should use the
// same.
// Stripping out the special characters like ; /-+!@#$%^&())";:[]{}\ | but allow underscore character _
String convertedName = param.getCopyName().replaceAll("[^\\dA-Za-z\\_]", "");
_log.info("Original copy name {} and converted copy name {}", param.getCopyName(), convertedName);
capabilities.put(VirtualPoolCapabilityValuesWrapper.FILE_TARGET_COPY_NAME, convertedName);
}
FileServiceApi fileServiceApi = getFileShareServiceImpl(capabilities, _dbClient);
try {
// Call out placementManager to get the recommendation for placement.
List recommendations = _filePlacementManager.getRecommendationsForFileCreateRequest(varray, project, currentVpool, capabilities);
// Verify the source virtual pool recommendations meets source fs storage!!!
fileServiceApi.createTargetsForExistingSource(fs, project, currentVpool, varray, taskList, task, recommendations, capabilities);
} catch (BadRequestException e) {
// Revert the file system to original state!!!
restoreFromOriginalFs(orgFs, fs);
_dbClient.updateObject(fs);
op = _dbClient.error(FileShare.class, fs.getId(), task, e);
_log.error("Create file system mirror copy failed {}, {}", e.getMessage(), e);
throw e;
} catch (InternalException e) {
// Revert the file system to original state!!!
restoreFromOriginalFs(orgFs, fs);
_dbClient.updateObject(fs);
op = _dbClient.error(FileShare.class, fs.getId(), task, e);
_log.error("Create file system mirror copy failed {}, {}", e.getMessage(), e);
throw e;
} catch (Exception e) {
_log.error("Create file system mirror copy failed {}, {}", e.getMessage(), e);
throw APIException.badRequests.unableToProcessRequest(e.getMessage());
}
auditOp(OperationTypeEnum.CREATE_MIRROR_FILE_SYSTEM, true, AuditLogManager.AUDITOP_BEGIN, fs.getLabel(), currentVpool.getLabel(), fs.getLabel(), project == null ? null : project.getId().toString());
return taskList.getTaskList().get(0);
}
use of com.emc.storageos.svcs.errorhandling.resources.APIException in project coprhd-controller by CoprHD.
the class FileService method snapshot.
/**
* Create file system snapshot
* <p>
* NOTE: This is an asynchronous operation.
*
* @param id
* the URN of a ViPR File system
* @param param
* file system snapshot parameters
* @brief Create file system snapshot
* @return Task resource representation
* @throws InternalException
*/
@POST
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{id}/protection/snapshots")
@CheckPermission(roles = { Role.TENANT_ADMIN }, acls = { ACL.ANY })
public TaskResourceRep snapshot(@PathParam("id") URI id, FileSystemSnapshotParam param) throws InternalException {
ArgValidator.checkFieldUriType(id, FileShare.class, "id");
FileShare fs = queryResource(id);
ArgValidator.checkEntity(fs, id, isIdEmbeddedInURL(id));
StorageSystem device = _dbClient.queryObject(StorageSystem.class, fs.getStorageDevice());
VirtualPool vpool = _dbClient.queryObject(VirtualPool.class, fs.getVirtualPool());
if (vpool == null) {
throw APIException.badRequests.invalidParameterFileSystemHasNoVirtualPool(id);
}
if (getNumSnapshots(fs) >= vpool.getMaxNativeSnapshots()) {
throw APIException.methodNotAllowed.maximumNumberSnapshotsReached();
}
String label = TimeUtils.formatDateForCurrent(param.getLabel());
// check duplicate fileshare snapshot names for this fileshare
checkForDuplicateName(label, Snapshot.class, id, "parent", _dbClient);
Snapshot snap = new Snapshot();
snap.setId(URIUtil.createId(Snapshot.class));
snap.setParent(new NamedURI(id, label));
snap.setLabel(label);
snap.setOpStatus(new OpStatusMap());
snap.setProject(new NamedURI(fs.getProject().getURI(), label));
String convertedName = label.replaceAll("[^\\dA-Za-z_]", "");
_log.info("Original name {} and converted name {}", label, convertedName);
snap.setName(convertedName);
fs.setOpStatus(new OpStatusMap());
Operation op = new Operation();
op.setResourceType(ResourceOperationTypeEnum.CREATE_FILE_SYSTEM_SNAPSHOT);
String task = UUID.randomUUID().toString();
snap.getOpStatus().createTaskStatus(task, op);
fs.getOpStatus().createTaskStatus(task, op);
_dbClient.createObject(snap);
_dbClient.persistObject(fs);
// find storageport for fs and based on protocol
if (null == fs.getStoragePort()) {
StoragePort storagePort;
try {
// assigned storageport to fs
storagePort = _fileScheduler.placeFileShareExport(fs, PROTOCOL_NFS, null);
_log.info("FS is not mounted so we are mounting the FS first and then creating the Snapshot and the returned storage port- {} and supported protocol-{}", storagePort.getPortName(), PROTOCOL_NFS);
} catch (APIException e) {
// if we don't find port for NFS protocol then
// in catch exception we get port for CIFS protocol
storagePort = _fileScheduler.placeFileShareExport(fs, PROTOCOL_CIFS, null);
_log.info("FS is not mounted so we are mounting the FS first and then creating the Snapshot and the returned storage port- {} and supported protocol-{}", storagePort.getPortName(), PROTOCOL_NFS);
}
}
// send request to controller
try {
FileServiceApi fileServiceApi = getFileShareServiceImpl(fs, _dbClient);
fileServiceApi.snapshotFS(device.getId(), snap.getId(), fs.getId(), task);
} catch (InternalException e) {
snap.setInactive(true);
_dbClient.persistObject(snap);
// should discriminate between validation problems vs. internal errors
throw e;
}
auditOp(OperationTypeEnum.CREATE_FILE_SYSTEM_SNAPSHOT, true, AuditLogManager.AUDITOP_BEGIN, snap.getLabel(), snap.getId().toString(), fs.getId().toString());
fs = _dbClient.queryObject(FileShare.class, id);
_log.debug("Before sending response, FS ID : {}, Taks : {} ; Status {}", fs.getOpStatus().get(task), fs.getOpStatus().get(task).getStatus());
return toTask(snap, task, op);
}
use of com.emc.storageos.svcs.errorhandling.resources.APIException in project coprhd-controller by CoprHD.
the class DisasterRecoveryService method resumePrecheck.
/**
* This is internal API to do precheck for resume
*/
@POST
@Path("/internal/resumeprecheck")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public SiteErrorResponse resumePrecheck() {
log.info("Precheck for resume internally");
SiteErrorResponse response = new SiteErrorResponse();
try {
precheckForResumeLocalStandby();
} catch (APIException e) {
log.warn("Failed to precheck switchover", e);
response.setErrorMessage(e.getMessage());
response.setServiceCode(e.getServiceCode().ordinal());
return response;
} catch (Exception e) {
log.error("Failed to precheck switchover", e);
response.setErrorMessage(e.getMessage());
return response;
}
return response;
}
Aggregations