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;
}
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());
}
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;
}
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;
}
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));
}
Aggregations