Search in sources :

Example 21 with Subscription

use of org.ligoj.app.model.Subscription in project plugin-vm by ligoj.

the class VmScheduleResourceTest method createAndUpdateSchedule.

@Test
public void createAndUpdateSchedule() throws Exception {
    final ApplicationContext mockContext = Mockito.mock(ApplicationContext.class);
    final VmScheduleRepository repository = Mockito.mock(VmScheduleRepository.class);
    final VmResource mockResource = Mockito.mock(VmResource.class);
    final Subscription entity = this.subscriptionRepository.findOneExpected(subscription);
    Mockito.when(mockContext.getBean(VmScheduleRepository.class)).thenReturn(repository);
    Mockito.when(mockContext.getBean(SecurityHelper.class)).thenReturn(Mockito.mock(SecurityHelper.class));
    Mockito.when(mockContext.getBean(VmResource.class)).thenReturn(mockResource);
    final StdScheduler scheduler = (StdScheduler) vmSchedulerFactoryBean.getScheduler();
    final QuartzScheduler qscheduler = (QuartzScheduler) FieldUtils.getField(StdScheduler.class, "sched", true).get(scheduler);
    final QuartzSchedulerResources resources = (QuartzSchedulerResources) FieldUtils.getField(QuartzScheduler.class, "resources", true).get(qscheduler);
    final JobDetail jobDetail = scheduler.getJobDetail(scheduler.getJobKeys(GroupMatcher.anyJobGroup()).iterator().next());
    // "ON" call would fail
    Mockito.doThrow(new RuntimeException()).when(mockResource).execute(entity, VmOperation.ON);
    try {
        // Mock the factory
        jobDetail.getJobDataMap().put("context", mockContext);
        ((RAMJobStore) resources.getJobStore()).storeJob(jobDetail, true);
        Assertions.assertEquals(1, this.repository.findAll().size());
        // Schedule all operations within the next 2 seconds
        final String cron = "" + ((DateUtils.newCalendar().get(Calendar.SECOND) + 2) % 60) + " * * * * ?";
        final int id = mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.OFF)));
        mockSchedule(repository, resource.create(subscription, newSchedule(cron + " *", VmOperation.ON)));
        Assertions.assertEquals(3, this.repository.findAll().size());
        // Yield for the schedules
        Thread.sleep(2500);
        // Check the executions
        Mockito.verify(mockResource).execute(entity, VmOperation.OFF);
        // Failed
        Mockito.verify(mockResource).execute(entity, VmOperation.ON);
        Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.REBOOT);
        Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.RESET);
        Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.SHUTDOWN);
        Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.SUSPEND);
        // Update the CRON and the operation
        final VmScheduleVo vo = newSchedule("" + ((DateUtils.newCalendar().get(Calendar.SECOND) + 2) % 60) + " * * * * ?", VmOperation.SHUTDOWN);
        vo.setId(id);
        resource.update(subscription, vo);
        Assertions.assertEquals(3, this.repository.findAll().size());
        // Yield for the schedules
        Thread.sleep(2500);
        Mockito.verify(mockResource).execute(entity, VmOperation.SHUTDOWN);
    } finally {
        // Restore the factory's context
        jobDetail.getJobDataMap().put("context", applicationContext);
        ((RAMJobStore) resources.getJobStore()).storeJob(jobDetail, true);
    }
}
Also used : QuartzScheduler(org.quartz.core.QuartzScheduler) QuartzSchedulerResources(org.quartz.core.QuartzSchedulerResources) RAMJobStore(org.quartz.simpl.RAMJobStore) VmResource(org.ligoj.app.plugin.vm.VmResource) ApplicationContext(org.springframework.context.ApplicationContext) JobDetail(org.quartz.JobDetail) VmScheduleRepository(org.ligoj.app.plugin.vm.dao.VmScheduleRepository) Subscription(org.ligoj.app.model.Subscription) SecurityHelper(org.ligoj.bootstrap.core.security.SecurityHelper) StdScheduler(org.quartz.impl.StdScheduler) Test(org.junit.jupiter.api.Test) AbstractServerTest(org.ligoj.app.AbstractServerTest)

Example 22 with Subscription

use of org.ligoj.app.model.Subscription in project plugin-vm by ligoj.

the class VmScheduleResourceTest method unscheduleAll.

@Test
public void unscheduleAll() throws Exception {
    Assertions.assertEquals(1, repository.findAll().size());
    repository.deleteAll();
    Assertions.assertEquals(0, repository.findAll().size());
    final Subscription entity = this.subscriptionRepository.findOneExpected(subscription);
    final ApplicationContext mockContext = Mockito.mock(ApplicationContext.class);
    final VmScheduleRepository repository = Mockito.mock(VmScheduleRepository.class);
    final VmResource mockResource = Mockito.mock(VmResource.class);
    Mockito.when(mockContext.getBean(VmScheduleRepository.class)).thenReturn(repository);
    Mockito.when(mockContext.getBean(SecurityHelper.class)).thenReturn(Mockito.mock(SecurityHelper.class));
    Mockito.when(mockContext.getBean(VmResource.class)).thenReturn(mockResource);
    final StdScheduler scheduler = (StdScheduler) vmSchedulerFactoryBean.getScheduler();
    final QuartzScheduler qscheduler = (QuartzScheduler) FieldUtils.getField(StdScheduler.class, "sched", true).get(scheduler);
    final QuartzSchedulerResources resources = (QuartzSchedulerResources) FieldUtils.getField(QuartzScheduler.class, "resources", true).get(qscheduler);
    final JobDetail jobDetail = scheduler.getJobDetail(scheduler.getJobKeys(GroupMatcher.anyJobGroup()).iterator().next());
    // One call would fail
    Mockito.doThrow(new RuntimeException()).when(mockResource).execute(entity, VmOperation.ON);
    final Subscription otherEntity = new Subscription();
    try {
        // Mock the factory
        jobDetail.getJobDataMap().put("context", mockContext);
        ((RAMJobStore) resources.getJobStore()).storeJob(jobDetail, true);
        // Schedule all operations within the next 2 seconds
        final String cron = "" + ((DateUtils.newCalendar().get(Calendar.SECOND) + 2) % 60) + " * * * * ? *";
        mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.ON)));
        mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.ON)));
        mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.ON)));
        mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.ON)));
        mockSchedule(repository, resource.create(subscription, newSchedule(cron, VmOperation.ON)));
        Assertions.assertEquals(5, this.repository.findAll().size());
        // Persist another VM schedule for another subscription within the
        // next 2 seconds
        otherEntity.setProject(entity.getProject());
        otherEntity.setNode(entity.getNode());
        this.subscriptionRepository.saveAndFlush(otherEntity);
        final VmScheduleVo schedule2 = newSchedule("0 0 0 1 1 ? 2050", VmOperation.ON);
        resource.create(otherEntity.getId(), schedule2);
        Assertions.assertEquals(6, this.repository.findAll().size());
        // Yield for the schedules
        Thread.sleep(2500);
    } finally {
        // Restore the factory's context
        jobDetail.getJobDataMap().put("context", applicationContext);
        ((RAMJobStore) resources.getJobStore()).storeJob(jobDetail, true);
    }
    Mockito.inOrder(mockResource).verify(mockResource, Mockito.calls(5)).execute(entity, VmOperation.ON);
    Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.OFF);
    Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.REBOOT);
    Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.RESET);
    Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.SHUTDOWN);
    Mockito.verify(mockResource, Mockito.never()).execute(entity, VmOperation.SUSPEND);
    // Remove all triggers of the subscription
    resource.unscheduleAll(subscription);
    Assertions.assertEquals(1, this.repository.findAll().size());
    resource.unscheduleAll(otherEntity.getId());
    Assertions.assertEquals(0, this.repository.findAll().size());
}
Also used : QuartzScheduler(org.quartz.core.QuartzScheduler) QuartzSchedulerResources(org.quartz.core.QuartzSchedulerResources) RAMJobStore(org.quartz.simpl.RAMJobStore) VmResource(org.ligoj.app.plugin.vm.VmResource) ApplicationContext(org.springframework.context.ApplicationContext) JobDetail(org.quartz.JobDetail) VmScheduleRepository(org.ligoj.app.plugin.vm.dao.VmScheduleRepository) Subscription(org.ligoj.app.model.Subscription) SecurityHelper(org.ligoj.bootstrap.core.security.SecurityHelper) StdScheduler(org.quartz.impl.StdScheduler) Test(org.junit.jupiter.api.Test) AbstractServerTest(org.ligoj.app.AbstractServerTest)

Example 23 with Subscription

use of org.ligoj.app.model.Subscription in project plugin-vm by ligoj.

the class VmScheduleResourceTest method delete.

@Test
public void delete() throws Exception {
    Assertions.assertEquals(1, repository.findAll().size());
    final Subscription entity = subscriptionRepository.findOneExpected(subscription);
    // Persist another VM schedule for another subscription
    final Subscription otherEntity = new Subscription();
    otherEntity.setProject(entity.getProject());
    otherEntity.setNode(entity.getNode());
    subscriptionRepository.saveAndFlush(otherEntity);
    final VmScheduleVo schedule2 = newSchedule("0 0 0 1 1 ? 2050", VmOperation.OFF);
    final int schedule = resource.create(otherEntity.getId(), schedule2);
    Assertions.assertEquals(2, repository.findAll().size());
    resource.delete(otherEntity.getId(), schedule);
    Assertions.assertEquals(1, repository.findAll().size());
    // Remove all triggers of the subscription
    resource.unscheduleAll(subscription);
    Assertions.assertEquals(0, repository.findAll().size());
}
Also used : Subscription(org.ligoj.app.model.Subscription) Test(org.junit.jupiter.api.Test) AbstractServerTest(org.ligoj.app.AbstractServerTest)

Example 24 with Subscription

use of org.ligoj.app.model.Subscription in project plugin-vm by ligoj.

the class VmResourceTest method downloadNodeSchedulesReport.

@Test
public void downloadNodeSchedulesReport() throws Exception {
    final VmResource resource = new VmResource();
    applicationContext.getAutowireCapableBeanFactory().autowireBean(resource);
    resource.locator = mockServicePluginLocator;
    final AtomicReference<VmOperation> operation = new AtomicReference<>(null);
    // The third call is skipped
    Mockito.doNothing().when(mockVmTool).execute(ArgumentMatchers.argThat(new ArgumentMatcher<VmExecution>() {

        @Override
        public boolean matches(final VmExecution argument) {
            argument.setOperation(operation.get());
            return true;
        }
    }));
    // Report without executions
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    ((StreamingOutput) resource.downloadNodeSchedulesReport("service:vm:test", "file1").getEntity()).write(output);
    List<String> lines = IOUtils.readLines(new ByteArrayInputStream(output.toByteArray()), StandardCharsets.UTF_8);
    Assertions.assertEquals(2, lines.size());
    Assertions.assertEquals("subscription;project;projectKey;projectName;node;cron;operation;lastDateHMS;lastTimestamp;lastOperation;vm;lastTrigger;lastSucceed;lastStatusText;lastErrorText;nextDateHMS;nextTimestamp", lines.get(0));
    // No last execution available
    Assertions.assertTrue(lines.get(1).matches("\\d+;\\d+;gfi-gstack;gStack;service:vm:test:test;0 0 0 1 1 \\? 2050;OFF;;;;;;;;;2050/01/01 00:00:00;2524604400000"), "Was : " + lines.get(1));
    output.close();
    // Manual execution
    operation.set(VmOperation.OFF);
    Integer id = resource.execute(subscription, VmOperation.OFF);
    vmExecutionRepository.findOneExpected(id).setStatusText("status1");
    // Manual execution by schedule, by pass the security check
    securityHelper.setUserName(SecurityHelper.SYSTEM_USERNAME);
    final Subscription entity = subscriptionRepository.findOneExpected(subscription);
    operation.set(VmOperation.SHUTDOWN);
    id = resource.execute(entity, VmOperation.ON);
    vmExecutionRepository.findOneExpected(id).setVm("vm1");
    // This call will be skipped
    operation.set(null);
    Assertions.assertNull(resource.execute(entity, VmOperation.REBOOT));
    // Restore the current user
    initSpringSecurityContext(getAuthenticationName());
    // Report contains only the last executions (OFF/SHUTDOWN/[REBOOT = skipped])
    output = new ByteArrayOutputStream();
    ((StreamingOutput) resource.downloadNodeSchedulesReport("service:vm:test", "file1").getEntity()).write(output);
    lines = IOUtils.readLines(new ByteArrayInputStream(output.toByteArray()), StandardCharsets.UTF_8);
    Assertions.assertEquals(2, lines.size());
    Assertions.assertTrue(lines.get(1).matches("\\d+;\\d+;gfi-gstack;gStack;service:vm:test:test;0 0 0 1 1 \\? 2050;OFF;.+;.+;SHUTDOWN;vm1;_system;true;;;2050/01/01 00:00:00;2524604400000"), "Was : " + lines.get(1));
    // Next execution where schedule CRON has been updated
    vmScheduleRepository.findBy("subscription.id", subscription).setCron("INVALID");
    operation.set(VmOperation.SHUTDOWN);
    id = resource.execute(entity, VmOperation.ON);
    vmExecutionRepository.findOneExpected(id).setVm("vm1");
    output = new ByteArrayOutputStream();
    ((StreamingOutput) resource.downloadNodeSchedulesReport("service:vm:test", "file1").getEntity()).write(output);
    lines = IOUtils.readLines(new ByteArrayInputStream(output.toByteArray()), StandardCharsets.UTF_8);
    Assertions.assertEquals(2, lines.size());
    Assertions.assertTrue(lines.get(1).matches("\\d+;\\d+;gfi-gstack;gStack;service:vm:test:test;INVALID;OFF;.+;.+;SHUTDOWN;vm1;fdaugan;true;;;ERROR;ERROR"));
    // Add another schedule to the same subscription, with an execution
    final VmSchedule schedule = new VmSchedule();
    schedule.setOperation(VmOperation.ON);
    schedule.setCron("0 0 0 1 1 ? 2049");
    schedule.setSubscription(entity);
    vmScheduleRepository.saveAndFlush(schedule);
    final VmExecution execution = new VmExecution();
    execution.setDate(new Date());
    execution.setSubscription(entity);
    execution.setTrigger("_system");
    execution.setOperation(VmOperation.ON);
    execution.setSucceed(true);
    vmExecutionRepository.saveAndFlush(execution);
    output = new ByteArrayOutputStream();
    ((StreamingOutput) resource.downloadNodeSchedulesReport("service:vm:test:test", "file1").getEntity()).write(output);
    lines = IOUtils.readLines(new ByteArrayInputStream(output.toByteArray()), StandardCharsets.UTF_8);
    Assertions.assertEquals(3, lines.size());
    Assertions.assertTrue(lines.get(2).matches("\\d+;\\d+;gfi-gstack;gStack;service:vm:test:test;0 0 0 1 1 \\? 2049;ON;.+;.+;ON;;_system;true;;;2049/01/01 00:00:00;2493068400000"), "Was : " + lines.get(2));
}
Also used : VmExecution(org.ligoj.app.plugin.vm.model.VmExecution) AtomicReference(java.util.concurrent.atomic.AtomicReference) StreamingOutput(javax.ws.rs.core.StreamingOutput) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Date(java.util.Date) ByteArrayInputStream(java.io.ByteArrayInputStream) VmOperation(org.ligoj.app.plugin.vm.model.VmOperation) ArgumentMatcher(org.mockito.ArgumentMatcher) Subscription(org.ligoj.app.model.Subscription) VmSchedule(org.ligoj.app.plugin.vm.model.VmSchedule) Test(org.junit.jupiter.api.Test) AbstractServerTest(org.ligoj.app.AbstractServerTest)

Example 25 with Subscription

use of org.ligoj.app.model.Subscription in project plugin-vm by ligoj.

the class VmJobTest method format.

@Test
public void format() {
    final VmSchedule vmSchedule = new VmSchedule();
    vmSchedule.setId(6789);
    final Subscription subscription = new Subscription();
    subscription.setId(12345);
    vmSchedule.setSubscription(subscription);
    Assertions.assertEquals("6789-12345", VmJob.format(vmSchedule));
}
Also used : Subscription(org.ligoj.app.model.Subscription) VmSchedule(org.ligoj.app.plugin.vm.model.VmSchedule) Test(org.junit.jupiter.api.Test)

Aggregations

Subscription (org.ligoj.app.model.Subscription)43 Test (org.junit.jupiter.api.Test)22 Path (javax.ws.rs.Path)10 Node (org.ligoj.app.model.Node)10 AbstractServerTest (org.ligoj.app.AbstractServerTest)9 IOException (java.io.IOException)7 GET (javax.ws.rs.GET)7 POST (javax.ws.rs.POST)7 HashMap (java.util.HashMap)6 Transactional (javax.transaction.Transactional)6 Produces (javax.ws.rs.Produces)6 Map (java.util.Map)5 Optional (java.util.Optional)5 PathParam (javax.ws.rs.PathParam)5 MediaType (javax.ws.rs.core.MediaType)5 Slf4j (lombok.extern.slf4j.Slf4j)5 File (java.io.File)4 Date (java.util.Date)4 Function (java.util.function.Function)4 DELETE (javax.ws.rs.DELETE)4