Search in sources :

Example 1 with Subscription

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

the class TerraformResourceTest method newResource.

private TerraformResource newResource(final Terraforming providerResource, final BiFunction<Subscription, String[], File> toFile, final boolean dryRun, final String... customArgs) {
    final TerraformResource resource = new TerraformResource() {

        @Override
        protected File toFile(final Subscription subscription, final String file) {
            return toFile.apply(subscription, new String[] { file });
        }

        /**
         * Prepare the Terraform environment to apply the new environment. Note there is no concurrency check.
         */
        @Override
        protected File applyTerraform(final Subscription entity, final Terraforming terra, final QuoteVo configuration) throws IOException, InterruptedException {
            if (dryRun) {
                // Ignore this call
                return null;
            }
            return super.applyTerraform(entity, terra, configuration);
        }
    };
    super.applicationContext.getAutowireCapableBeanFactory().autowireBean(resource);
    // Replace the plugin locator
    final ServicePluginLocator locator = Mockito.mock(ServicePluginLocator.class);
    resource.locator = locator;
    // Replace the runner
    resource.runner = new TerraformRunnerResource();
    super.applicationContext.getAutowireCapableBeanFactory().autowireBean(resource.runner);
    Mockito.when(locator.getResource("service:prov:test:account", Terraforming.class)).thenReturn(providerResource);
    final PluginsClassLoader classLoader = Mockito.mock(PluginsClassLoader.class);
    Mockito.when(classLoader.getHomeDirectory()).thenReturn(MOCK_PATH.toPath());
    // Replace the CLI runner
    resource.terraformUtils = new TerraformUtils() {

        @Override
        public ProcessBuilder newBuilder(String... args) {
            return new ProcessBuilder(ArrayUtils.addAll(new String[] { "java", "-cp", MOCK_PATH.getParent(), "org.ligoj.app.plugin.prov.terraform.Main" }, customArgs.length > 0 ? customArgs : args));
        }

        @Override
        protected boolean isInstalled() {
            return true;
        }

        @Override
        protected PluginsClassLoader getClassLoader() {
            return classLoader;
        }

        public String getLastestVersion() {
            return "2.0.0";
        }
    };
    return resource;
}
Also used : QuoteVo(org.ligoj.app.plugin.prov.QuoteVo) Subscription(org.ligoj.app.model.Subscription) PluginsClassLoader(org.ligoj.app.resource.plugin.PluginsClassLoader) ServicePluginLocator(org.ligoj.app.resource.ServicePluginLocator)

Example 2 with Subscription

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

the class ProvResourceTest method create.

@Test
public void create() throws Exception {
    final Subscription subscription = new Subscription();
    subscription.setNode(em.find(Subscription.class, this.subscription).getNode());
    subscription.setProject(em.find(Subscription.class, this.subscription).getProject());
    em.persist(subscription);
    em.flush();
    em.clear();
    resource.create(subscription.getId());
    final QuoteVo configuration = resource.getConfiguration(subscription.getId());
    Assertions.assertNotNull(configuration);
    Assertions.assertNotNull(configuration.getName());
    Assertions.assertNotNull(configuration.getDescription());
}
Also used : Subscription(org.ligoj.app.model.Subscription) AbstractAppTest(org.ligoj.app.AbstractAppTest) Test(org.junit.jupiter.api.Test)

Example 3 with Subscription

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

the class ProvQuoteInstanceResource method lookup.

private QuoteInstanceLookup lookup(final ProvQuote configuration, final double cpu, final int ram, final Boolean constant, final VmOs osName, final String type, final boolean ephemeral, final String location, final String usageName) {
    final String node = configuration.getSubscription().getNode().getId();
    final int subscription = configuration.getSubscription().getId();
    // Resolve
    final VmOs os = Optional.ofNullable(osName).map(VmOs::toPricingOs).orElse(null);
    // Resolve the location to use
    final String locationR = location == null ? configuration.getLocation().getName() : location;
    // Compute the rate to use
    final ProvUsage usage = usageName == null ? ObjectUtils.defaultIfNull(configuration.getUsage(), USAGE_DEFAULT) : resource.findConfiguredByName(usageRepository, usageName, subscription);
    final double rate = usage.getRate() / 100d;
    final int duration = usage.getDuration();
    // Resolve the required instance type
    final Integer typeId = type == null ? null : assertFound(itRepository.findByName(subscription, type), type).getId();
    // Return only the first matching instance
    // Template instance
    final QuoteInstanceLookup template = ipRepository.findLowestPrice(node, cpu, ram, constant, os, typeId, ephemeral, locationR, rate, duration, PageRequest.of(0, 1)).stream().findFirst().map(ip -> newPrice((ProvInstancePrice) ip[0], (double) ip[2])).orElse(null);
    // Custom instance
    final QuoteInstanceLookup custom = ipRepository.findLowestCustomPrice(node, Math.ceil(cpu), Math.ceil(ram / 1024), constant, os, locationR, PageRequest.of(0, 1)).stream().findFirst().map(ip -> newPrice((ProvInstancePrice) ip[0], rate * (double) ip[1])).orElse(null);
    // Select the best price term
    if (template == null) {
        return custom;
    }
    if (custom == null) {
        return template;
    }
    return custom.getCost() < template.getCost() ? custom : template;
}
Also used : CsvForBean(org.ligoj.bootstrap.core.csv.CsvForBean) Produces(javax.ws.rs.Produces) ProvInstancePriceRepository(org.ligoj.app.plugin.prov.dao.ProvInstancePriceRepository) Path(javax.ws.rs.Path) ProvUsageRepository(org.ligoj.app.plugin.prov.dao.ProvUsageRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) ValidationJsonException(org.ligoj.bootstrap.core.validation.ValidationJsonException) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) ByteArrayInputStream(java.io.ByteArrayInputStream) Consumes(javax.ws.rs.Consumes) ProvLocation(org.ligoj.app.plugin.prov.model.ProvLocation) ProvInstanceTypeRepository(org.ligoj.app.plugin.prov.dao.ProvInstanceTypeRepository) DataTableAttributes(org.ligoj.bootstrap.core.json.datatable.DataTableAttributes) Map(java.util.Map) Multipart(org.apache.cxf.jaxrs.ext.multipart.Multipart) DefaultValue(javax.ws.rs.DefaultValue) Subscription(org.ligoj.app.model.Subscription) DescribedBean(org.ligoj.bootstrap.core.DescribedBean) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) Transactional(javax.transaction.Transactional) PageRequest(org.springframework.data.domain.PageRequest) Reader(java.io.Reader) StandardCharsets(java.nio.charset.StandardCharsets) ProvInstancePrice(org.ligoj.app.plugin.prov.model.ProvInstancePrice) Objects(java.util.Objects) ProvQuoteStorageRepository(org.ligoj.app.plugin.prov.dao.ProvQuoteStorageRepository) IOUtils(org.apache.commons.io.IOUtils) Slf4j(lombok.extern.slf4j.Slf4j) Optional(java.util.Optional) UriInfo(javax.ws.rs.core.UriInfo) TableItem(org.ligoj.bootstrap.core.json.TableItem) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) HashMap(java.util.HashMap) ArrayUtils(org.apache.commons.lang3.ArrayUtils) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ProvQuoteInstance(org.ligoj.app.plugin.prov.model.ProvQuoteInstance) Function(java.util.function.Function) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ObjectUtils(org.apache.commons.lang3.ObjectUtils) Service(org.springframework.stereotype.Service) ProvUsage(org.ligoj.app.plugin.prov.model.ProvUsage) POST(javax.ws.rs.POST) SequenceInputStream(java.io.SequenceInputStream) ProvQuoteInstanceRepository(org.ligoj.app.plugin.prov.dao.ProvQuoteInstanceRepository) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) ProvInstancePriceTermRepository(org.ligoj.app.plugin.prov.dao.ProvInstancePriceTermRepository) VmOs(org.ligoj.app.plugin.prov.model.VmOs) StringReader(java.io.StringReader) ProvInstancePriceTerm(org.ligoj.app.plugin.prov.model.ProvInstancePriceTerm) PUT(javax.ws.rs.PUT) ProvQuote(org.ligoj.app.plugin.prov.model.ProvQuote) BufferedReader(java.io.BufferedReader) ProvInstanceType(org.ligoj.app.plugin.prov.model.ProvInstanceType) InputStream(java.io.InputStream) VmOs(org.ligoj.app.plugin.prov.model.VmOs) ProvUsage(org.ligoj.app.plugin.prov.model.ProvUsage)

Example 4 with Subscription

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

the class ProvQuoteInstanceResource method saveOrUpdate.

/**
 * Save or update the given entity from the {@link QuoteInstanceEditionVo}. The computed cost are recursively
 * updated from the instance to the quote total cost.
 */
private UpdatedCost saveOrUpdate(final ProvQuoteInstance entity, final QuoteInstanceEditionVo vo) {
    // Compute the unbound cost delta
    final int deltaUnbound = BooleanUtils.toInteger(vo.getMaxQuantity() == null) - BooleanUtils.toInteger(entity.isUnboundCost());
    // Check the associations and copy attributes to the entity
    final ProvQuote configuration = getQuoteFromSubscription(vo.getSubscription());
    final Subscription subscription = configuration.getSubscription();
    final String providerId = subscription.getNode().getRefined().getId();
    DescribedBean.copy(vo, entity);
    entity.setConfiguration(configuration);
    final ProvLocation oldLocation = getLocation(entity);
    entity.setPrice(ipRepository.findOneExpected(vo.getPrice()));
    entity.setLocation(resource.findLocation(providerId, vo.getLocation()));
    entity.setUsage(Optional.ofNullable(vo.getUsage()).map(u -> resource.findConfiguredByName(usageRepository, u, subscription.getId())).orElse(null));
    entity.setOs(ObjectUtils.defaultIfNull(vo.getOs(), entity.getPrice().getOs()));
    entity.setRam(vo.getRam());
    entity.setCpu(vo.getCpu());
    entity.setConstant(vo.getConstant());
    entity.setEphemeral(vo.isEphemeral());
    entity.setInternet(vo.getInternet());
    entity.setMaxVariableCost(vo.getMaxVariableCost());
    entity.setMinQuantity(vo.getMinQuantity());
    entity.setMaxQuantity(vo.getMaxQuantity());
    resource.checkVisibility(entity.getPrice().getType(), providerId);
    checkConstraints(entity);
    checkOs(entity);
    // Update the unbound increment of the global quote
    configuration.setUnboundCostCounter(configuration.getUnboundCostCounter() + deltaUnbound);
    // Save and update the costs
    final UpdatedCost cost = newUpdateCost(entity);
    final Map<Integer, FloatingCost> storagesCosts = new HashMap<>();
    final boolean dirtyPrice = !oldLocation.equals(getLocation(entity));
    CollectionUtils.emptyIfNull(entity.getStorages()).stream().peek(s -> {
        if (dirtyPrice) {
            // Location has changed, the available storage price is invalidated
            storageResource.refresh(s);
            storageResource.refreshCost(s);
        }
    }).forEach(s -> storagesCosts.put(s.getId(), addCost(s, storageResource::updateCost)));
    cost.setRelatedCosts(storagesCosts);
    cost.setTotalCost(toFloatingCost(entity.getConfiguration()));
    return cost;
}
Also used : CsvForBean(org.ligoj.bootstrap.core.csv.CsvForBean) Produces(javax.ws.rs.Produces) ProvInstancePriceRepository(org.ligoj.app.plugin.prov.dao.ProvInstancePriceRepository) Path(javax.ws.rs.Path) ProvUsageRepository(org.ligoj.app.plugin.prov.dao.ProvUsageRepository) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) ValidationJsonException(org.ligoj.bootstrap.core.validation.ValidationJsonException) MediaType(javax.ws.rs.core.MediaType) QueryParam(javax.ws.rs.QueryParam) ByteArrayInputStream(java.io.ByteArrayInputStream) Consumes(javax.ws.rs.Consumes) ProvLocation(org.ligoj.app.plugin.prov.model.ProvLocation) ProvInstanceTypeRepository(org.ligoj.app.plugin.prov.dao.ProvInstanceTypeRepository) DataTableAttributes(org.ligoj.bootstrap.core.json.datatable.DataTableAttributes) Map(java.util.Map) Multipart(org.apache.cxf.jaxrs.ext.multipart.Multipart) DefaultValue(javax.ws.rs.DefaultValue) Subscription(org.ligoj.app.model.Subscription) DescribedBean(org.ligoj.bootstrap.core.DescribedBean) DELETE(javax.ws.rs.DELETE) Context(javax.ws.rs.core.Context) Transactional(javax.transaction.Transactional) PageRequest(org.springframework.data.domain.PageRequest) Reader(java.io.Reader) StandardCharsets(java.nio.charset.StandardCharsets) ProvInstancePrice(org.ligoj.app.plugin.prov.model.ProvInstancePrice) Objects(java.util.Objects) ProvQuoteStorageRepository(org.ligoj.app.plugin.prov.dao.ProvQuoteStorageRepository) IOUtils(org.apache.commons.io.IOUtils) Slf4j(lombok.extern.slf4j.Slf4j) Optional(java.util.Optional) UriInfo(javax.ws.rs.core.UriInfo) TableItem(org.ligoj.bootstrap.core.json.TableItem) PathParam(javax.ws.rs.PathParam) GET(javax.ws.rs.GET) HashMap(java.util.HashMap) ArrayUtils(org.apache.commons.lang3.ArrayUtils) BooleanUtils(org.apache.commons.lang3.BooleanUtils) ProvQuoteInstance(org.ligoj.app.plugin.prov.model.ProvQuoteInstance) Function(java.util.function.Function) CollectionUtils(org.apache.commons.collections4.CollectionUtils) ObjectUtils(org.apache.commons.lang3.ObjectUtils) Service(org.springframework.stereotype.Service) ProvUsage(org.ligoj.app.plugin.prov.model.ProvUsage) POST(javax.ws.rs.POST) SequenceInputStream(java.io.SequenceInputStream) ProvQuoteInstanceRepository(org.ligoj.app.plugin.prov.dao.ProvQuoteInstanceRepository) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) ProvInstancePriceTermRepository(org.ligoj.app.plugin.prov.dao.ProvInstancePriceTermRepository) VmOs(org.ligoj.app.plugin.prov.model.VmOs) StringReader(java.io.StringReader) ProvInstancePriceTerm(org.ligoj.app.plugin.prov.model.ProvInstancePriceTerm) PUT(javax.ws.rs.PUT) ProvQuote(org.ligoj.app.plugin.prov.model.ProvQuote) BufferedReader(java.io.BufferedReader) ProvInstanceType(org.ligoj.app.plugin.prov.model.ProvInstanceType) InputStream(java.io.InputStream) HashMap(java.util.HashMap) ProvLocation(org.ligoj.app.plugin.prov.model.ProvLocation) ProvQuote(org.ligoj.app.plugin.prov.model.ProvQuote) Subscription(org.ligoj.app.model.Subscription)

Example 5 with Subscription

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

the class EventResourceTest method registerSubscriptionEvent.

@Test
public void registerSubscriptionEvent() {
    final Subscription subscription = new Subscription();
    subscription.setProject(projectRepository.findByName("MDA"));
    subscription.setNode(em.find(Node.class, "service:build:jenkins:bpr"));
    em.persist(subscription);
    long count = repository.count();
    Assertions.assertTrue(resource.registerEvent(subscription, EventType.STATUS, NodeStatus.UP.name()));
    Assertions.assertEquals(++count, repository.count());
    Assertions.assertTrue(resource.registerEvent(subscription, EventType.STATUS, NodeStatus.DOWN.name()));
    Assertions.assertEquals(++count, repository.count());
    final Event lastEvent = repository.findFirstBySubscriptionAndTypeOrderByIdDesc(subscription, EventType.STATUS);
    Assertions.assertTrue(DateUtils.addSeconds(lastEvent.getDate(), 5).after(new Date()));
    Assertions.assertFalse(resource.registerEvent(subscription, EventType.STATUS, NodeStatus.DOWN.name()));
    Assertions.assertEquals(count, repository.count());
    Assertions.assertEquals(lastEvent, repository.findFirstBySubscriptionAndTypeOrderByIdDesc(subscription, EventType.STATUS));
}
Also used : Node(org.ligoj.app.model.Node) Event(org.ligoj.app.model.Event) Subscription(org.ligoj.app.model.Subscription) Date(java.util.Date) AbstractAppTest(org.ligoj.app.AbstractAppTest) 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