@Override public ResponseEntity<MgmtAction> getAction(@PathVariable("targetId") final String targetId, @PathVariable("actionId") final Long actionId) { final Action action = deploymentManagement.findAction(actionId) .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); if (!action.getTarget().getControllerId().equals(targetId)) { LOG.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), targetId); return ResponseEntity.notFound().build(); } return ResponseEntity.ok(MgmtTargetMapper.toResponseWithLinks(targetId, action)); }
/** * If the action has a maintenance schedule defined but is no longer valid, * cancel the action. * * @param action * is the {@link Action} to check. */ private void checkAndCancelExpiredAction(final Action action) { if (action != null && action.hasMaintenanceSchedule() && action.isMaintenanceScheduleLapsed()) { try { controllerManagement.cancelAction(action.getId()); } catch (final CancelActionNotAllowedException e) { LOG.info("Cancel action not allowed exception :{}", e); } } }
/** * If the action has a maintenance schedule defined but is no longer valid, * cancel the action. * * @param action * is the {@link Action} to check. */ private void checkAndCancelExpiredAction(final Action action) { if (action != null && action.hasMaintenanceSchedule() && action.isMaintenanceScheduleLapsed()) { try { controllerManagement.cancelAction(action.getId()); } catch (final CancelActionNotAllowedException e) { LOG.info("Cancel action not allowed exception :{}", e); } } }
@Override public ResponseEntity<DdiCancel> getControllerCancelAction(@PathVariable("tenant") final String tenant, @PathVariable("controllerId") @NotEmpty final String controllerId, @PathVariable("actionId") @NotEmpty final Long actionId) { LOG.debug("getControllerCancelAction({})", controllerId); final Target target = controllerManagement.getByControllerId(controllerId) .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId)); final Action action = findActionWithExceptionIfNotFound(actionId); if (!action.getTarget().getId().equals(target.getId())) { LOG.warn(GIVEN_ACTION_IS_NOT_ASSIGNED_TO_GIVEN_TARGET, action.getId(), target.getId()); return ResponseEntity.notFound().build(); } if (action.isCancelingOrCanceled()) { final DdiCancel cancel = new DdiCancel(String.valueOf(action.getId()), new DdiCancelActionToStop(String.valueOf(action.getId()))); LOG.debug("Found an active CancelAction for target {}. returning cancel: {}", controllerId, cancel); controllerManagement.registerRetrieved(action.getId(), RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target retrieved cancel action and should start now the cancelation."); return new ResponseEntity<>(cancel, HttpStatus.OK); } return ResponseEntity.notFound().build(); }
@Override public ResponseEntity<DdiControllerBase> getControllerBase(@PathVariable("tenant") final String tenant, @PathVariable("controllerId") final String controllerId) { LOG.debug("getControllerBase({})", controllerId); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotexist(controllerId, IpUtil .getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties)); final Action action = controllerManagement.findOldestActiveActionByTarget(controllerId).orElse(null); checkAndCancelExpiredAction(action); return new ResponseEntity<>( DataConversionHelper.fromTarget(target, action, action == null ? controllerManagement.getPollingTime() : controllerManagement.getPollingTimeForAction(action.getId()), tenantAware), HttpStatus.OK); }
@Override public ResponseEntity<DdiControllerBase> getControllerBase(@PathVariable("tenant") final String tenant, @PathVariable("controllerId") final String controllerId) { LOG.debug("getControllerBase({})", controllerId); final Target target = controllerManagement.findOrRegisterTargetIfItDoesNotexist(controllerId, IpUtil .getClientIpFromRequest(requestResponseContextHolder.getHttpServletRequest(), securityProperties)); final Action action = controllerManagement.findOldestActiveActionByTarget(controllerId).orElse(null); checkAndCancelExpiredAction(action); return new ResponseEntity<>( DataConversionHelper.fromTarget(target, action, action == null ? controllerManagement.getPollingTime() : controllerManagement.getPollingTimeForAction(action.getId()), tenantAware), HttpStatus.OK); }
@Override public ResponseEntity<MgmtAction> updateAction(@PathVariable("targetId") final String targetId, @PathVariable("actionId") final Long actionId, @RequestBody final MgmtActionRequestBodyPut actionUpdate) { Action action = deploymentManagement.findAction(actionId) .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); if (!action.getTarget().getControllerId().equals(targetId)) { LOG.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), targetId); return ResponseEntity.notFound().build(); } if (!MgmtActionType.FORCED.equals(actionUpdate.getForceType())) { throw new ValidationException("Resource supports only switch to FORCED."); } action = deploymentManagement.forceTargetAction(actionId); return ResponseEntity.ok(MgmtTargetMapper.toResponseWithLinks(targetId, action)); }
private ActionStatus checkAndLogDownload(final HttpServletRequest request, final Target target, final Long module) { final Action action = controllerManagement .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module) .orElseThrow(() -> new SoftwareModuleNotAssignedToTargetException(module, target.getControllerId())); final String range = request.getHeader("Range"); String message; if (range != null) { message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range + " of: " + request.getRequestURI(); } else { message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads " + request.getRequestURI(); } return controllerManagement.addInformationalActionStatus( entityFactory.actionStatus().create(action.getId()).status(Status.DOWNLOAD).message(message)); }
private ActionStatus checkAndLogDownload(final HttpServletRequest request, final Target target, final Long module) { final Action action = controllerManagement .getActionForDownloadByTargetAndSoftwareModule(target.getControllerId(), module) .orElseThrow(() -> new SoftwareModuleNotAssignedToTargetException(module, target.getControllerId())); final String range = request.getHeader("Range"); String message; if (range != null) { message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads range " + range + " of: " + request.getRequestURI(); } else { message = RepositoryConstants.SERVER_MESSAGE_PREFIX + "Target downloads " + request.getRequestURI(); } return controllerManagement.addInformationalActionStatus( entityFactory.actionStatus().create(action.getId()).status(Status.DOWNLOAD).message(message)); }
private void lookIfUpdateAvailable(final Target target) { final Optional<Action> actionOptional = controllerManagement .findOldestActiveActionByTarget(target.getControllerId()); if (!actionOptional.isPresent()) { return; } final Action action = actionOptional.get(); if (action.isCancelingOrCanceled()) { amqpMessageDispatcherService.sendCancelMessageToTarget(target.getTenant(), target.getControllerId(), action.getId(), target.getAddress()); return; } final Map<SoftwareModule, List<SoftwareModuleMetadata>> modules = Maps .newHashMapWithExpectedSize(action.getDistributionSet().getModules().size()); final Map<Long, List<SoftwareModuleMetadata>> metadata = controllerManagement .findTargetVisibleMetaDataBySoftwareModuleId(action.getDistributionSet().getModules().stream() .map(SoftwareModule::getId).collect(Collectors.toList())); action.getDistributionSet().getModules().forEach(module -> modules.put(module, metadata.get(module.getId()))); amqpMessageDispatcherService.sendUpdateMessageToTarget(action.getTenant(), action.getTarget(), action.getId(), modules, action.isMaintenanceWindowAvailable()); }
private Action sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Collection<String> msgs) { return controllerManagament.addUpdateActionStatus( entityFactory.actionStatus().create(updActA.getId()).status(status).messages(msgs)); }
@Override public ResponseEntity<PagedList<MgmtActionStatus>> getActionStatusList( @PathVariable("targetId") final String targetId, @PathVariable("actionId") final Long actionId, @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_OFFSET, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_OFFSET) final int pagingOffsetParam, @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_PAGING_LIMIT, defaultValue = MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT) final int pagingLimitParam, @RequestParam(value = MgmtRestConstants.REQUEST_PARAMETER_SORTING, required = false) final String sortParam) { final Target target = findTargetWithExceptionIfNotFound(targetId); final Action action = deploymentManagement.findAction(actionId) .orElseThrow(() -> new EntityNotFoundException(Action.class, actionId)); if (!action.getTarget().getId().equals(target.getId())) { LOG.warn(ACTION_TARGET_MISSING_ASSIGN_WARN, action.getId(), target.getId()); return ResponseEntity.notFound().build(); } final int sanitizedOffsetParam = PagingUtility.sanitizeOffsetParam(pagingOffsetParam); final int sanitizedLimitParam = PagingUtility.sanitizePageLimitParam(pagingLimitParam); final Sort sorting = PagingUtility.sanitizeActionStatusSortParam(sortParam); final Page<ActionStatus> statusList = this.deploymentManagement.findActionStatusByAction( new OffsetBasedPageRequest(sanitizedOffsetParam, sanitizedLimitParam, sorting), action.getId()); return ResponseEntity.ok(new PagedList<>( MgmtTargetMapper.toActionStatusRestResponse(statusList.getContent(), deploymentManagement), statusList.getTotalElements())); }
@Override public ResponseEntity<Void> postCancelActionFeedback(@Valid @RequestBody final DdiActionFeedback feedback, @PathVariable("tenant") final String tenant, @PathVariable("controllerId") @NotEmpty final String controllerId, @PathVariable("actionId") @NotEmpty final Long actionId) { LOG.debug("provideCancelActionFeedback for target [{}]: {}", controllerId, feedback); final Target target = controllerManagement.getByControllerId(controllerId) .orElseThrow(() -> new EntityNotFoundException(Target.class, controllerId)); if (!actionId.equals(feedback.getId())) { LOG.warn( "provideBasedeploymentActionFeedback: action in payload ({}) was not identical to action in path ({}).", feedback.getId(), actionId); return ResponseEntity.notFound().build(); } final Action action = findActionWithExceptionIfNotFound(actionId); if (!action.getTarget().getId().equals(target.getId())) { LOG.warn(GIVEN_ACTION_IS_NOT_ASSIGNED_TO_GIVEN_TARGET, action.getId(), target.getId()); return ResponseEntity.notFound().build(); } controllerManagement .addCancelActionStatus(generateActionCancelStatus(feedback, target, feedback.getId(), entityFactory)); return ResponseEntity.ok().build(); }
private Action sendUpdateActionStatusToTarget(final Status status, final Action updActA, final Collection<String> msgs) { return controllerManagament.addUpdateActionStatus( entityFactory.actionStatus().create(updActA.getId()).status(status).messages(msgs)); }
protected Action prepareFinishedUpdate(final String controllerId, final String distributionSet, final boolean isRequiredMigrationStep) { final DistributionSet ds = testdataFactory.createDistributionSet(distributionSet, isRequiredMigrationStep); Target savedTarget = testdataFactory.createTarget(controllerId); savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator() .next(); Action savedAction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId()) .getContent().get(0); savedAction = controllerManagement.addUpdateActionStatus( entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.RUNNING)); return controllerManagement.addUpdateActionStatus( entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.FINISHED)); }
protected Action prepareFinishedUpdate(final String controllerId, final String distributionSet, final boolean isRequiredMigrationStep) { final DistributionSet ds = testdataFactory.createDistributionSet(distributionSet, isRequiredMigrationStep); Target savedTarget = testdataFactory.createTarget(controllerId); savedTarget = assignDistributionSet(ds.getId(), savedTarget.getControllerId()).getAssignedEntity().iterator() .next(); Action savedAction = deploymentManagement.findActiveActionsByTarget(PAGE, savedTarget.getControllerId()) .getContent().get(0); savedAction = controllerManagement.addUpdateActionStatus( entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.RUNNING)); return controllerManagement.addUpdateActionStatus( entityFactory.actionStatus().create(savedAction.getId()).status(Action.Status.FINISHED)); }
static MgmtAction toResponseWithLinks(final String controllerId, final Action action) { final MgmtAction result = toResponse(controllerId, action); if (action.isCancelingOrCanceled()) { result.add(linkTo(methodOn(MgmtTargetRestApi.class).getAction(controllerId, action.getId())) .withRel(MgmtRestConstants.TARGET_V1_CANCELED_ACTION)); } result.add(linkTo( methodOn(MgmtDistributionSetRestApi.class).getDistributionSet(action.getDistributionSet().getId())) .withRel("distributionset")); result.add(linkTo(methodOn(MgmtTargetRestApi.class).getActionStatusList(controllerId, action.getId(), 0, MgmtRestConstants.REQUEST_PARAMETER_PAGING_DEFAULT_LIMIT_VALUE, ActionStatusFields.ID.getFieldName() + ":" + SortDirection.DESC)) .withRel(MgmtRestConstants.TARGET_V1_ACTION_STATUS)); return result; }
private void feedbackToByInSync(final DistributionSet savedSet) { final Action action = deploymentManagement.findActionsByDistributionSet(PAGE, savedSet.getId()).getContent() .get(0); controllerManagement .addUpdateActionStatus(entityFactory.actionStatus().create(action.getId()).status(Status.FINISHED)); }
@Test @Description("Cancels an active action, only active actions can be deleted. Required Permission: UPDATE_TARGET.") public void deleteActionFromTarget() throws Exception { final Action actions = generateActionForTarget(targetId, false); mockMvc.perform(delete(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/{targetId}/" + MgmtRestConstants.TARGET_V1_ACTIONS + "/{actionId}", targetId, actions.getId())) .andExpect(status().isNoContent()).andDo(MockMvcResultPrinter.print()) .andDo(this.document.document( pathParameters(parameterWithName("targetId").description(ApiModelPropertiesGeneric.ITEM_ID), parameterWithName("actionId").description(ApiModelPropertiesGeneric.ITEM_ID)))); }
@Test @Description("Handles the GET request of retrieving all targets within SP based by parameter. Required Permission: READ_TARGET.") public void getStatusFromActionWithParameters() throws Exception { final Action action = generateActionForTarget(targetId); mockMvc.perform(get(MgmtRestConstants.TARGET_V1_REQUEST_MAPPING + "/" + targetId + "/" + MgmtRestConstants.TARGET_V1_ACTIONS + "/" + action.getId() + "/" + MgmtRestConstants.TARGET_V1_ACTION_STATUS + "?limit=10&sort=id:ASC&offset=0")) .andExpect(status().isOk()).andDo(MockMvcResultPrinter.print()) .andDo(this.document.document( requestParameters(parameterWithName("limit").description(ApiModelPropertiesGeneric.LIMIT), parameterWithName("sort").description(ApiModelPropertiesGeneric.SORT), parameterWithName("offset").description(ApiModelPropertiesGeneric.OFFSET)))); }