/** * Return non secured parameters values related to the subscription.The attached project is validated against the * current user to check it is visible. Secured parameters (even the encrypted ones) are not returned. The * visibility of this subscription is checked. * * @param id * The subscription identifier. * @return secured associated parameters values. Key of returned map is the identifier of * {@link org.ligoj.app.model.Parameter} */ @GET @Path("{id:\\d+}") @org.springframework.transaction.annotation.Transactional(readOnly = true) public Map<String, String> getNonSecuredParameters(@PathParam("id") final int id) { return parameterValueResource.getNonSecuredSubscriptionParameters(checkVisible(id).getId()); }
/** * Build and return the trigger identifier from the schedule and the * subscription. * * @param schedule * The schedule entity. * @return the {@link String} identifier for the trigger. */ protected static String format(final VmSchedule schedule) { return schedule.getId() + "-" + schedule.getSubscription().getId(); }
/** * Return members of given subscription. */ private Set<UserOrg> getMembersOfSubscription(final Subscription subscription) { final Set<UserOrg> users = new HashSet<>(); final ServicePlugin plugin = servicePluginLocator.getResource(subscription.getNode().getId()); if (plugin instanceof LdapPluginResource) { users.addAll(((LdapPluginResource) plugin).getMembers(subscription.getId())); } return users; }
/** * Write <code>subscription;project;projetKey;projectName;node</code>. * * @param writer * Target output. * @param subscription * Related subscription. */ private void writeCommon(final Writer writer, final Subscription subscription) throws IOException { final Project project = subscription.getProject(); writer.write('\n'); writer.write(String.valueOf(subscription.getId())); writer.write(';'); writer.write(String.valueOf(project.getId())); writer.write(';'); writer.write(project.getPkey()); writer.write(';'); writer.write(project.getName().replaceAll("\"", "'")); writer.write(';'); writer.write(subscription.getNode().getId()); }
/** * Get a file reference for a specific subscription. This file will use the subscription as a context to isolate it, * and using the related node and the subscription's identifier. The parent directories are created as needed. * * @param subscription * The subscription used a context of the file to create. * @param fragments * The file fragments. * @return The {@link Path} reference. * @throws IOException * When the parent directories creation failed. * @since 2.2.4 */ public Path toPath(final Subscription subscription, final String... fragments) throws IOException { return toPath(toPath(subscription.getNode()).resolve(String.valueOf(subscription.getId())), fragments); }
/** * Delete entity. Should be protected with RBAC. * * @param id * The entity identifier. * @throws Exception * When the delete fails. Managed at JAX-RS level. */ @DELETE @Path("{id:\\d+}") public void delete(@PathParam("id") final int id) throws Exception { final Project project = findOneVisible(repository::findOneVisible, id, Function.identity()); for (final Subscription subscription : project.getSubscriptions()) { subscriptionResource.delete(subscription.getId()); } repository.delete(project); }
/** * Check the given schedule exists and is related to given subscription. * * @param subscription * The subscription holder. * @param schedule * The target schedule identifier. * @return The resolved schedule when found and owned by the subscription. */ private VmSchedule checkOwnership(final int subscription, final int schedule) { final VmSchedule entity = repository.findOneExpected(schedule); if (entity.getSubscription().getId().intValue() != subscription) { throw new EntityNotFoundException(String.valueOf(schedule)); } return entity; } }
/** * Return all configured schedules report of all VM related to a a visible subscription related to the given node. * * @param node * The related node. * @param file * The requested file name. * @return The download stream. */ @GET @Produces(MediaType.APPLICATION_OCTET_STREAM) @Path(VmResource.SERVICE_URL + "/{node:service:.+}/{file:schedules-.*.csv}") public Response downloadNodeSchedulesReport(@PathParam("node") final String node, @PathParam("file") final String file) { // Get all visible schedules linked to this node final List<VmSchedule> schedules = vmScheduleRepository.findAllByNode(node, securityHelper.getLogin()); // Get all last execution related to given node, Key is the subscription identifier final Map<Integer, VmExecution> lastExecutions = vmExecutionRepository.findAllByNodeLast(node).stream() .collect(Collectors.toMap(e -> e.getSubscription().getId(), Function.identity())); // Get all last executions of all schedules return AbstractToolPluginResource.download(o -> writeSchedules(o, schedules, lastExecutions), file).build(); }
/** * Save as needed the given schedule. * * @param execution * The execution to persist. * @param operation * The original operation to execute. */ private void saveAndFlush(final VmExecution execution, final VmOperation operation) { // Check this execution has been really been executed if (execution.getOperation() == null) { log.info("Operation {} on subscription {} : skipped", operation, execution.getSubscription().getId()); } else { // Persist the execution result vmExecutionRepository.saveAndFlush(execution); } } }
/** * Execute the given execution. The current execution context can be completed : VM identifier or "statusText". * * @param execution * The current execution. Not this execution ay be updated by the implementor, and real proceeded * operation can be altered. When real operation is set to <code>null</code>, the execution is considered * as skipped. * @throws Exception * Any exception while executing the operation. * @see #execute(int, VmOperation) * @since 1.3.1 */ default void execute(final VmExecution execution) throws Exception { execute(execution.getSubscription().getId(), execution.getOperation()); } }
/** * Check status for a subscription. * * @param subscription * Subscription entity. * @param parameters * Parameters of a subscription. * @return status of given subscription. */ public SubscriptionStatusWithData checkSubscriptionStatus(final Subscription subscription, final Map<String, String> parameters) { final String node = subscription.getNode().getId(); try { log.info("Check status of a subscription attached to {}...", node); // Find the plug-in associated to the requested node final ToolPlugin toolPlugin = locator.getResourceExpected(node, ToolPlugin.class); // Call service which check status final SubscriptionStatusWithData status = toolPlugin.checkSubscriptionStatus(subscription.getId(), node, parameters); status.setNode(node); log.info("Check status of a subscription attached to {} succeed", node); return status; } catch (final Exception e) { // NOSONAR // Do not pollute logs with this failures // Service is down when an exception is thrown, log the error // without trace log.warn("Check status of a subscription attached to {} failed : {}", node, e.getMessage()); } return new SubscriptionStatusWithData(false); }
/** * Create the given subscription parameter values. Value validity is checked. * * @param values * the parameter values to persist. * @param subscription * The related subscription. */ public void create(final List<ParameterValueCreateVo> values, final Subscription subscription) { create(values, v -> v.setSubscription(subscription)); cacheManager.getCache("subscription-parameters").evict(subscription.getId()); }
/** * Refresh given subscriptions and return their status. */ private SubscriptionStatusWithData refreshSubscription(final Subscription subscription) { final Map<String, String> parameters = getParameters(subscription.getId()); final SubscriptionStatusWithData statusWithData = nodeResource.checkSubscriptionStatus(subscription, parameters); statusWithData.setId(subscription.getId()); statusWithData.setProject(subscription.getProject().getId()); statusWithData.setParameters(parameterValueResource.getNonSecuredSubscriptionParameters(subscription.getId())); // Update the last event with fresh data eventResource.registerEvent(subscription, EventType.STATUS, statusWithData.getStatus().name()); // Return the fresh statuses return statusWithData; }
@Override protected void executeInternal(final JobExecutionContext arg0) { // Extract the job data to execute the operation final int schedule = arg0.getMergedJobDataMap().getInt("schedule"); final ApplicationContext context = ObjectUtils.defaultIfNull((ApplicationContext) arg0.getMergedJobDataMap().get("context"), SpringUtils.getApplicationContext()); final VmSchedule entity = context.getBean(VmScheduleRepository.class).findOneExpected(schedule); log.info("Executing {} for schedule {}, subscription {}", entity.getOperation(), entity.getId(), entity.getSubscription().getId()); // Set the user context.getBean(SecurityHelper.class).setUserName(SecurityHelper.SYSTEM_USERNAME); // Execute the operation context.getBean(VmExecutionResource.class).execute(entity.getSubscription(), entity.getOperation()); log.info("Succeed {} for schedule {}, subscription {}", entity.getOperation(), entity.getId(), entity.getSubscription().getId()); }
/** * Delegates the creation to the hierarchy of the related plug-in, and starting from the related plug-in. <br> * Exception appearing there causes to roll-back the previous persists. * * @throws Exception * When the link/create fails. Managed at upper level. */ private void delegateToPlugin(final SubscriptionEditionVo vo, final Subscription entity) throws Exception { for (ServicePlugin p = locator.getResource(vo.getNode()); p != null; p = locator .getResource(locator.getParent(p.getKey()))) { if (vo.getMode() == SubscriptionMode.CREATE) { // Create mode p.create(entity.getId()); } else { // Link mode p.link(entity.getId()); } } }
/** * Persist the trigger in the Quartz scheduler. */ private VmSchedule persistTrigger(final VmSchedule schedule) throws SchedulerException { // The trigger for the common VM Job will the following convention : // schedule.id-subscription.id final String id = VmJob.format(schedule); final JobDetailImpl object = (JobDetailImpl) vmJobDetailFactoryBean.getObject(); object.getJobDataMap().put("vmServicePlugin", this); final Trigger trigger = TriggerBuilder.newTrigger().withIdentity(id, SCHEDULE_TRIGGER_GROUP) .withSchedule(CronScheduleBuilder.cronSchedule(schedule.getCron()) .inTimeZone(DateUtils.getApplicationTimeZone())) .forJob(object).usingJobData("subscription", schedule.getSubscription().getId()) .usingJobData("operation", schedule.getOperation().name()).usingJobData("schedule", schedule.getId()) .build(); // Add this trigger vmSchedulerFactoryBean.getObject().scheduleJob(trigger); return schedule; }
/** * Check the visibility of a configured entity. * * @param configured * The requested configured entity. * @param <K> * The {@link Configurable} identifier type. * @param <T> * The {@link Configurable} type. * @return The formal entity parameter. */ protected <K extends Serializable, T extends Configurable<C, K>> T checkConfiguredVisibility(final T configured) { final Subscription entity = subscriptionRepository .findOneExpected(configured.getConfiguration().getSubscription().getId()); if (projectRepository.findOneVisible(entity.getProject().getId(), securityHelper.getLogin()) == null) { // Associated project is not visible, reject the configuration access throw new EntityNotFoundException(configured.getId().toString()); } return configured; }
@Override public boolean isFinished(final VmSnapshotStatus task) { // Complete the status for the not completed tasks if (task.isFailed()) { task.setFinishedRemote(true); } else if (!task.isFinishedRemote()) { getSnapshot(subscriptionResource.checkVisible(task.getLocked().getId()).getNode()) .completeStatus(task); } return task.isFinishedRemote(); }
private boolean completeStatus(final VmExecutionStatus task) { if (task.isFailed()) { task.setFinishedRemote(true); } if (!task.isFinishedRemote() && task.isFinished()) { // Complete the status for the uncompleted tasks final int subscription = task.getLocked().getId(); final String node = task.getLocked().getNode().getId(); try { final Vm vm = getTool(node).getVmDetails(subscriptionResource.getParametersNoCheck(subscription)); task.setVm(vm); task.setFinishedRemote(!vm.isBusy()); return true; } catch (final Exception e) { // Unable to get the VM details log.info("Unable to retrive VM information of subscription {}, node {}", subscription, node); } } return false; }
/** * {@link Event} JPA to VO object transformer without refined information. * * @param entity * Source entity. * @return The corresponding VO object with node/subscription reference. */ public static EventVo toVo(final Event entity) { final EventVo vo = new EventVo(); vo.setValue(entity.getValue()); vo.setType(entity.getType()); if (entity.getNode() == null) { vo.setSubscription(entity.getSubscription().getId()); vo.setNode(NodeResource.toVoLight(entity.getSubscription().getNode())); } else { vo.setNode(NodeResource.toVoLight(entity.getNode())); } return vo; }