diff --git a/src/main/java/org/nrg/xnat/compute/config/ComputeConfig.java b/src/main/java/org/nrg/xnat/compute/config/ComputeConfig.java deleted file mode 100644 index 4cf6877..0000000 --- a/src/main/java/org/nrg/xnat/compute/config/ComputeConfig.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ComponentScan({"org.nrg.xnat.compute.services.impl", - "org.nrg.xnat.compute.services", - "org.nrg.xnat.compute.rest", - "org.nrg.xnat.compute.repositories"}) -public class ComputeConfig { -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentConfigEntity.java b/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentConfigEntity.java deleted file mode 100644 index e8990f8..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentConfigEntity.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.framework.constants.Scope; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntity; -import org.nrg.xnat.compute.models.ComputeEnvironmentConfig; - -import javax.persistence.*; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode(callSuper = true) -public class ComputeEnvironmentConfigEntity extends AbstractHibernateEntity { - - private Set configTypes; - - private ComputeEnvironmentEntity computeEnvironment; - private Map scopes; - private ComputeEnvironmentHardwareOptionsEntity hardwareOptions; - - @ElementCollection - public Set getConfigTypes() { - if (configTypes == null) { - configTypes = new HashSet<>(); - } - - return configTypes; - } - - public void setConfigTypes(Set configTypes) { - this.configTypes = configTypes; - } - - @OneToOne(mappedBy = "computeEnvironmentConfig", cascade = CascadeType.ALL, orphanRemoval = true) - public ComputeEnvironmentEntity getComputeEnvironment() { - return computeEnvironment; - } - - public void setComputeEnvironment(ComputeEnvironmentEntity computeEnvironment) { - computeEnvironment.setComputeEnvironmentConfig(this); - this.computeEnvironment = computeEnvironment; - } - - @OneToMany(mappedBy = "computeEnvironmentConfig", cascade = CascadeType.ALL, orphanRemoval = true) - public Map getScopes() { - return scopes; - } - - public void setScopes(Map scopes) { - this.scopes = scopes; - } - - @OneToOne(mappedBy = "computeEnvironmentConfig", cascade = CascadeType.ALL, orphanRemoval = true) - public ComputeEnvironmentHardwareOptionsEntity getHardwareOptions() { - return hardwareOptions; - } - - public void setHardwareOptions(ComputeEnvironmentHardwareOptionsEntity hardwareOptions) { - this.hardwareOptions = hardwareOptions; - } - - /** - * Creates a new entity from the pojo. - * @param pojo The pojo to create the entity from - * @return The newly created entity - */ - public static ComputeEnvironmentConfigEntity fromPojo(final ComputeEnvironmentConfig pojo) { - final ComputeEnvironmentConfigEntity entity = new ComputeEnvironmentConfigEntity(); - entity.update(pojo); - return entity; - } - - /** - * Creates a new pojo from the entity. - * @return The pojo created from the entity - */ - public ComputeEnvironmentConfig toPojo() { - return ComputeEnvironmentConfig.builder() - .id(getId()) - .configTypes(getConfigTypes() - .stream() - .map(ComputeEnvironmentConfig.ConfigType::valueOf) - .collect(Collectors.toSet())) - .computeEnvironment(getComputeEnvironment().toPojo()) - .scopes(getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toPojo()))) - .hardwareOptions(getHardwareOptions().toPojo()) - .build(); - } - - /** - * Updates the entity with the values from the pojo. Does not update the hardwareConfigs, since that is a - * many-to-many relationship and needs to be handled separately. - * @param pojo The pojo to update the entity with - */ - public void update(final ComputeEnvironmentConfig pojo) { - setConfigTypes(pojo.getConfigTypes() - .stream() - .map(Enum::name) - .collect(Collectors.toSet())); - - if (getComputeEnvironment() == null) { - // This is a new entity, so we need to create the computeEnvironment entity - setComputeEnvironment(ComputeEnvironmentEntity.fromPojo(pojo.getComputeEnvironment())); - } else { - // This is an existing entity, so we need to update the computeEnvironment entity - getComputeEnvironment().update(pojo.getComputeEnvironment()); - } - - if (getScopes() == null) { - // This is a new entity, so we need to create the scopes entity - setScopes(pojo.getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> ComputeEnvironmentScopeEntity.fromPojo(e.getValue())))); - } else { - // This is an existing entity, so we need to update the scopes entities - getScopes().forEach((key, value) -> value.update(pojo.getScopes().get(key))); - } - - // Set the computeEnvironmentConfig on the scopes - getScopes().values().forEach(s -> s.setComputeEnvironmentConfig(this)); - - if (getHardwareOptions() == null) { - // This is a new entity, so we need to create the hardwareOptions entity - ComputeEnvironmentHardwareOptionsEntity computeEnvironmentHardwareOptionsEntity = ComputeEnvironmentHardwareOptionsEntity.fromPojo(pojo.getHardwareOptions()); - setHardwareOptions(computeEnvironmentHardwareOptionsEntity); - computeEnvironmentHardwareOptionsEntity.setComputeEnvironmentConfig(this); - } else { - // This is an existing entity, so we need to update the hardwareOptions entity - getHardwareOptions().update(pojo.getHardwareOptions()); - } - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentEntity.java b/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentEntity.java deleted file mode 100644 index 5c0e110..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentEntity.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntity; -import org.nrg.xnat.compute.models.ComputeEnvironment; - -import javax.persistence.*; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -@Entity -@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"name"})}) -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode(callSuper = true) -public class ComputeEnvironmentEntity extends AbstractHibernateEntity { - - private String name; - private String image; - private String command; - - private List environmentVariables; - private List mounts; - - @ToString.Exclude @EqualsAndHashCode.Exclude private ComputeEnvironmentConfigEntity computeEnvironmentConfig; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getImage() { - return image; - } - - public void setImage(String image) { - this.image = image; - } - - public String getCommand() { - return command; - } - - public void setCommand(String command) { - this.command = command; - } - - @ElementCollection - public List getEnvironmentVariables() { - if (environmentVariables == null) { - environmentVariables = new ArrayList<>(); - } - - return environmentVariables; - } - - public void setEnvironmentVariables(List environmentVariables) { - this.environmentVariables = environmentVariables; - } - - @ElementCollection - public List getMounts() { - if (mounts == null) { - mounts = new ArrayList<>(); - } - - return mounts; - } - - public void setMounts(List mounts) { - this.mounts = mounts; - } - - @OneToOne - public ComputeEnvironmentConfigEntity getComputeEnvironmentConfig() { - return computeEnvironmentConfig; - } - - public void setComputeEnvironmentConfig(ComputeEnvironmentConfigEntity computeEnvironmentConfig) { - this.computeEnvironmentConfig = computeEnvironmentConfig; - } - - /** - * Creates a new entity from the given pojo. - * @param pojo The pojo to convert. - * @return The entity created from the pojo. - */ - public static ComputeEnvironmentEntity fromPojo(ComputeEnvironment pojo) { - final ComputeEnvironmentEntity entity = new ComputeEnvironmentEntity(); - entity.update(pojo); - return entity; - } - - /** - * Converts this entity to a pojo. - * @return The pojo created from this entity. - */ - public ComputeEnvironment toPojo() { - return ComputeEnvironment.builder() - .name(getName()) - .image(getImage()) - .command(getCommand()) - .environmentVariables(getEnvironmentVariables().stream().map(EnvironmentVariableEntity::toPojo).collect(Collectors.toList())) - .mounts(getMounts().stream().map(MountEntity::toPojo).collect(Collectors.toList())) - .build(); - } - - /** - * Updates this entity from the given pojo. - * @param pojo The pojo to update from. - */ - public void update(ComputeEnvironment pojo) { - setName(pojo.getName()); - setImage(pojo.getImage()); - setCommand(pojo.getCommand()); - - // Clear the existing environment variables - getEnvironmentVariables().clear(); - - // Add the new environment variables - if (pojo.getEnvironmentVariables() != null) { - getEnvironmentVariables().addAll(pojo.getEnvironmentVariables() - .stream() - .map(EnvironmentVariableEntity::fromPojo) - .collect(Collectors.toList())); - } - - // Clear the existing mounts - getMounts().clear(); - - // Add the new mounts - if (pojo.getMounts() != null) { - getMounts().addAll(pojo.getMounts() - .stream() - .map(MountEntity::fromPojo) - .collect(Collectors.toList())); - } - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentHardwareOptionsEntity.java b/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentHardwareOptionsEntity.java deleted file mode 100644 index c3c5ee9..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentHardwareOptionsEntity.java +++ /dev/null @@ -1,114 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.xnat.compute.models.ComputeEnvironmentHardwareOptions; - -import javax.persistence.*; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; - -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode -public class ComputeEnvironmentHardwareOptionsEntity { - - private long id; - - @ToString.Exclude @EqualsAndHashCode.Exclude private ComputeEnvironmentConfigEntity computeEnvironmentConfig; - - private boolean allowAllHardware; - private Set hardwareConfigs; - - @Id - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - @OneToOne - @MapsId - public ComputeEnvironmentConfigEntity getComputeEnvironmentConfig() { - return computeEnvironmentConfig; - } - - public void setComputeEnvironmentConfig(ComputeEnvironmentConfigEntity computeEnvironmentConfig) { - this.computeEnvironmentConfig = computeEnvironmentConfig; - } - - public boolean isAllowAllHardware() { - return allowAllHardware; - } - - public void setAllowAllHardware(boolean allowAllHardware) { - this.allowAllHardware = allowAllHardware; - } - - @ManyToMany - @JoinTable(name = "compute_environment_hardware_options_hardware_config", - joinColumns = @JoinColumn(name = "compute_environment_hardware_options_id"), - inverseJoinColumns = @JoinColumn(name = "hardware_config_id")) - public Set getHardwareConfigs() { - return hardwareConfigs; - } - - public void setHardwareConfigs(Set hardwareConfigs) { - this.hardwareConfigs = hardwareConfigs; - } - - public void addHardwareConfig(HardwareConfigEntity hardwareConfig) { - if (hardwareConfigs == null) { - hardwareConfigs = new HashSet<>(); - } - - hardwareConfigs.add(hardwareConfig); - } - - public void removeHardwareConfig(HardwareConfigEntity hardwareConfig) { - if (hardwareConfigs != null) { - hardwareConfigs.remove(hardwareConfig); - } - } - - /** - * Creates a new entity from the given pojo. - * @param pojo The pojo to create the entity from. - * @return The newly created entity. - */ - public static ComputeEnvironmentHardwareOptionsEntity fromPojo(final ComputeEnvironmentHardwareOptions pojo) { - final ComputeEnvironmentHardwareOptionsEntity entity = new ComputeEnvironmentHardwareOptionsEntity(); - entity.update(pojo); - return entity; - } - - /** - * Creates a new pojo from the given entity. - * @return The newly created pojo. - */ - public ComputeEnvironmentHardwareOptions toPojo() { - return ComputeEnvironmentHardwareOptions.builder() - .allowAllHardware(allowAllHardware) - .hardwareConfigs(hardwareConfigs.stream().map(HardwareConfigEntity::toPojo).collect(Collectors.toSet())) - .build(); - } - - /** - * Updates the entity with the values from the given pojo. - * @param pojo The pojo to update the entity with. - */ - public void update(final ComputeEnvironmentHardwareOptions pojo) { - setAllowAllHardware(pojo.isAllowAllHardware()); - - if (hardwareConfigs == null) { - hardwareConfigs = new HashSet<>(); - } - - // Updating the hardware configs is handled separately by the add/remove hardware config methods - } -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentScopeEntity.java b/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentScopeEntity.java deleted file mode 100644 index 4a7ef9c..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/ComputeEnvironmentScopeEntity.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.framework.constants.Scope; -import org.nrg.xnat.compute.models.ComputeEnvironmentScope; - -import javax.persistence.*; -import java.util.HashSet; -import java.util.Set; - -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode -public class ComputeEnvironmentScopeEntity { - - private long id; - private String scope; - private boolean enabled; - private Set ids; - - @ToString.Exclude @EqualsAndHashCode.Exclude private ComputeEnvironmentConfigEntity computeEnvironmentConfig; - - @Id - @GeneratedValue - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getScope() { - return scope; - } - - public void setScope(String scope) { - this.scope = scope; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - @ElementCollection - public Set getIds() { - if (ids == null) { - ids = new HashSet<>(); - } - - return ids; - } - - public void setIds(Set ids) { - this.ids = ids; - } - - @ManyToOne - public ComputeEnvironmentConfigEntity getComputeEnvironmentConfig() { - return computeEnvironmentConfig; - } - - public void setComputeEnvironmentConfig(ComputeEnvironmentConfigEntity computeEnvironmentConfig) { - this.computeEnvironmentConfig = computeEnvironmentConfig; - } - - /** - * Updates this entity with the values from the given pojo. - * @param pojo The pojo to update from - */ - public void update(ComputeEnvironmentScope pojo) { - setScope(pojo.getScope().name()); - setEnabled(pojo.isEnabled()); - - getIds().clear(); - - // add new ids - if (pojo.getIds() != null && !pojo.getIds().isEmpty()) { - getIds().addAll(pojo.getIds()); - } - } - - /** - * Converts this entity to a pojo. - * @return The pojo - */ - public ComputeEnvironmentScope toPojo() { - return ComputeEnvironmentScope.builder() - .scope(Scope.valueOf(getScope())) - .enabled(isEnabled()) - .ids(getIds()) - .build(); - } - - /** - * Creates a new entity from the given pojo. - * @param pojo The pojo to create from - * @return The new entity - */ - public static ComputeEnvironmentScopeEntity fromPojo(ComputeEnvironmentScope pojo) { - final ComputeEnvironmentScopeEntity entity = new ComputeEnvironmentScopeEntity(); - entity.update(pojo); - return entity; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/ConstraintConfigEntity.java b/src/main/java/org/nrg/xnat/compute/entities/ConstraintConfigEntity.java deleted file mode 100644 index 09436da..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/ConstraintConfigEntity.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.framework.constants.Scope; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntity; -import org.nrg.xnat.compute.models.ConstraintConfig; - -import javax.persistence.CascadeType; -import javax.persistence.Entity; -import javax.persistence.OneToMany; -import javax.persistence.OneToOne; -import java.util.Map; -import java.util.stream.Collectors; - -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode(callSuper = true) -public class ConstraintConfigEntity extends AbstractHibernateEntity { - - private ConstraintEntity constraint; - private Map scopes; - - @OneToOne(mappedBy = "constraintConfig", cascade = CascadeType.ALL, orphanRemoval = true) - public ConstraintEntity getConstraint() { - return constraint; - } - - public void setConstraint(ConstraintEntity constraint) { - constraint.setConstraintConfig(this); - this.constraint = constraint; - } - - @OneToMany(mappedBy = "constraintConfig", cascade = CascadeType.ALL, orphanRemoval = true) - public Map getScopes() { - return scopes; - } - - public void setScopes(Map scopes) { - this.scopes = scopes; - } - - /** - * This method is used to update the entity from the pojo. - * @param pojo The pojo to update from. - */ - public void update(final ConstraintConfig pojo) { - if (getConstraint() == null) { - // New entity - setConstraint(ConstraintEntity.fromPojo(pojo.getConstraint())); - } else { - // Existing entity - getConstraint().update(pojo.getConstraint()); - } - - getConstraint().setConstraintConfig(this); - - if (getScopes() == null) { - // This is a new entity, so we need to create the scope entities - setScopes(pojo.getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> ConstraintScopeEntity.fromPojo(e.getValue())))); - } else { - // This is an existing entity, so we need to update the scope entities - getScopes().forEach((key, value) -> value.update(pojo.getScopes().get(key))); - } - - // Set the constraint config on the scope entities - getScopes().forEach((key, value) -> value.setConstraintConfig(this)); - } - - /** - * This method is used to convert the entity to a pojo. - * @return The pojo. - */ - public ConstraintConfig toPojo() { - return ConstraintConfig.builder() - .id(getId()) - .constraint(getConstraint().toPojo()) - .scopes(getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toPojo()))) - .build(); - } - - /** - * This method is used to create a new entity from the pojo. - * @param pojo The pojo to create from. - * @return The new entity. - */ - public static ConstraintConfigEntity fromPojo(final ConstraintConfig pojo) { - final ConstraintConfigEntity entity = new ConstraintConfigEntity(); - entity.update(pojo); - return entity; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/ConstraintEntity.java b/src/main/java/org/nrg/xnat/compute/entities/ConstraintEntity.java deleted file mode 100644 index e621c93..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/ConstraintEntity.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntity; -import org.nrg.xnat.compute.models.Constraint; - -import javax.persistence.ElementCollection; -import javax.persistence.Entity; -import javax.persistence.MapsId; -import javax.persistence.OneToOne; -import java.util.HashSet; -import java.util.Set; - -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode(callSuper = true) -public class ConstraintEntity extends AbstractHibernateEntity { - - private String key; - private Set constraintValues; // Different from model, values is a reserved word - private String operator; - - @ToString.Exclude @EqualsAndHashCode.Exclude private ConstraintConfigEntity constraintConfig; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - @ElementCollection - public Set getConstraintValues() { - return constraintValues; - } - - public void setConstraintValues(Set constraintValues) { - if (constraintValues == null) { - constraintValues = new HashSet<>(); - } - - this.constraintValues = constraintValues; - } - - public String getOperator() { - return operator; - } - - public void setOperator(String operator) { - this.operator = operator; - } - - @OneToOne - @MapsId - public ConstraintConfigEntity getConstraintConfig() { - return constraintConfig; - } - - public void setConstraintConfig(ConstraintConfigEntity constraintConfig) { - this.constraintConfig = constraintConfig; - } - - public void update(final Constraint constraint) { - setKey(constraint.getKey()); - setConstraintValues(constraint.getValues()); - setOperator(constraint.getOperator().toString()); - setConstraintConfig(this.constraintConfig); - } - - public Constraint toPojo() { - return Constraint.builder() - .key(getKey()) - .values(getConstraintValues()) - .operator(Constraint.Operator.valueOf(getOperator())) - .build(); - } - - public static ConstraintEntity fromPojo(final Constraint constraint) { - final ConstraintEntity entity = new ConstraintEntity(); - entity.update(constraint); - return entity; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/ConstraintScopeEntity.java b/src/main/java/org/nrg/xnat/compute/entities/ConstraintScopeEntity.java deleted file mode 100644 index 05cd6b9..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/ConstraintScopeEntity.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.framework.constants.Scope; -import org.nrg.xnat.compute.models.ConstraintScope; - -import javax.persistence.*; -import java.util.HashSet; -import java.util.Set; - -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode -public class ConstraintScopeEntity { - - private long id; - private String scope; - private boolean enabled; - private Set ids; - - @ToString.Exclude @EqualsAndHashCode.Exclude private ConstraintConfigEntity constraintConfig; - - @Id - @GeneratedValue - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public String getScope() { - return scope; - } - - public void setScope(String scope) { - this.scope = scope; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - @ElementCollection - public Set getIds() { - return ids; - } - - public void setIds(Set ids) { - this.ids = ids; - } - - @ManyToOne - public ConstraintConfigEntity getConstraintConfig() { - return constraintConfig; - } - - public void setConstraintConfig(ConstraintConfigEntity constraintConfig) { - this.constraintConfig = constraintConfig; - } - - /** - * Converts this entity to a pojo. - * @return The pojo. - */ - public ConstraintScope toPojo() { - return ConstraintScope.builder() - .scope(Scope.valueOf(getScope())) - .enabled(isEnabled()) - .ids(getIds()) - .build(); - } - - /** - * Updates this entity from the given pojo. - * @param pojo The pojo. - */ - public void update(final ConstraintScope pojo) { - setScope(pojo.getScope().name()); - setEnabled(pojo.isEnabled()); - - if (getIds() == null) { - // This is a new entity, so we need to initialize the collection - setIds(new HashSet<>()); - } else { - // This is an existing entity, so we need to clear the collection - getIds().clear(); - } - - // add new ids - if (pojo.getIds() != null) { - getIds().addAll(pojo.getIds()); - } - } - - /** - * Creates a new entity from the given pojo. - * @param pojo The pojo. - * @return The entity. - */ - public static ConstraintScopeEntity fromPojo(final ConstraintScope pojo) { - final ConstraintScopeEntity entity = new ConstraintScopeEntity(); - entity.update(pojo); - return entity; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/EnvironmentVariableEntity.java b/src/main/java/org/nrg/xnat/compute/entities/EnvironmentVariableEntity.java deleted file mode 100644 index 84f7dd4..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/EnvironmentVariableEntity.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.xnat.compute.models.EnvironmentVariable; - -import javax.persistence.Embeddable; - -@Embeddable -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode -public class EnvironmentVariableEntity { - - private String key; - private String value; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public void update(EnvironmentVariable environmentVariable) { - setKey(environmentVariable.getKey()); - setValue(environmentVariable.getValue()); - } - - public EnvironmentVariable toPojo() { - return EnvironmentVariable.builder() - .key(key) - .value(value) - .build(); - } - - public static EnvironmentVariableEntity fromPojo(EnvironmentVariable environmentVariable) { - final EnvironmentVariableEntity entity = new EnvironmentVariableEntity(); - entity.update(environmentVariable); - return entity; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/GenericResourceEntity.java b/src/main/java/org/nrg/xnat/compute/entities/GenericResourceEntity.java deleted file mode 100644 index a147093..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/GenericResourceEntity.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.xnat.compute.models.GenericResource; - -import javax.persistence.Embeddable; - -@Embeddable -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode -public class GenericResourceEntity { - - private String name; - private String value; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public void update(GenericResource genericResource) { - setName(genericResource.getName()); - setValue(genericResource.getValue()); - } - - public GenericResource toPojo() { - return GenericResource.builder() - .name(name) - .value(value) - .build(); - } - - public static GenericResourceEntity fromPojo(GenericResource genericResource) { - final GenericResourceEntity entity = new GenericResourceEntity(); - entity.update(genericResource); - return entity; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/HardwareConfigEntity.java b/src/main/java/org/nrg/xnat/compute/entities/HardwareConfigEntity.java deleted file mode 100644 index 3c250a1..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/HardwareConfigEntity.java +++ /dev/null @@ -1,111 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.framework.constants.Scope; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntity; -import org.nrg.xnat.compute.models.HardwareConfig; - -import javax.persistence.*; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode(callSuper = true) -public class HardwareConfigEntity extends AbstractHibernateEntity { - - private HardwareEntity hardware; - private Map scopes; - - @ToString.Exclude @EqualsAndHashCode.Exclude private List computeEnvironmentHardwareOptions; - - @OneToOne(mappedBy = "hardwareConfig", cascade = CascadeType.ALL, orphanRemoval = true) - public HardwareEntity getHardware() { - return hardware; - } - - public void setHardware(HardwareEntity hardware) { - hardware.setHardwareConfig(this); - this.hardware = hardware; - } - - @OneToMany(mappedBy = "hardwareConfig", cascade = CascadeType.ALL, orphanRemoval = true) - public Map getScopes() { - return scopes; - } - - public void setScopes(Map scopes) { - this.scopes = scopes; - } - - @ManyToMany(mappedBy = "hardwareConfigs") - public List getComputeEnvironmentHardwareOptions() { - return computeEnvironmentHardwareOptions; - } - - public void setComputeEnvironmentHardwareOptions(List computeEnvironmentHardwareOptions) { - this.computeEnvironmentHardwareOptions = computeEnvironmentHardwareOptions; - } - - /** - * Creates a new entity from the given pojo. - * @param pojo The pojo from which to create the entity. - * @return The newly created entity. - */ - public static HardwareConfigEntity fromPojo(final HardwareConfig pojo) { - final HardwareConfigEntity entity = new HardwareConfigEntity(); - entity.update(pojo); - return entity; - } - - /** - * Creates a new pojo from the given entity. - * @return The newly created pojo. - */ - public HardwareConfig toPojo() { - return HardwareConfig.builder() - .id(getId()) - .hardware(getHardware().toPojo()) - .scopes(getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toPojo()))) - .build(); - } - - /** - * Updates the entity with the values from the given pojo. - * @param pojo The pojo from which to update the entity. - */ - public void update(final HardwareConfig pojo) { - if (getHardware() == null) { - // This is a new entity, so we need to create the hardware entity - setHardware(HardwareEntity.fromPojo(pojo.getHardware())); - } else { - // This is an existing entity, so we need to update the hardware entity - getHardware().update(pojo.getHardware()); - } - - // Set the hardware config on the hardware entity - getHardware().setHardwareConfig(this); - - if (getScopes() == null) { - // This is a new entity, so we need to create the scope entities - setScopes(pojo.getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, e -> HardwareScopeEntity.fromPojo(e.getValue())))); - } else { - // This is an existing entity, so we need to update the scope entities - getScopes().forEach((key, value) -> value.update(pojo.getScopes().get(key))); - } - - // Set the hardware config on the scope entities - getScopes().forEach((key, value) -> value.setHardwareConfig(this)); - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/HardwareConstraintEntity.java b/src/main/java/org/nrg/xnat/compute/entities/HardwareConstraintEntity.java deleted file mode 100644 index 10a7c86..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/HardwareConstraintEntity.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntity; -import org.nrg.xnat.compute.models.Constraint; - -import javax.persistence.*; -import java.util.Set; - -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -public class HardwareConstraintEntity extends AbstractHibernateEntity { - - private String key; - private Set constraintValues; // Different from model, values is a reserved word - private String operator; - - @ToString.Exclude @EqualsAndHashCode.Exclude private HardwareEntity hardware; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - @ElementCollection(fetch = FetchType.EAGER) - public Set getConstraintValues() { - return constraintValues; - } - - public void setConstraintValues(Set constraintValues) { - this.constraintValues = constraintValues; - } - - public String getOperator() { - return operator; - } - - public void setOperator(String operator) { - this.operator = operator; - } - - @ManyToOne - @JoinColumn(name = "hardware_entity_id") - public HardwareEntity getHardware() { - return hardware; - } - - public void setHardware(HardwareEntity hardware) { - this.hardware = hardware; - } - - public void update(final Constraint constraint) { - setKey(constraint.getKey()); - setConstraintValues(constraint.getValues()); - setOperator(constraint.getOperator().toString()); - setHardware(this.hardware); - } - - public Constraint toPojo() { - return Constraint.builder() - .key(key) - .values(constraintValues) - .operator(Constraint.Operator.valueOf(operator)) - .build(); - } - - public static HardwareConstraintEntity fromPojo(final Constraint constraint) { - final HardwareConstraintEntity entity = new HardwareConstraintEntity(); - entity.update(constraint); - return entity; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/HardwareEntity.java b/src/main/java/org/nrg/xnat/compute/entities/HardwareEntity.java deleted file mode 100644 index 22ee0a7..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/HardwareEntity.java +++ /dev/null @@ -1,184 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntity; -import org.nrg.xnat.compute.models.Hardware; - -import javax.persistence.*; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -@Entity -@Table(uniqueConstraints = {@UniqueConstraint(columnNames = {"name"})}) -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode(callSuper = true) -public class HardwareEntity extends AbstractHibernateEntity { - - private String name; - - private Double cpuReservation; - private Double cpuLimit; - private String memoryReservation; - private String memoryLimit; - - private List constraints; - private List environmentVariables; - private List genericResources; - - @ToString.Exclude @EqualsAndHashCode.Exclude private HardwareConfigEntity hardwareConfig; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Double getCpuReservation() { - return cpuReservation; - } - - public void setCpuReservation(Double cpuReservation) { - this.cpuReservation = cpuReservation; - } - - public Double getCpuLimit() { - return cpuLimit; - } - - public void setCpuLimit(Double cpuLimit) { - this.cpuLimit = cpuLimit; - } - - public String getMemoryReservation() { - return memoryReservation; - } - - public void setMemoryReservation(String memoryReservation) { - this.memoryReservation = memoryReservation; - } - - public String getMemoryLimit() { - return memoryLimit; - } - - public void setMemoryLimit(String memoryLimit) { - this.memoryLimit = memoryLimit; - } - - @OneToMany(mappedBy = "hardware", cascade = CascadeType.ALL, orphanRemoval = true) - public List getConstraints() { - if (constraints == null) { - constraints = new ArrayList<>(); - } - - return constraints; - } - - public void setConstraints(List constraints) { - this.constraints = constraints; - } - - @ElementCollection - public List getEnvironmentVariables() { - if (environmentVariables == null) { - environmentVariables = new ArrayList<>(); - } - - return environmentVariables; - } - - public void setEnvironmentVariables(List environmentVariables) { - this.environmentVariables = environmentVariables; - } - - @ElementCollection - public List getGenericResources() { - if (genericResources == null) { - genericResources = new ArrayList<>(); - } - - return genericResources; - } - - public void setGenericResources(List genericResources) { - this.genericResources = genericResources; - } - - @OneToOne - public HardwareConfigEntity getHardwareConfig() { - return hardwareConfig; - } - - public void setHardwareConfig(HardwareConfigEntity hardwareConfig) { - this.hardwareConfig = hardwareConfig; - } - - public static HardwareEntity fromPojo(Hardware pojo) { - HardwareEntity entity = new HardwareEntity(); - entity.update(pojo); - return entity; - } - - public Hardware toPojo() { - return Hardware.builder() - .name(getName()) - .cpuReservation(getCpuReservation()) - .cpuLimit(getCpuLimit()) - .memoryReservation(getMemoryReservation()) - .memoryLimit(getMemoryLimit()) - .constraints(getConstraints().stream().map(HardwareConstraintEntity::toPojo).collect(Collectors.toList())) - .environmentVariables(getEnvironmentVariables().stream().map(EnvironmentVariableEntity::toPojo).collect(Collectors.toList())) - .genericResources(getGenericResources().stream().map(GenericResourceEntity::toPojo).collect(Collectors.toList())) - .build(); - } - - public void update(Hardware pojo) { - setName(pojo.getName()); - setCpuReservation(pojo.getCpuReservation()); - setCpuLimit(pojo.getCpuLimit()); - setMemoryReservation(pojo.getMemoryReservation()); - setMemoryLimit(pojo.getMemoryLimit()); - - // remove old constraints, need to remove hardware reference from old constraints before clearing - getConstraints().forEach(c -> c.setHardware(null)); - getConstraints().clear(); - - // add new constraints - if (pojo.getConstraints() != null) { - getConstraints().addAll(pojo.getConstraints() - .stream() - .map(HardwareConstraintEntity::fromPojo) - .collect(Collectors.toList())); - getConstraints().forEach(c -> c.setHardware(this)); - } - - // remove old environment variables - getEnvironmentVariables().clear(); - - // add new environment variables - if (pojo.getEnvironmentVariables() != null) { - getEnvironmentVariables().addAll(pojo.getEnvironmentVariables() - .stream() - .map(EnvironmentVariableEntity::fromPojo) - .collect(Collectors.toList())); - } - - // remove old resources - getGenericResources().clear(); - - // add new resources - if (pojo.getGenericResources() != null) { - getGenericResources().addAll(pojo.getGenericResources() - .stream() - .map(GenericResourceEntity::fromPojo) - .collect(Collectors.toList())); - } - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/HardwareScopeEntity.java b/src/main/java/org/nrg/xnat/compute/entities/HardwareScopeEntity.java deleted file mode 100644 index 47c3e2d..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/HardwareScopeEntity.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.framework.constants.Scope; -import org.nrg.xnat.compute.models.HardwareScope; - -import javax.persistence.*; -import java.util.HashSet; -import java.util.Set; - -@Entity -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode -public class HardwareScopeEntity { - - private long id; - private String scope; - private boolean enabled; - private Set ids; - - @ToString.Exclude @EqualsAndHashCode.Exclude private HardwareConfigEntity hardwareConfig; - - @Id - @GeneratedValue - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - public boolean isEnabled() { - return enabled; - } - - public String getScope() { - return scope; - } - - public void setScope(String scope) { - this.scope = scope; - } - - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } - - @ElementCollection - public Set getIds() { - return ids; - } - - public void setIds(Set ids) { - this.ids = ids; - } - - @ManyToOne - public HardwareConfigEntity getHardwareConfig() { - return hardwareConfig; - } - - public void setHardwareConfig(HardwareConfigEntity hardwareConfig) { - this.hardwareConfig = hardwareConfig; - } - - /** - * Converts this entity to a pojo. - * @return The pojo. - */ - public HardwareScope toPojo() { - return HardwareScope.builder() - .scope(Scope.valueOf(getScope())) - .enabled(isEnabled()) - .ids(getIds()) - .build(); - } - - /** - * Updates this entity from the given pojo. - * @param pojo The pojo. - */ - public void update(final HardwareScope pojo) { - setScope(pojo.getScope().name()); - setEnabled(pojo.isEnabled()); - - if (getIds() == null) { - // This is a new entity, so we need to initialize the collection - setIds(new HashSet<>()); - } else { - // This is an existing entity, so we need to clear the collection - getIds().clear(); - } - - // add new ids - if (pojo.getIds() != null) { - getIds().addAll(pojo.getIds()); - } - } - - /** - * Creates a new entity from the given pojo. - * @param pojo The pojo. - * @return The entity. - */ - public static HardwareScopeEntity fromPojo(final HardwareScope pojo) { - final HardwareScopeEntity entity = new HardwareScopeEntity(); - entity.update(pojo); - return entity; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/entities/MountEntity.java b/src/main/java/org/nrg/xnat/compute/entities/MountEntity.java deleted file mode 100644 index 2c5d9f2..0000000 --- a/src/main/java/org/nrg/xnat/compute/entities/MountEntity.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.nrg.xnat.compute.entities; - -import lombok.*; -import org.nrg.xnat.compute.models.Mount; - -import javax.persistence.Embeddable; - -@Embeddable -@Builder -@AllArgsConstructor -@NoArgsConstructor -@ToString -@EqualsAndHashCode -public class MountEntity { - - private String volumeName; - private String localPath; - private String containerPath; - private boolean readOnly; - - public String getVolumeName() { - return volumeName; - } - - public void setVolumeName(String volumeName) { - this.volumeName = volumeName; - } - - public String getLocalPath() { - return localPath; - } - - public void setLocalPath(String localPath) { - this.localPath = localPath; - } - - public String getContainerPath() { - return containerPath; - } - - public void setContainerPath(String containerPath) { - this.containerPath = containerPath; - } - - public boolean isReadOnly() { - return readOnly; - } - - public void setReadOnly(boolean readOnly) { - this.readOnly = readOnly; - } - - public void update(Mount mount) { - setVolumeName(mount.getVolumeName()); - setLocalPath(mount.getLocalPath()); - setContainerPath(mount.getContainerPath()); - setReadOnly(mount.isReadOnly()); - } - - public Mount toPojo() { - return Mount.builder() - .volumeName(volumeName) - .localPath(localPath) - .containerPath(containerPath) - .readOnly(readOnly) - .build(); - } - - public static MountEntity fromPojo(Mount mount) { - final MountEntity entity = new MountEntity(); - entity.update(mount); - return entity; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/AccessScope.java b/src/main/java/org/nrg/xnat/compute/models/AccessScope.java deleted file mode 100644 index 09d5405..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/AccessScope.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.nrg.xnat.compute.models; - -import org.nrg.framework.constants.Scope; - -import java.util.Map; -import java.util.Set; - -public interface AccessScope { - - Scope getScope(); - - boolean isEnabled(); // is enabled for all ids - - Set getIds(); // ids that are enabled for this scope (if isEnabled is false) - - /** - * A scope/id combination is enabled if the scope is enabled for all ids or if the id is in the set of ids - * - * @param id The id to check - * @return Whether the scope/id combination is enabled - */ - default boolean isEnabledFor(String id) { - if (isEnabled()) { - return true; - } else { - return getIds().contains(id); - } - } - - /** - * Given the provided user execution scope, determine if the config is enabled for - * - * @param configRequiredAccessScopes The required access scopes for the config - * @param userExecutionScope The user's execution scope - * @return Whether the config is enabled for the provided execution scope - */ - static boolean isEnabledFor(Map configRequiredAccessScopes, Map userExecutionScope) { - for (Scope scope : Scope.values()) { - if (configRequiredAccessScopes.containsKey(scope)) { - AccessScope configRequiredAccessScope = configRequiredAccessScopes.get(scope); - if (!configRequiredAccessScope.isEnabledFor(userExecutionScope.get(scope))) { - return false; - } - } - } - return true; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironment.java b/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironment.java deleted file mode 100644 index ae4145b..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironment.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.nrg.xnat.compute.models; - -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class ComputeEnvironment { - - @ApiModelProperty(position = 0) private String name; - @ApiModelProperty(position = 1) private String image; - @ApiModelProperty(position = 2) private String command; - @ApiModelProperty(position = 3) private List environmentVariables; - @ApiModelProperty(position = 4) private List mounts; - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironmentConfig.java b/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironmentConfig.java deleted file mode 100644 index c92a681..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironmentConfig.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.nrg.xnat.compute.models; - -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; -import org.nrg.framework.constants.Scope; - -import java.util.Map; -import java.util.Set; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class ComputeEnvironmentConfig { - - @ApiModelProperty(position = 0) private Long id; - @ApiModelProperty(position = 1) private Set configTypes; - @ApiModelProperty(position = 2) private ComputeEnvironment computeEnvironment; - @ApiModelProperty(position = 3) private Map scopes; - @ApiModelProperty(position = 4) private ComputeEnvironmentHardwareOptions hardwareOptions; - - public enum ConfigType { - JUPYTERHUB, - CONTAINER_SERVICE, - GENERAL - } -} diff --git a/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironmentHardwareOptions.java b/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironmentHardwareOptions.java deleted file mode 100644 index adf57fe..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironmentHardwareOptions.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.nrg.xnat.compute.models; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.Set; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class ComputeEnvironmentHardwareOptions { - - private boolean allowAllHardware; - private Set hardwareConfigs; - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironmentScope.java b/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironmentScope.java deleted file mode 100644 index a1833ef..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/ComputeEnvironmentScope.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.nrg.xnat.compute.models; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; -import org.nrg.framework.constants.Scope; - -import java.util.Set; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class ComputeEnvironmentScope implements AccessScope { - - private Scope scope; - private boolean enabled; // Whether the scope is enabled for all ids or only for the ids in the set - private Set ids; // The set of ids that are enabled for this scope (if isEnabled is false) - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/Constraint.java b/src/main/java/org/nrg/xnat/compute/models/Constraint.java deleted file mode 100644 index 1e27938..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/Constraint.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.nrg.xnat.compute.models; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class Constraint { - - public enum Operator { - IN, - NOT_IN, - } - - private String key; - private Set values; - private Operator operator; - - /** - * Convert to list of Docker constraint strings. Example: ["key==value1", "key==value2"] - * @return List of Docker constraint strings - */ - public List toList() { - List list = new ArrayList<>(); - - values.forEach((value) -> { - final String operatorString; - - switch (operator) { - case IN: - operatorString = "=="; - break; - case NOT_IN: - operatorString = "!="; - break; - default: - throw new RuntimeException("Unknown constraint operator: " + operator); - } - - list.add(key + operatorString + value); - }); - - return list; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/ConstraintConfig.java b/src/main/java/org/nrg/xnat/compute/models/ConstraintConfig.java deleted file mode 100644 index 9fbcbe2..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/ConstraintConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.nrg.xnat.compute.models; - -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; -import org.nrg.framework.constants.Scope; - -import java.util.Map; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class ConstraintConfig { - - @ApiModelProperty(position = 0) private Long id; - @ApiModelProperty(position = 1) private Constraint constraint; - @ApiModelProperty(position = 2) private Map scopes; - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/ConstraintScope.java b/src/main/java/org/nrg/xnat/compute/models/ConstraintScope.java deleted file mode 100644 index fc9678f..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/ConstraintScope.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.nrg.xnat.compute.models; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; -import org.nrg.framework.constants.Scope; - -import java.util.Set; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class ConstraintScope implements AccessScope { - - private Scope scope; - private boolean enabled; // Whether the scope is enabled for all ids or only for the ids in the set - private Set ids; // The set of ids that are enabled for this scope (if isEnabled is false) - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/EnvironmentVariable.java b/src/main/java/org/nrg/xnat/compute/models/EnvironmentVariable.java deleted file mode 100644 index d605fa6..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/EnvironmentVariable.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.nrg.xnat.compute.models; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class EnvironmentVariable { - - private String key; - private String value; - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/GenericResource.java b/src/main/java/org/nrg/xnat/compute/models/GenericResource.java deleted file mode 100644 index c2a6995..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/GenericResource.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.nrg.xnat.compute.models; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class GenericResource { - - private String name; - private String value; - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/Hardware.java b/src/main/java/org/nrg/xnat/compute/models/Hardware.java deleted file mode 100644 index a68e442..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/Hardware.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.nrg.xnat.compute.models; - -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class Hardware { - - @ApiModelProperty(position = 0) private String name; - @ApiModelProperty(position = 1) private Double cpuLimit; - @ApiModelProperty(position = 2) private Double cpuReservation; - @ApiModelProperty(position = 3) private String memoryLimit; - @ApiModelProperty(position = 4) private String memoryReservation; - @ApiModelProperty(position = 5) private List constraints; - @ApiModelProperty(position = 6) private List environmentVariables; - @ApiModelProperty(position = 7) private List genericResources; - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/HardwareConfig.java b/src/main/java/org/nrg/xnat/compute/models/HardwareConfig.java deleted file mode 100644 index c9eaf68..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/HardwareConfig.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.nrg.xnat.compute.models; - -import io.swagger.annotations.ApiModelProperty; -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; -import org.nrg.framework.constants.Scope; - -import java.util.Map; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class HardwareConfig { - - @ApiModelProperty(position = 0) private Long id; - @ApiModelProperty(position = 1) private Hardware hardware; - @ApiModelProperty(position = 2) private Map scopes; - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/HardwareScope.java b/src/main/java/org/nrg/xnat/compute/models/HardwareScope.java deleted file mode 100644 index 288c767..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/HardwareScope.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.nrg.xnat.compute.models; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; -import org.nrg.framework.constants.Scope; - -import java.util.Set; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class HardwareScope implements AccessScope { - - private Scope scope; - private boolean enabled; // Whether the scope is enabled for all ids or only for the ids in the set - private Set ids; // The set of ids that are enabled for this scope (if isEnabled is false) - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/JobTemplate.java b/src/main/java/org/nrg/xnat/compute/models/JobTemplate.java deleted file mode 100644 index 85eee12..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/JobTemplate.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.nrg.xnat.compute.models; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class JobTemplate { - - private ComputeEnvironment computeEnvironment; - private Hardware hardware; - private List constraints; - -} diff --git a/src/main/java/org/nrg/xnat/compute/models/Mount.java b/src/main/java/org/nrg/xnat/compute/models/Mount.java deleted file mode 100644 index 8c3c15c..0000000 --- a/src/main/java/org/nrg/xnat/compute/models/Mount.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.nrg.xnat.compute.models; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Builder -@AllArgsConstructor -@NoArgsConstructor -@Data -public class Mount { - - private String volumeName; - private String localPath; - private String containerPath; - private boolean readOnly; - -} diff --git a/src/main/java/org/nrg/xnat/compute/repositories/ComputeEnvironmentConfigDao.java b/src/main/java/org/nrg/xnat/compute/repositories/ComputeEnvironmentConfigDao.java deleted file mode 100644 index 21c9de0..0000000 --- a/src/main/java/org/nrg/xnat/compute/repositories/ComputeEnvironmentConfigDao.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.nrg.xnat.compute.repositories; - -import lombok.extern.slf4j.Slf4j; -import org.hibernate.Criteria; -import org.hibernate.Hibernate; -import org.hibernate.SessionFactory; -import org.hibernate.criterion.Restrictions; -import org.nrg.framework.orm.hibernate.AbstractHibernateDAO; -import org.nrg.xnat.compute.entities.ComputeEnvironmentConfigEntity; -import org.nrg.xnat.compute.entities.ComputeEnvironmentScopeEntity; -import org.nrg.xnat.compute.entities.HardwareConfigEntity; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Repository; - -import java.util.Collections; -import java.util.List; - -@Repository -@Slf4j -public class ComputeEnvironmentConfigDao extends AbstractHibernateDAO { - - private final HardwareConfigDao hardwareConfigDao; - - // For testing - public ComputeEnvironmentConfigDao(final SessionFactory sessionFactory, - final HardwareConfigDao hardwareConfigDao) { - super(sessionFactory); - this.hardwareConfigDao = hardwareConfigDao; - } - - @Autowired - public ComputeEnvironmentConfigDao(HardwareConfigDao hardwareConfigDao) { - this.hardwareConfigDao = hardwareConfigDao; - } - - /** - * Initializes the entity, loading all collections and proxies. - * @param entity The entity to initialize. - */ - @Override - public void initialize(final ComputeEnvironmentConfigEntity entity) { - if (entity == null) { - return; - } - - Hibernate.initialize(entity); - - Hibernate.initialize(entity.getConfigTypes()); - - Hibernate.initialize(entity.getComputeEnvironment()); - if (entity.getComputeEnvironment() != null) { - Hibernate.initialize(entity.getComputeEnvironment().getEnvironmentVariables()); - Hibernate.initialize(entity.getComputeEnvironment().getMounts()); - } - - Hibernate.initialize(entity.getScopes()); - if (entity.getScopes() != null) { - entity.getScopes().forEach((scope, computeEnvironmentScopeEntity) -> { - initialize(computeEnvironmentScopeEntity); - }); - } - - Hibernate.initialize(entity.getHardwareOptions()); - if (entity.getHardwareOptions() != null) { - Hibernate.initialize(entity.getHardwareOptions().getHardwareConfigs()); - - if (entity.getHardwareOptions().getHardwareConfigs() != null) { - for (HardwareConfigEntity hardwareConfig : entity.getHardwareOptions().getHardwareConfigs()) { - hardwareConfigDao.initialize(hardwareConfig); - } - } - } - } - - /** - * Initializes the entity, loading all collections and proxies. - * @param entity The entity to initialize. - */ - public void initialize(ComputeEnvironmentScopeEntity entity) { - if (entity == null) { - return; - } - - Hibernate.initialize(entity); - Hibernate.initialize(entity.getIds()); - } - - /** - * Finds all compute environment configs that have the specified type. - * @param type The type to search for. - * @return The list of compute environment configs that have the specified type. - */ - public List findByType(String type) { - // Need to use a criteria query because the configTypes field is a collection. - Criteria criteria = getSession().createCriteria(ComputeEnvironmentConfigEntity.class) - .createCriteria("configTypes") - .add(Restrictions.eq("elements", type)); - - List entities = criteria.list(); - - if (entities == null) { - return Collections.emptyList(); - } - - for (ComputeEnvironmentConfigEntity entity : entities) { - initialize(entity); - } - - return entities; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/repositories/ConstraintConfigDao.java b/src/main/java/org/nrg/xnat/compute/repositories/ConstraintConfigDao.java deleted file mode 100644 index 46ccb97..0000000 --- a/src/main/java/org/nrg/xnat/compute/repositories/ConstraintConfigDao.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.nrg.xnat.compute.repositories; - -import lombok.extern.slf4j.Slf4j; -import org.hibernate.Hibernate; -import org.hibernate.SessionFactory; -import org.nrg.framework.orm.hibernate.AbstractHibernateDAO; -import org.nrg.xnat.compute.entities.ConstraintConfigEntity; -import org.nrg.xnat.compute.entities.ConstraintEntity; -import org.nrg.xnat.compute.entities.ConstraintScopeEntity; -import org.springframework.stereotype.Repository; - -@Repository -@Slf4j -public class ConstraintConfigDao extends AbstractHibernateDAO { - - // For testing - public ConstraintConfigDao(final SessionFactory sessionFactory) { - super(sessionFactory); - } - - /** - * Initialize the constraint config entity. - * @param entity The entity to initialize. - */ - @Override - public void initialize(final ConstraintConfigEntity entity) { - if (entity == null) { - return; - } - - initialize(entity.getConstraint()); - - Hibernate.initialize(entity.getScopes()); - if (entity.getScopes() != null) { - entity.getScopes().forEach((scope, constraintScopeEntity) -> { - initialize(constraintScopeEntity); - }); - } - } - - /** - * Initialize the constraint entity. - * @param entity The entity to initialize. - */ - void initialize(final ConstraintEntity entity) { - if (entity == null) { - return; - } - - Hibernate.initialize(entity); - if (entity.getConstraintValues() != null) { - Hibernate.initialize(entity.getConstraintValues()); - } - } - - /** - * Initialize the constraint scope entity. - * @param entity The entity to initialize. - */ - public void initialize(ConstraintScopeEntity entity) { - if (entity == null) { - return; - } - - Hibernate.initialize(entity); - Hibernate.initialize(entity.getIds()); - } -} diff --git a/src/main/java/org/nrg/xnat/compute/repositories/HardwareConfigDao.java b/src/main/java/org/nrg/xnat/compute/repositories/HardwareConfigDao.java deleted file mode 100644 index b9ef99c..0000000 --- a/src/main/java/org/nrg/xnat/compute/repositories/HardwareConfigDao.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.nrg.xnat.compute.repositories; - -import lombok.extern.slf4j.Slf4j; -import org.hibernate.Hibernate; -import org.hibernate.SessionFactory; -import org.nrg.framework.orm.hibernate.AbstractHibernateDAO; -import org.nrg.xnat.compute.entities.HardwareConfigEntity; -import org.nrg.xnat.compute.entities.HardwareConstraintEntity; -import org.nrg.xnat.compute.entities.HardwareEntity; -import org.nrg.xnat.compute.entities.HardwareScopeEntity; -import org.springframework.stereotype.Repository; - -@Repository -@Slf4j -public class HardwareConfigDao extends AbstractHibernateDAO { - - // For testing - public HardwareConfigDao(final SessionFactory sessionFactory) { - super(sessionFactory); - } - - /** - * Initializes the entity, loading all collections and proxies. - * @param entity The entity to initialize. - */ - @Override - public void initialize(final HardwareConfigEntity entity) { - if (entity == null) { - return; - } - - Hibernate.initialize(entity); - - Hibernate.initialize(entity.getScopes()); - if (entity.getScopes() != null) { - entity.getScopes().forEach((scope, hardwareScopeEntity) -> { - initialize(hardwareScopeEntity); - }); - } - - Hibernate.initialize(entity.getHardware()); - if (entity.getHardware() != null) { - initialize(entity.getHardware()); - } - - if (entity.getComputeEnvironmentHardwareOptions() != null) { - Hibernate.initialize(entity.getComputeEnvironmentHardwareOptions()); - } - } - - /** - * Initializes the entity, loading all collections and proxies. - * @param entity The entity to initialize. - */ - public void initialize(HardwareScopeEntity entity) { - if (entity == null) { - return; - } - - Hibernate.initialize(entity); - Hibernate.initialize(entity.getIds()); - } - - /** - * Initializes the entity, loading all collections and proxies. - * @param entity The entity to initialize. - */ - public void initialize(final HardwareEntity entity) { - if (entity == null) { - return; - } - - Hibernate.initialize(entity); - - Hibernate.initialize(entity.getConstraints()); - if (entity.getConstraints() != null) { - for (final HardwareConstraintEntity constraint : entity.getConstraints()) { - Hibernate.initialize(constraint.getConstraintValues()); - } - } - - Hibernate.initialize(entity.getEnvironmentVariables()); - Hibernate.initialize(entity.getGenericResources()); - } -} diff --git a/src/main/java/org/nrg/xnat/compute/rest/ComputeEnvironmentConfigsApi.java b/src/main/java/org/nrg/xnat/compute/rest/ComputeEnvironmentConfigsApi.java deleted file mode 100644 index 2f567b1..0000000 --- a/src/main/java/org/nrg/xnat/compute/rest/ComputeEnvironmentConfigsApi.java +++ /dev/null @@ -1,143 +0,0 @@ -package org.nrg.xnat.compute.rest; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import org.nrg.framework.annotations.XapiRestController; -import org.nrg.framework.constants.Scope; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xapi.rest.AbstractXapiRestController; -import org.nrg.xapi.rest.XapiRequestMapping; -import org.nrg.xdat.security.services.RoleHolder; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.nrg.xnat.compute.models.ComputeEnvironmentConfig; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.*; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.nrg.xdat.security.helpers.AccessLevel.Admin; -import static org.nrg.xdat.security.helpers.AccessLevel.Read; -import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; - -@Api("ComputeEnvironmentConfigs REST API") -@XapiRestController -@RequestMapping(value = "/compute-environment-configs") -public class ComputeEnvironmentConfigsApi extends AbstractXapiRestController { - - private final ComputeEnvironmentConfigService computeEnvironmentConfigService; - - @Autowired - public ComputeEnvironmentConfigsApi(final UserManagementServiceI userManagementService, - final RoleHolder roleHolder, - final ComputeEnvironmentConfigService computeEnvironmentConfigService) { - super(userManagementService, roleHolder); - this.computeEnvironmentConfigService = computeEnvironmentConfigService; - } - - @ApiOperation(value = "Get all compute environment configs or all compute environment configs for a given type.", response = ComputeEnvironmentConfig.class) - @ApiResponses({ - @ApiResponse(code = 200, message = "Compute environment configs successfully retrieved."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @XapiRequestMapping(value = "", produces = APPLICATION_JSON_VALUE, method = RequestMethod.GET, restrictTo = Admin) - public List getAll(@RequestParam(value = "type", required = false) final ComputeEnvironmentConfig.ConfigType type) { - if (type != null) { - return computeEnvironmentConfigService.getByType(type); - } else { - return computeEnvironmentConfigService.getAll(); - } - } - - @ApiOperation(value = "Get a compute environment config.", response = ComputeEnvironmentConfig.class) - @ApiResponses({ - @ApiResponse(code = 200, message = "Compute environment config successfully retrieved."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 404, message = "Compute environment config not found."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @XapiRequestMapping(value = "/{id}", produces = APPLICATION_JSON_VALUE, method = RequestMethod.GET, restrictTo = Admin) - public ComputeEnvironmentConfig get(@PathVariable("id") final Long id) throws NotFoundException { - return computeEnvironmentConfigService.retrieve(id) - .orElseThrow(() -> new NotFoundException("Compute environment config not found.")); - } - - @ApiOperation(value = "Create a compute environment config.", response = ComputeEnvironmentConfig.class) - @ApiResponses({ - @ApiResponse(code = 201, message = "Compute environment config successfully created."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @ResponseStatus(HttpStatus.CREATED) - @XapiRequestMapping(value = "", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE, method = RequestMethod.POST, restrictTo = Admin) - public ComputeEnvironmentConfig create(@RequestBody final ComputeEnvironmentConfig computeEnvironmentConfig) { - return computeEnvironmentConfigService.create(computeEnvironmentConfig); - } - - @ApiOperation(value = "Update a compute environment config.", response = ComputeEnvironmentConfig.class) - @ApiResponses({ - @ApiResponse(code = 200, message = "Compute environment config successfully updated."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 404, message = "Compute environment config not found."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @XapiRequestMapping(value = "/{id}", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE, method = RequestMethod.PUT, restrictTo = Admin) - public ComputeEnvironmentConfig update(@PathVariable("id") final Long id, - @RequestBody final ComputeEnvironmentConfig computeEnvironmentConfig) throws NotFoundException { - if (!id.equals(computeEnvironmentConfig.getId())) { - throw new IllegalArgumentException("The ID in the path must match the ID in the body."); - } - - return computeEnvironmentConfigService.update(computeEnvironmentConfig); - } - - @ApiOperation(value = "Delete a compute environment config.") - @ApiResponses({ - @ApiResponse(code = 204, message = "Compute environment config successfully deleted."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 404, message = "Compute environment config not found."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @ResponseStatus(HttpStatus.NO_CONTENT) - @XapiRequestMapping(value = "/{id}", method = RequestMethod.DELETE, restrictTo = Admin) - public void delete(@PathVariable("id") final Long id) throws NotFoundException { - computeEnvironmentConfigService.delete(id); - } - - @ApiOperation(value = "Get all available compute environment configs for the provided execution scope.", response = ComputeEnvironmentConfig.class, responseContainer = "List") - @ApiResponses({ - @ApiResponse(code = 200, message = "Compute environment configs successfully retrieved."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @XapiRequestMapping(value = "/available", produces = APPLICATION_JSON_VALUE, method = RequestMethod.GET, restrictTo = Read) - public List getAvailable(@RequestParam final Map params) { - ComputeEnvironmentConfig.ConfigType type = null; - - // If the type is specified, remove it from the params map so it doesn't get used as an execution scope. - if (params.containsKey("type")) { - type = ComputeEnvironmentConfig.ConfigType.valueOf(params.get("type")); - params.remove("type"); - } - - // Get the execution scope from the params map. - Map executionScope = params.entrySet().stream() - .filter(entry -> Scope.getCodes().contains(entry.getKey())) - .collect(Collectors.toMap(entry -> Scope.getScope(entry.getKey()), Map.Entry::getValue)); - - return computeEnvironmentConfigService.getAvailable(type, executionScope); - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/rest/ConstraintConfigsApi.java b/src/main/java/org/nrg/xnat/compute/rest/ConstraintConfigsApi.java deleted file mode 100644 index 50b711d..0000000 --- a/src/main/java/org/nrg/xnat/compute/rest/ConstraintConfigsApi.java +++ /dev/null @@ -1,115 +0,0 @@ -package org.nrg.xnat.compute.rest; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import org.nrg.framework.annotations.XapiRestController; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xapi.rest.AbstractXapiRestController; -import org.nrg.xapi.rest.XapiRequestMapping; -import org.nrg.xdat.security.services.RoleHolder; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.nrg.xnat.compute.models.ConstraintConfig; -import org.nrg.xnat.compute.services.ConstraintConfigService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseStatus; - -import java.util.List; - -import static org.nrg.xdat.security.helpers.AccessLevel.Admin; -import static org.springframework.http.HttpStatus.CREATED; -import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; -import static org.springframework.web.bind.annotation.RequestMethod.*; - -@Api("Constraint Configs REST API") -@XapiRestController -@RequestMapping(value = "/constraint-configs") -public class ConstraintConfigsApi extends AbstractXapiRestController { - - private final ConstraintConfigService constraintConfigService; - - @Autowired - public ConstraintConfigsApi(final UserManagementServiceI userManagementService, - final RoleHolder roleHolder, - final ConstraintConfigService constraintConfigService) { - super(userManagementService, roleHolder); - this.constraintConfigService = constraintConfigService; - } - - @ApiOperation(value = "Get a constraint config.", response = ConstraintConfig.class) - @ApiResponses({ - @ApiResponse(code = 200, message = "Placement constraint config successfully retrieved."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 404, message = "Placement constraint config not found."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @XapiRequestMapping(value = "/{id}", produces = APPLICATION_JSON_VALUE, method = GET, restrictTo = Admin) - public ConstraintConfig get(@PathVariable final Long id) throws NotFoundException { - return constraintConfigService.retrieve(id) - .orElseThrow(() -> new NotFoundException("No placement constraint config found with ID " + id)); - } - - @ApiOperation(value = "Get all constraint configs.", response = ConstraintConfig.class, responseContainer = "List") - @ApiResponses({ - @ApiResponse(code = 200, message = "Placement constraint configs successfully retrieved."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @XapiRequestMapping(value = "", produces = APPLICATION_JSON_VALUE, method = GET, restrictTo = Admin) - public List getAll() { - return constraintConfigService.getAll(); - } - - @ApiOperation(value = "Create a constraint config.", response = ConstraintConfig.class) - @ApiResponses({ - @ApiResponse(code = 201, message = "Placement constraint config successfully created."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @ResponseStatus(CREATED) - @XapiRequestMapping(value = "", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE, method = POST, restrictTo = Admin) - public ConstraintConfig create(@RequestBody final ConstraintConfig constraintConfig) { - return constraintConfigService.create(constraintConfig); - } - - @ApiOperation(value = "Update a constraint config.", response = ConstraintConfig.class) - @ApiResponses({ - @ApiResponse(code = 200, message = "Placement constraint config successfully updated."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 404, message = "Placement constraint config not found."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @XapiRequestMapping(value = "/{id}", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE, method = PUT, restrictTo = Admin) - public ConstraintConfig update(@PathVariable final Long id, - @RequestBody final ConstraintConfig constraintConfig) throws NotFoundException { - if (!id.equals(constraintConfig.getId())) { - throw new IllegalArgumentException("Placement constraint config ID in path does not match ID in body."); - } - - return constraintConfigService.update(constraintConfig); - } - - @ApiOperation(value = "Delete a constraint config.") - @ApiResponses({ - @ApiResponse(code = 204, message = "Placement constraint config successfully deleted."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 404, message = "Placement constraint config not found."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @ResponseStatus(HttpStatus.NO_CONTENT) - @XapiRequestMapping(value = "/{id}", method = DELETE, restrictTo = Admin) - public void delete(@PathVariable final Long id) throws NotFoundException { - constraintConfigService.delete(id); - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/rest/HardwareConfigsApi.java b/src/main/java/org/nrg/xnat/compute/rest/HardwareConfigsApi.java deleted file mode 100644 index 60af77e..0000000 --- a/src/main/java/org/nrg/xnat/compute/rest/HardwareConfigsApi.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.nrg.xnat.compute.rest; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiResponse; -import io.swagger.annotations.ApiResponses; -import org.nrg.framework.annotations.XapiRestController; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xapi.rest.AbstractXapiRestController; -import org.nrg.xapi.rest.XapiRequestMapping; -import org.nrg.xdat.security.services.RoleHolder; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.nrg.xnat.compute.models.HardwareConfig; -import org.nrg.xnat.compute.services.HardwareConfigService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseStatus; - -import java.util.List; - -import static org.nrg.xdat.security.helpers.AccessLevel.Admin; -import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; -import static org.springframework.web.bind.annotation.RequestMethod.*; - -@Api("Hardware Configs REST API") -@XapiRestController -@RequestMapping(value = "/hardware-configs") -public class HardwareConfigsApi extends AbstractXapiRestController { - - private final HardwareConfigService hardwareConfigService; - - @Autowired - public HardwareConfigsApi(final UserManagementServiceI userManagementService, - final RoleHolder roleHolder, - final HardwareConfigService hardwareConfigService) { - super(userManagementService, roleHolder); - this.hardwareConfigService = hardwareConfigService; - } - - @ApiOperation(value = "Get a hardware config.", response = HardwareConfig.class) - @ApiResponses({ - @ApiResponse(code = 200, message = "Hardware config successfully retrieved."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 404, message = "Hardware config not found."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @XapiRequestMapping(value = "/{id}", produces = APPLICATION_JSON_VALUE, method = GET, restrictTo = Admin) - public HardwareConfig get(@PathVariable("id") final Long id) throws NotFoundException { - return hardwareConfigService.retrieve(id).orElseThrow(() -> new NotFoundException("No hardware config found for ID " + id)); - } - - @ApiOperation(value = "Get all hardware configs.", response = HardwareConfig.class) - @ApiResponses({ - @ApiResponse(code = 200, message = "Hardware configs successfully retrieved."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @XapiRequestMapping(value = "", produces = APPLICATION_JSON_VALUE, method = GET, restrictTo = Admin) - public List getAll() { - return hardwareConfigService.retrieveAll(); - } - - @ApiOperation(value = "Create a hardware config.", response = HardwareConfig.class) - @ApiResponses({ - @ApiResponse(code = 201, message = "Hardware config successfully created."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @ResponseStatus(HttpStatus.CREATED) - @XapiRequestMapping(value = "", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE, method = POST, restrictTo = Admin) - public HardwareConfig create(@RequestBody final HardwareConfig hardwareConfig) { - return hardwareConfigService.create(hardwareConfig); - } - - @ApiOperation(value = "Update a hardware config.", response = HardwareConfig.class) - @ApiResponses({ - @ApiResponse(code = 200, message = "Hardware config successfully updated."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 404, message = "Hardware config not found."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @XapiRequestMapping(value = "/{id}", consumes = APPLICATION_JSON_VALUE, method = PUT, restrictTo = Admin) - public HardwareConfig update(@PathVariable("id") final Long id, - @RequestBody final HardwareConfig hardwareConfig) throws NotFoundException { - if (!id.equals(hardwareConfig.getId())) { - throw new IllegalArgumentException("The hardware config ID in the path must match the ID in the body."); - } - return hardwareConfigService.update(hardwareConfig); - } - - @ApiOperation(value = "Delete a hardware config.") - @ApiResponses({ - @ApiResponse(code = 204, message = "Hardware config successfully deleted."), - @ApiResponse(code = 401, message = "Must be authenticated to access the XNAT REST API."), - @ApiResponse(code = 403, message = "Not authorized."), - @ApiResponse(code = 404, message = "Hardware config not found."), - @ApiResponse(code = 500, message = "Unexpected error") - }) - @ResponseStatus(HttpStatus.NO_CONTENT) - @XapiRequestMapping(value = "/{id}", method = DELETE, restrictTo = Admin) - public void delete(@PathVariable("id") final Long id) throws NotFoundException { - hardwareConfigService.delete(id); - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/ComputeEnvironmentConfigEntityService.java b/src/main/java/org/nrg/xnat/compute/services/ComputeEnvironmentConfigEntityService.java deleted file mode 100644 index 9e19830..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/ComputeEnvironmentConfigEntityService.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.nrg.xnat.compute.services; - -import org.nrg.framework.orm.hibernate.BaseHibernateService; -import org.nrg.xnat.compute.entities.ComputeEnvironmentConfigEntity; -import org.nrg.xnat.compute.models.ComputeEnvironmentConfig; - -import java.util.List; - -public interface ComputeEnvironmentConfigEntityService extends BaseHibernateService { - - void addHardwareConfigEntity(Long computeEnvironmentConfigId, Long hardwareConfigId); - void removeHardwareConfigEntity(Long computeEnvironmentConfigId, Long hardwareConfigId); - List findByType(ComputeEnvironmentConfig.ConfigType type); - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/ComputeEnvironmentConfigService.java b/src/main/java/org/nrg/xnat/compute/services/ComputeEnvironmentConfigService.java deleted file mode 100644 index 829b8eb..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/ComputeEnvironmentConfigService.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.nrg.xnat.compute.services; - -import org.nrg.framework.constants.Scope; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xnat.compute.models.ComputeEnvironmentConfig; - -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public interface ComputeEnvironmentConfigService { - - boolean exists(Long id); - Optional retrieve(Long id); - List getAll(); - List getByType(ComputeEnvironmentConfig.ConfigType type); - List getAvailable(Map executionScope); - List getAvailable(ComputeEnvironmentConfig.ConfigType type, Map executionScope); - boolean isAvailable(Long id, Map executionScope); - ComputeEnvironmentConfig create(ComputeEnvironmentConfig computeEnvironmentConfig); - ComputeEnvironmentConfig update(ComputeEnvironmentConfig computeEnvironmentConfig) throws NotFoundException; - void delete(Long id) throws NotFoundException; - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/ConstraintConfigEntityService.java b/src/main/java/org/nrg/xnat/compute/services/ConstraintConfigEntityService.java deleted file mode 100644 index 4adcd2b..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/ConstraintConfigEntityService.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.nrg.xnat.compute.services; - -import org.nrg.framework.orm.hibernate.BaseHibernateService; -import org.nrg.xnat.compute.entities.ConstraintConfigEntity; - -public interface ConstraintConfigEntityService extends BaseHibernateService { - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/ConstraintConfigService.java b/src/main/java/org/nrg/xnat/compute/services/ConstraintConfigService.java deleted file mode 100644 index fe0c8f2..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/ConstraintConfigService.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.nrg.xnat.compute.services; - -import org.nrg.framework.constants.Scope; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xnat.compute.models.ConstraintConfig; - -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public interface ConstraintConfigService { - - Optional retrieve(Long id); - List getAll(); - List getAvailable(Map executionScope); - ConstraintConfig create(ConstraintConfig config); - ConstraintConfig update(ConstraintConfig config) throws NotFoundException; - void delete(Long id); - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/HardwareConfigEntityService.java b/src/main/java/org/nrg/xnat/compute/services/HardwareConfigEntityService.java deleted file mode 100644 index de8aa74..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/HardwareConfigEntityService.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.nrg.xnat.compute.services; - -import org.nrg.framework.orm.hibernate.BaseHibernateService; -import org.nrg.xnat.compute.entities.HardwareConfigEntity; - -public interface HardwareConfigEntityService extends BaseHibernateService { - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/HardwareConfigService.java b/src/main/java/org/nrg/xnat/compute/services/HardwareConfigService.java deleted file mode 100644 index 64b0b9a..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/HardwareConfigService.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.nrg.xnat.compute.services; - -import org.nrg.framework.constants.Scope; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xnat.compute.models.HardwareConfig; - -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public interface HardwareConfigService { - - boolean exists(Long id); - Optional retrieve(Long id); - List retrieveAll(); - HardwareConfig create(HardwareConfig hardwareConfig); - HardwareConfig update(HardwareConfig hardwareConfig) throws NotFoundException; - void delete(Long id) throws NotFoundException; - boolean isAvailable(Long id, Map executionScope); - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/JobTemplateService.java b/src/main/java/org/nrg/xnat/compute/services/JobTemplateService.java deleted file mode 100644 index 9e1f3da..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/JobTemplateService.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.nrg.xnat.compute.services; - -import org.nrg.framework.constants.Scope; -import org.nrg.xnat.compute.models.JobTemplate; - -import java.util.Map; - -public interface JobTemplateService { - - boolean isAvailable(Long computeEnvironmentConfigId, Long hardwareConfigId, Map executionScope); - JobTemplate resolve(Long computeEnvironmentConfigId, Long hardwareConfigId, Map executionScope); - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/impl/DefaultComputeEnvironmentConfigService.java b/src/main/java/org/nrg/xnat/compute/services/impl/DefaultComputeEnvironmentConfigService.java deleted file mode 100644 index 048ce91..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/impl/DefaultComputeEnvironmentConfigService.java +++ /dev/null @@ -1,389 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.nrg.framework.constants.Scope; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xnat.compute.entities.ComputeEnvironmentConfigEntity; -import org.nrg.xnat.compute.entities.HardwareConfigEntity; -import org.nrg.xnat.compute.models.*; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigEntityService; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigService; -import org.nrg.xnat.compute.services.HardwareConfigEntityService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.*; -import java.util.stream.Collectors; - -@Service -@Slf4j -public class DefaultComputeEnvironmentConfigService implements ComputeEnvironmentConfigService { - - private final ComputeEnvironmentConfigEntityService computeEnvironmentConfigEntityService; - private final HardwareConfigEntityService hardwareConfigEntityService; - - @Autowired - public DefaultComputeEnvironmentConfigService(final ComputeEnvironmentConfigEntityService computeEnvironmentConfigEntityService, - final HardwareConfigEntityService hardwareConfigEntityService) { - this.computeEnvironmentConfigEntityService = computeEnvironmentConfigEntityService; - this.hardwareConfigEntityService = hardwareConfigEntityService; - } - - /** - * Checks if a ComputeEnvironmentConfig with the given ID exists. - * - * @param id The ID of the ComputeEnvironmentConfig to check for. - * @return True if a ComputeEnvironmentConfig with the given ID exists, false otherwise. - */ - @Override - public boolean exists(Long id) { - return computeEnvironmentConfigEntityService.exists("id", id); - } - - /** - * Gets a ComputeEnvironmentConfig by its ID. - * - * @param id The ID of the ComputeEnvironmentConfig to retrieve. - * @return The ComputeEnvironmentConfig with the given ID, if it exists or else an empty Optional. - */ - @Override - public Optional retrieve(Long id) { - ComputeEnvironmentConfigEntity entity = computeEnvironmentConfigEntityService.retrieve(id); - return Optional.ofNullable(entity) - .map(ComputeEnvironmentConfigEntity::toPojo); - } - - /** - * Get all ComputeEnvironmentConfigs. - * - * @return A list of all ComputeEnvironmentConfigs. - */ - @Override - public List getAll() { - return computeEnvironmentConfigEntityService - .getAll() - .stream() - .map(ComputeEnvironmentConfigEntity::toPojo) - .collect(Collectors.toList()); - } - - /** - * Creates a new ComputeEnvironmentConfig. - * - * @param type The type of the ComputeEnvironmentConfig to create. - * @return The newly created ComputeEnvironmentConfig. - */ - @Override - public List getByType(ComputeEnvironmentConfig.ConfigType type) { - return computeEnvironmentConfigEntityService - .findByType(type) - .stream() - .map(ComputeEnvironmentConfigEntity::toPojo) - .collect(Collectors.toList()); - } - - /** - * Get all ComputeEnvironmentConfigs that are available to the provided execution scope. A config is available - * provided the execution scope contains all the required access scopes of the config and each scope/id combination - * is enabled. - * - * @param executionScope The execution scope to check availability for. - * Example {Scope.Site: "", Scope.Project: "Project1", Scope.User: "User1"} - * @return A list of ComputeEnvironmentConfigs that are available for the provided execution scope. - */ - @Override - public List getAvailable(Map executionScope) { - return getAvailable(null, executionScope); - } - - /** - * Get the ComputeEnvironmentConfigs of the given type that are available to the provided execution scope. A config - * is available provided the execution scope contains all the required access scopes of the config and each scope/id - * combination is enabled. - * - * @param type The type of the ComputeEnvironmentConfig to get. If null, all types are returned. - * @param executionScope The execution scope to check availability for. - * Example {Scope.Site: "", Scope.Project: "Project1", Scope.User: "User1", Scope.DataType: "xnat:mrSessionData"} - * @return A list of ComputeEnvironmentConfigs that are available for the provided requestedScope. - */ - @Override - public List getAvailable(ComputeEnvironmentConfig.ConfigType type, Map executionScope) { - List all; - - if (type == null) { - all = getAll(); - } else { - all = getByType(type); - } - - final List available = all.stream().filter(computeEnvironmentConfig -> { - Map requiredScopes = computeEnvironmentConfig.getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - return AccessScope.isEnabledFor(requiredScopes, executionScope); - }).collect(Collectors.toList()); - - available.forEach(computeEnvironmentConfig -> { - // Filter out any hardware configs that are not available to the execution scope - final Set hardwareConfigs = computeEnvironmentConfig.getHardwareOptions().getHardwareConfigs(); - final Set availableHardware = hardwareConfigs.stream() - .filter(hardwareConfig -> { - Map requiredScopes = hardwareConfig.getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - return AccessScope.isEnabledFor(requiredScopes, executionScope); - }).collect(Collectors.toSet()); - - computeEnvironmentConfig.getHardwareOptions().setHardwareConfigs(availableHardware); - }); - - return available; - } - - /** - * Checks if a ComputeEnvironmentConfig with the given ID is available to the provided scope/id combinations. A - * config is available provided the execution scope contains all the required access scopes of the config and each - * scope/id combination is enabled. - * - * @param id The ID of the ComputeEnvironmentConfig to check availability for. - * @param executionScope The execution scope to check availability for. - * @return True if the ComputeEnvironmentConfig with the given ID is available for the provided execution scope, - * false otherwise. - */ - @Override - public boolean isAvailable(Long id, Map executionScope) { - final Optional computeEnvironmentConfig = retrieve(id); - - if (!computeEnvironmentConfig.isPresent()) { - return false; - } - - Map requiredScopes = computeEnvironmentConfig.get().getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - return AccessScope.isEnabledFor(requiredScopes, executionScope); - } - - /** - * Creates a new ComputeEnvironmentConfig. - * - * @param computeEnvironmentConfig The ComputeEnvironmentConfig to create. - * @return The newly created ComputeEnvironmentConfig, with its ID set. - */ - @Override - public ComputeEnvironmentConfig create(ComputeEnvironmentConfig computeEnvironmentConfig) { - // Validate the ComputeEnvironmentConfig - validate(computeEnvironmentConfig); - - // Create the new compute environment config entity - ComputeEnvironmentConfigEntity newComputeEnvironmentConfigEntity = computeEnvironmentConfigEntityService.create(ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig)); - - // Update the pojo with the new ID, needed for association with hardware configs - computeEnvironmentConfig.setId(newComputeEnvironmentConfigEntity.getId()); - - setHardwareConfigsForComputeEnvironmentConfig(computeEnvironmentConfig); - - return computeEnvironmentConfigEntityService.retrieve(newComputeEnvironmentConfigEntity.getId()).toPojo(); - } - - /** - * Updates an existing ComputeEnvironmentConfig. - * - * @param computeEnvironmentConfig The ComputeEnvironmentConfig to update. - * @return The updated ComputeEnvironmentConfig. - * @throws NotFoundException If the ComputeEnvironmentConfig to update does not exist. - */ - @Override - public ComputeEnvironmentConfig update(ComputeEnvironmentConfig computeEnvironmentConfig) throws NotFoundException { - // Validate the ComputeEnvironmentConfig - if (computeEnvironmentConfig.getId() == null) { - throw new IllegalArgumentException("ComputeEnvironmentConfig ID cannot be null when updating"); - } - - validate(computeEnvironmentConfig); - - ComputeEnvironmentConfigEntity template = computeEnvironmentConfigEntityService.get(computeEnvironmentConfig.getId()); - template.update(computeEnvironmentConfig); - computeEnvironmentConfigEntityService.update(template); - - // Update the pojo with the new ID, needed for association with hardware configs - computeEnvironmentConfig.setId(template.getId()); - - setHardwareConfigsForComputeEnvironmentConfig(computeEnvironmentConfig); - - return computeEnvironmentConfigEntityService.get(computeEnvironmentConfig.getId()).toPojo(); - } - - /** - * Deletes an existing ComputeEnvironmentConfig. - * - * @param id The ID of the ComputeEnvironmentConfig to delete. - * @throws NotFoundException If the ComputeEnvironmentConfig to delete does not exist. - */ - @Override - public void delete(Long id) throws NotFoundException { - if (!exists(id)) { - throw new NotFoundException("No compute environment config found with ID " + id); - } - - // Remove all hardware configs from the compute environment config - // Get the ids of all hardware configs associated with the compute environment config before deleting to avoid - // a ConcurrentModificationException - Set hardwareConfigIds = computeEnvironmentConfigEntityService.retrieve(id) - .getHardwareOptions() - .getHardwareConfigs() - .stream() - .map(HardwareConfigEntity::getId) - .collect(Collectors.toSet()); - - hardwareConfigIds.forEach(hardwareConfigId -> { - computeEnvironmentConfigEntityService.removeHardwareConfigEntity(id, hardwareConfigId); - }); - - computeEnvironmentConfigEntityService.delete(id); - } - - /** - * Connect the hardware config entities to the compute environment config entity. - * - * @param computeEnvironmentConfig The compute environment config to connect the hardware configs to. - */ - protected void setHardwareConfigsForComputeEnvironmentConfig(ComputeEnvironmentConfig computeEnvironmentConfig) { - // Probably a more efficient way to do this, but it works for now - // Remove all hardware configs from the compute environment config - // Get the ids of all hardware configs associated with the compute environment config before deleting to avoid - // a ConcurrentModificationException - Set hardwareConfigIds = computeEnvironmentConfigEntityService.retrieve(computeEnvironmentConfig.getId()) - .getHardwareOptions() - .getHardwareConfigs() - .stream() - .map(HardwareConfigEntity::getId) - .collect(Collectors.toSet()); - - hardwareConfigIds.forEach(hardwareConfigId -> { - computeEnvironmentConfigEntityService.removeHardwareConfigEntity(computeEnvironmentConfig.getId(), hardwareConfigId); - }); - - // Add the hardware configs to the compute environment config - if (computeEnvironmentConfig.getHardwareOptions().isAllowAllHardware()) { - // Add all hardware configs to the compute environment config - hardwareConfigEntityService.getAll().forEach(hardwareConfigEntity -> { - computeEnvironmentConfigEntityService.addHardwareConfigEntity(computeEnvironmentConfig.getId(), hardwareConfigEntity.getId()); - }); - } else { - // Add the specified hardware configs to the compute environment config - computeEnvironmentConfig.getHardwareOptions().getHardwareConfigs().forEach(hardwareConfig -> { - if (hardwareConfig.getId() == null) { - // cant add a hardware config that doesn't exist - return; - } - - HardwareConfigEntity hardwareConfigEntity = hardwareConfigEntityService.retrieve(hardwareConfig.getId()); - - if (hardwareConfigEntity == null) { - // cant add a hardware config that doesn't exist - return; - } - - computeEnvironmentConfigEntityService.addHardwareConfigEntity(computeEnvironmentConfig.getId(), hardwareConfigEntity.getId()); - }); - } - } - - /** - * Validates the given ComputeEnvironmentConfig. Throws an IllegalArgumentException if the ComputeEnvironmentConfig is invalid. - * - * @param config The ComputeEnvironmentConfig to validate. - */ - protected void validate(ComputeEnvironmentConfig config) { - if (config == null) { - throw new IllegalArgumentException("ComputeEnvironmentConfig cannot be null"); - } - - List errors = new ArrayList<>(); - - errors.addAll(validate(config.getConfigTypes())); - errors.addAll(validate(config.getComputeEnvironment())); - errors.addAll(validate(config.getScopes())); - errors.addAll(validate(config.getHardwareOptions())); - - if (!errors.isEmpty()) { - throw new IllegalArgumentException("ComputeEnvironmentConfig is invalid: " + errors); - } - } - - private List validate(final Set configTypes) { - List errors = new ArrayList<>(); - - if (configTypes == null || configTypes.isEmpty()) { - errors.add("ComputeEnvironmentConfig must have at least one config type"); - } - - return errors; - } - - private List validate(final ComputeEnvironment computeEnvironment) { - List errors = new ArrayList<>(); - - if (computeEnvironment == null) { - errors.add("ComputeEnvironment cannot be null"); - return errors; - } - - if (StringUtils.isBlank(computeEnvironment.getName())) { - errors.add("ComputeEnvironment name cannot be blank"); - } - - if (StringUtils.isBlank(computeEnvironment.getImage())) { - errors.add("ComputeEnvironment image cannot be blank"); - } - - return errors; - } - - private List validate(final Map scopes) { - List errors = new ArrayList<>(); - - if (scopes == null || scopes.isEmpty()) { - errors.add("ComputeEnvironmentConfig must have at least one scope"); - return errors; - } - - if (!scopes.containsKey(Scope.Site)) { - errors.add("ComputeEnvironmentConfig must have a site scope"); - } - - if (!scopes.containsKey(Scope.User)) { - errors.add("ComputeEnvironmentConfig must have a user scope"); - } - - if (!scopes.containsKey(Scope.Project)) { - errors.add("ComputeEnvironmentConfig must have a project scope"); - } - - return errors; - } - - private List validate(final ComputeEnvironmentHardwareOptions hardwareOptions) { - List errors = new ArrayList<>(); - - if (hardwareOptions == null) { - errors.add("ComputeEnvironmentHardwareOptions cannot be null"); - return errors; - } - - if (hardwareOptions.getHardwareConfigs() == null) { - errors.add("ComputeEnvironmentHardwareOptions hardware configs cannot be null"); - } - - return errors; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/impl/DefaultConstraintConfigService.java b/src/main/java/org/nrg/xnat/compute/services/impl/DefaultConstraintConfigService.java deleted file mode 100644 index 6afe944..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/impl/DefaultConstraintConfigService.java +++ /dev/null @@ -1,195 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang.StringUtils; -import org.nrg.framework.constants.Scope; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xnat.compute.entities.ConstraintConfigEntity; -import org.nrg.xnat.compute.models.AccessScope; -import org.nrg.xnat.compute.models.Constraint; -import org.nrg.xnat.compute.models.ConstraintConfig; -import org.nrg.xnat.compute.models.ConstraintScope; -import org.nrg.xnat.compute.services.ConstraintConfigEntityService; -import org.nrg.xnat.compute.services.ConstraintConfigService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -@Service -@Slf4j -public class DefaultConstraintConfigService implements ConstraintConfigService { - - private final ConstraintConfigEntityService constraintConfigEntityService; - - @Autowired - public DefaultConstraintConfigService(ConstraintConfigEntityService constraintConfigEntityService) { - this.constraintConfigEntityService = constraintConfigEntityService; - } - - /** - * Returns the constraint config with the given id. - * - * @param id The id of the constraint config to retrieve - * @return The constraint config with the given id - */ - @Override - public Optional retrieve(Long id) { - ConstraintConfigEntity entity = constraintConfigEntityService.retrieve(id); - return Optional.ofNullable(entity) - .map(ConstraintConfigEntity::toPojo); - } - - /** - * Get all constraint configs. - * - * @return List of all constraint configs - */ - @Override - public List getAll() { - return constraintConfigEntityService - .getAll() - .stream() - .map(ConstraintConfigEntity::toPojo) - .collect(Collectors.toList()); - } - - /** - * Returns all the constraint configs that are available to the provided execution scope. - * - * @param executionScope The scope to get constraint configs for - * (e.g. {Scope.Project: "project1", Scope.User: "user1"}) - * @return All constraint configs that are available for the given scope - */ - @Override - public List getAvailable(Map executionScope) { - return constraintConfigEntityService - .getAll() - .stream() - .map(ConstraintConfigEntity::toPojo) - .filter(config -> { - Map requiredScopes = config.getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - return AccessScope.isEnabledFor(requiredScopes, executionScope); - }) - .collect(Collectors.toList()); - } - - /** - * Creates a new constraint config. - * - * @param config The constraint config to create - * @return The created constraint config - */ - @Override - public ConstraintConfig create(ConstraintConfig config) { - // Validate - validate(config); - - // Create - ConstraintConfigEntity entity = constraintConfigEntityService.create(ConstraintConfigEntity.fromPojo(config)); - return constraintConfigEntityService.retrieve(entity.getId()).toPojo(); - } - - /** - * Updates the given constraint config. - * - * @param config The constraint config to update - * @return The updated constraint config - * @throws NotFoundException If the constraint config does not exist - */ - @Override - public ConstraintConfig update(ConstraintConfig config) throws NotFoundException { - // Validate - if (config.getId() == null) { - throw new IllegalArgumentException("Constraint config id cannot be null when updating"); - } - - validate(config); - - // Update - ConstraintConfigEntity template = constraintConfigEntityService.retrieve(config.getId()); - template.update(config); - constraintConfigEntityService.update(template); - return constraintConfigEntityService.retrieve(template.getId()).toPojo(); - } - - /** - * Deletes the constraint config with the given id. - * - * @param id The id of the constraint config to delete - */ - @Override - public void delete(Long id) { - constraintConfigEntityService.delete(id); - } - - /** - * Validates that the given constraint config is valid. Throws an IllegalArgumentException if it is not. - * - * @param config The constraint config to validate - */ - protected void validate(ConstraintConfig config) { - if (config == null) { - throw new IllegalArgumentException("Constraint config cannot be null"); - } - - List errors = new ArrayList<>(); - - errors.addAll(validate(config.getConstraint())); - errors.addAll(validate(config.getScopes())); - - if (!errors.isEmpty()) { - throw new IllegalArgumentException("Constraint config is invalid: " + String.join(", ", errors)); - } - } - - private List validate(Constraint constraint) { - List errors = new ArrayList<>(); - - if (constraint == null) { - errors.add("Constraint cannot be null"); - return errors; - } - - if (StringUtils.isBlank(constraint.getKey())) { - errors.add("Constraint key cannot be null or blank"); - } - - if (constraint.getValues() == null || constraint.getValues().isEmpty()) { - errors.add("Constraint values cannot be null or empty"); - } - - if (constraint.getOperator() == null) { - errors.add("Constraint operator cannot be null"); - } - - return errors; - } - - private List validate(Map scopes) { - List errors = new ArrayList<>(); - - if (scopes == null || scopes.isEmpty()) { - errors.add("Scopes cannot be null or empty"); - return errors; - } - - if (!scopes.containsKey(Scope.Site)) { - errors.add("Scopes must contain a site scope"); - } - - if (!scopes.containsKey(Scope.Project)) { - errors.add("Scopes must contain a project scope"); - } - - return errors; - } -} diff --git a/src/main/java/org/nrg/xnat/compute/services/impl/DefaultHardwareConfigService.java b/src/main/java/org/nrg/xnat/compute/services/impl/DefaultHardwareConfigService.java deleted file mode 100644 index c2f74e8..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/impl/DefaultHardwareConfigService.java +++ /dev/null @@ -1,230 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang.StringUtils; -import org.nrg.framework.constants.Scope; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xnat.compute.entities.ComputeEnvironmentConfigEntity; -import org.nrg.xnat.compute.entities.ComputeEnvironmentHardwareOptionsEntity; -import org.nrg.xnat.compute.entities.HardwareConfigEntity; -import org.nrg.xnat.compute.models.AccessScope; -import org.nrg.xnat.compute.models.Hardware; -import org.nrg.xnat.compute.models.HardwareConfig; -import org.nrg.xnat.compute.models.HardwareScope; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigEntityService; -import org.nrg.xnat.compute.services.HardwareConfigEntityService; -import org.nrg.xnat.compute.services.HardwareConfigService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -@Service -@Slf4j -public class DefaultHardwareConfigService implements HardwareConfigService { - - private final HardwareConfigEntityService hardwareConfigEntityService; - private final ComputeEnvironmentConfigEntityService computeEnvironmentConfigEntityService; - - @Autowired - public DefaultHardwareConfigService(final HardwareConfigEntityService hardwareConfigEntityService, - final ComputeEnvironmentConfigEntityService computeEnvironmentConfigEntityService) { - this.hardwareConfigEntityService = hardwareConfigEntityService; - this.computeEnvironmentConfigEntityService = computeEnvironmentConfigEntityService; - } - - /** - * Checks if a hardware config with the given id exists. - * - * @param id The id of the hardware config to check for - * @return True if a hardware config with the given id exists, false otherwise - */ - @Override - public boolean exists(Long id) { - return hardwareConfigEntityService.exists("id", id); - } - - /** - * Returns the hardware config with the given id. - * - * @param id The id of the hardware config to retrieve - * @return An optional containing the hardware config with the given id, or empty if no such hardware config exists - */ - @Override - public Optional retrieve(Long id) { - HardwareConfigEntity entity = hardwareConfigEntityService.retrieve(id); - return Optional.ofNullable(entity).map(HardwareConfigEntity::toPojo); - } - - /** - * Returns all hardware configs - * - * @return List of all hardware configs - */ - @Override - public List retrieveAll() { - return hardwareConfigEntityService - .getAll() - .stream() - .map(HardwareConfigEntity::toPojo) - .collect(Collectors.toList()); - } - - /** - * Creates a new hardware config. - * - * @param hardwareConfig The hardware config to create - * @return The newly created hardware config with an id - */ - @Override - public HardwareConfig create(HardwareConfig hardwareConfig) { - // Validate the hardware config - validate(hardwareConfig); - - // Create the new hardware config entity - HardwareConfigEntity hardwareConfigEntity = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig)); - - // Add the hardware config to all compute environment configs that allow all hardware - computeEnvironmentConfigEntityService.getAll().stream() - .map(ComputeEnvironmentConfigEntity::getHardwareOptions) - .filter(ComputeEnvironmentHardwareOptionsEntity::isAllowAllHardware) - .forEach(hardwareOptions -> { - computeEnvironmentConfigEntityService.addHardwareConfigEntity(hardwareOptions.getId(), hardwareConfigEntity.getId()); - }); - - return hardwareConfigEntityService.retrieve(hardwareConfigEntity.getId()).toPojo(); - } - - /** - * Updates an existing hardware config. - * - * @param hardwareConfig The hardware config to update - * @return The updated hardware config - * @throws NotFoundException If no hardware config exists with the given id - */ - @Override - public HardwareConfig update(HardwareConfig hardwareConfig) throws NotFoundException { - // Validate the hardware config - if (hardwareConfig.getId() == null) { - throw new IllegalArgumentException("Hardware config id cannot be null"); - } - - validate(hardwareConfig); - - // Update the hardware config - HardwareConfigEntity template = hardwareConfigEntityService.get(hardwareConfig.getId()); - template.update(hardwareConfig); - hardwareConfigEntityService.update(template); - return hardwareConfigEntityService.get(hardwareConfig.getId()).toPojo(); - } - - /** - * Deletes the hardware config with the given id. - * - * @param id The id of the hardware config to delete - * @throws NotFoundException If no hardware config exists with the given id - */ - @Override - public void delete(Long id) throws NotFoundException { - if (!exists(id)) { - throw new NotFoundException("No hardware config found with id " + id); - } - - // Remove the hardware config from all compute environment configs - // Probably a more efficient way to do this, but this is the easiest way to do it - computeEnvironmentConfigEntityService.getAll().stream() - .map(ComputeEnvironmentConfigEntity::getHardwareOptions) - .forEach(hardwareOptions -> { - computeEnvironmentConfigEntityService.removeHardwareConfigEntity(hardwareOptions.getId(), id); - }); - - hardwareConfigEntityService.delete(id); - } - - /** - * Checks if the hardware config is available to the provided execution scope. - * - * @param id The id of the hardware config to check - * @param executionScope The execution scope to check the hardware config against - * @return True if the hardware config is available to the provided execution scope, false otherwise - **/ - @Override - public boolean isAvailable(Long id, Map executionScope) { - final Optional hardwareConfig = retrieve(id); - - if (!hardwareConfig.isPresent()) { - log.error("No hardware config found with id " + id); - return false; - } - - Map requiredScopes = hardwareConfig.get().getScopes() - .entrySet() - .stream() - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - return AccessScope.isEnabledFor(requiredScopes, executionScope); - } - - /** - * Validates the given hardware config. Throws an IllegalArgumentException if the hardware config is invalid. - * - * @param hardwareConfig The hardware config to validate - */ - protected void validate(HardwareConfig hardwareConfig) { - if (hardwareConfig == null) { - throw new IllegalArgumentException("Hardware config cannot be null"); - } - - List errors = new ArrayList<>(); - - errors.addAll(validate(hardwareConfig.getHardware())); - errors.addAll(validate(hardwareConfig.getScopes())); - - if (!errors.isEmpty()) { - throw new IllegalArgumentException("Hardware config is invalid: " + String.join(", ", errors)); - } - } - - private List validate(final Hardware hardware) { - List errors = new ArrayList<>(); - - if (hardware == null) { - errors.add("Hardware cannot be null"); - return errors; - } - - if (StringUtils.isBlank(hardware.getName())) { - errors.add("Hardware name cannot be blank"); - } - - return errors; - } - - private List validate(final Map scopes) { - List errors = new ArrayList<>(); - - if (scopes == null || scopes.isEmpty()) { - errors.add("Hardware scopes cannot be null or empty"); - return errors; - } - - if (!scopes.containsKey(Scope.Site)) { - errors.add("Hardware scopes must contain a site scope"); - } - - if (!scopes.containsKey(Scope.User)) { - errors.add("Hardware scopes must contain a user scope"); - } - - if (!scopes.containsKey(Scope.Project)) { - errors.add("Hardware scopes must contain a project scope"); - } - - return errors; - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/impl/DefaultJobTemplateService.java b/src/main/java/org/nrg/xnat/compute/services/impl/DefaultJobTemplateService.java deleted file mode 100644 index dc919c6..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/impl/DefaultJobTemplateService.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import lombok.extern.slf4j.Slf4j; -import org.nrg.framework.constants.Scope; -import org.nrg.xnat.compute.models.*; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigService; -import org.nrg.xnat.compute.services.ConstraintConfigService; -import org.nrg.xnat.compute.services.HardwareConfigService; -import org.nrg.xnat.compute.services.JobTemplateService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -@Service -@Slf4j -public class DefaultJobTemplateService implements JobTemplateService { - - private final ComputeEnvironmentConfigService computeEnvironmentConfigService; - private final HardwareConfigService hardwareConfigService; - private final ConstraintConfigService constraintConfigService; - - @Autowired - public DefaultJobTemplateService(final ComputeEnvironmentConfigService computeEnvironmentConfigService, - final HardwareConfigService hardwareConfigService, - final ConstraintConfigService constraintConfigService) { - this.computeEnvironmentConfigService = computeEnvironmentConfigService; - this.hardwareConfigService = hardwareConfigService; - this.constraintConfigService = constraintConfigService; - } - - /** - * Returns true if the specified compute environment config and hardware config are available for the provided - * execution scope and the hardware config is allowed by the compute environment config. - * - * @param computeEnvironmentConfigId the compute environment config id - * @param hardwareConfigId the hardware config id - * @return true if the specified compute environment config and hardware config are available for the provided - * execution scope and the hardware config is allowed by the compute environment config - */ - @Override - public boolean isAvailable(Long computeEnvironmentConfigId, Long hardwareConfigId, Map executionScope) { - if (computeEnvironmentConfigId == null || hardwareConfigId == null || executionScope == null) { - throw new IllegalArgumentException("One or more parameters is null"); - } - - boolean isComputeEnvironmentConfigAvailable = computeEnvironmentConfigService.isAvailable(computeEnvironmentConfigId, executionScope); - boolean isHardwareConfigAvailable = hardwareConfigService.isAvailable(hardwareConfigId, executionScope); - - if (!isComputeEnvironmentConfigAvailable || !isHardwareConfigAvailable) { - return false; - } - - ComputeEnvironmentConfig computeEnvironmentConfig = computeEnvironmentConfigService - .retrieve(computeEnvironmentConfigId) - .orElseThrow(() -> new IllegalArgumentException("ComputeEnvironmentConfig with id " + computeEnvironmentConfigId + " does not exist")); - - if (computeEnvironmentConfig.getHardwareOptions().isAllowAllHardware()) { - return true; - } - - return computeEnvironmentConfig.getHardwareOptions() - .getHardwareConfigs().stream() - .map(HardwareConfig::getId) - .anyMatch(id -> id.equals(hardwareConfigId)); - } - - /** - * Returns a job template complete with compute environment, hardware, and constraints. - * - * @param computeEnvironmentConfigId the compute environment config id - * @param hardwareConfigId the hardware config id - * @param executionScope the execution scope to verify the compute environment config and hardware are - * available - * @return a job template complete with compute environment, hardware, and constraints - */ - @Override - public JobTemplate resolve(Long computeEnvironmentConfigId, Long hardwareConfigId, Map executionScope) { - if (computeEnvironmentConfigId == null || hardwareConfigId == null || executionScope == null) { - throw new IllegalArgumentException("One or more parameters is null"); - } - - if (!isAvailable(computeEnvironmentConfigId, hardwareConfigId, executionScope)) { - throw new IllegalArgumentException("JobTemplate resolution failed for computeEnvironmentConfigId " + computeEnvironmentConfigId + " and hardwareConfigId " + hardwareConfigId + " and executionScope " + executionScope); - } - - ComputeEnvironmentConfig computeEnvironmentConfig = computeEnvironmentConfigService - .retrieve(computeEnvironmentConfigId) - .orElseThrow(() -> new IllegalArgumentException("ComputeEnvironmentConfig with id " + computeEnvironmentConfigId + " does not exist")); - - HardwareConfig hardwareConfig = hardwareConfigService - .retrieve(hardwareConfigId) - .orElseThrow(() -> new IllegalArgumentException("HardwareConfig with id " + hardwareConfigId + " does not exist")); - - List constraints = constraintConfigService.getAvailable(executionScope).stream() - .map(ConstraintConfig::getConstraint) - .collect(Collectors.toList()); - - JobTemplate jobTemplate = JobTemplate.builder() - .computeEnvironment(computeEnvironmentConfig.getComputeEnvironment()) - .hardware(hardwareConfig.getHardware()) - .constraints(constraints) - .build(); - - return jobTemplate; - } -} diff --git a/src/main/java/org/nrg/xnat/compute/services/impl/HibernateComputeEnvironmentConfigEntityService.java b/src/main/java/org/nrg/xnat/compute/services/impl/HibernateComputeEnvironmentConfigEntityService.java deleted file mode 100644 index 27b95ed..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/impl/HibernateComputeEnvironmentConfigEntityService.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import lombok.extern.slf4j.Slf4j; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntityService; -import org.nrg.xnat.compute.entities.ComputeEnvironmentConfigEntity; -import org.nrg.xnat.compute.entities.HardwareConfigEntity; -import org.nrg.xnat.compute.models.ComputeEnvironmentConfig; -import org.nrg.xnat.compute.repositories.ComputeEnvironmentConfigDao; -import org.nrg.xnat.compute.repositories.HardwareConfigDao; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigEntityService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import javax.transaction.Transactional; -import java.util.List; - -@Service -@Slf4j -public class HibernateComputeEnvironmentConfigEntityService extends AbstractHibernateEntityService implements ComputeEnvironmentConfigEntityService { - - private final HardwareConfigDao hardwareConfigDao; - - // For testing - public HibernateComputeEnvironmentConfigEntityService(final ComputeEnvironmentConfigDao computeEnvironmentConfigDao, - final HardwareConfigDao hardwareConfigDao) { - super(); - this.hardwareConfigDao = hardwareConfigDao; - setDao(computeEnvironmentConfigDao); - } - - @Autowired - public HibernateComputeEnvironmentConfigEntityService(HardwareConfigDao hardwareConfigDao) { - this.hardwareConfigDao = hardwareConfigDao; - } - - /** - * Associates a hardware config with a compute environment config - * @param computeEnvironmentConfigId The compute environment config id - * @param hardwareConfigId The hardware config id to associate with the compute environment config - */ - @Override - @Transactional - public void addHardwareConfigEntity(Long computeEnvironmentConfigId, Long hardwareConfigId) { - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity = getDao().retrieve(computeEnvironmentConfigId); - HardwareConfigEntity hardwareConfigEntity = hardwareConfigDao.retrieve(hardwareConfigId); - computeEnvironmentConfigEntity.getHardwareOptions().addHardwareConfig(hardwareConfigEntity); - getDao().update(computeEnvironmentConfigEntity); - hardwareConfigDao.update(hardwareConfigEntity); - } - - /** - * Removes association between a hardware config and a compute environment config - * @param computeEnvironmentConfigId The compute environment config id - * @param hardwareConfigId The hardware config id to remove from the compute environment config - */ - @Override - @Transactional - public void removeHardwareConfigEntity(Long computeEnvironmentConfigId, Long hardwareConfigId) { - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity = getDao().retrieve(computeEnvironmentConfigId); - HardwareConfigEntity hardwareConfigEntity = hardwareConfigDao.retrieve(hardwareConfigId); - computeEnvironmentConfigEntity.getHardwareOptions().removeHardwareConfig(hardwareConfigEntity); - getDao().update(computeEnvironmentConfigEntity); - hardwareConfigDao.update(hardwareConfigEntity); - } - - /** - * Returns a list of compute environment configs by type - * @param type The type of compute environment configs to return - * @return A list of compute environment configs of the environmentified type - */ - @Override - @Transactional - public List findByType(ComputeEnvironmentConfig.ConfigType type) { - return getDao().findByType(type.name()); - } - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/impl/HibernateConstraintConfigEntityService.java b/src/main/java/org/nrg/xnat/compute/services/impl/HibernateConstraintConfigEntityService.java deleted file mode 100644 index 76dc177..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/impl/HibernateConstraintConfigEntityService.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import lombok.extern.slf4j.Slf4j; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntityService; -import org.nrg.xnat.compute.entities.ConstraintConfigEntity; -import org.nrg.xnat.compute.repositories.ConstraintConfigDao; -import org.nrg.xnat.compute.services.ConstraintConfigEntityService; -import org.springframework.stereotype.Service; - -@Service -@Slf4j -public class HibernateConstraintConfigEntityService extends AbstractHibernateEntityService implements ConstraintConfigEntityService { - -} diff --git a/src/main/java/org/nrg/xnat/compute/services/impl/HibernateHardwareConfigEntityService.java b/src/main/java/org/nrg/xnat/compute/services/impl/HibernateHardwareConfigEntityService.java deleted file mode 100644 index c70a80d..0000000 --- a/src/main/java/org/nrg/xnat/compute/services/impl/HibernateHardwareConfigEntityService.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import lombok.extern.slf4j.Slf4j; -import org.nrg.framework.orm.hibernate.AbstractHibernateEntityService; -import org.nrg.xnat.compute.entities.HardwareConfigEntity; -import org.nrg.xnat.compute.repositories.HardwareConfigDao; -import org.nrg.xnat.compute.services.HardwareConfigEntityService; -import org.springframework.stereotype.Service; - -@Service -@Slf4j -public class HibernateHardwareConfigEntityService extends AbstractHibernateEntityService implements HardwareConfigEntityService { - -} diff --git a/src/main/resources/META-INF/resources/scripts/xnat/plugin/compute/compute-environment-configs.js b/src/main/resources/META-INF/resources/scripts/xnat/plugin/compute/compute-environment-configs.js deleted file mode 100644 index 869fe56..0000000 --- a/src/main/resources/META-INF/resources/scripts/xnat/plugin/compute/compute-environment-configs.js +++ /dev/null @@ -1,1022 +0,0 @@ -console.debug("Loading compute-environment-configs.js"); - -var XNAT = getObject(XNAT || {}); -XNAT.compute = getObject(XNAT.compute|| {}); -XNAT.compute.computeEnvironmentConfigs = getObject(XNAT.compute.computeEnvironmentConfigs || {}); - -(function (factory) { - if (typeof define === 'function' && define.amd) { - define(factory); - } else if (typeof exports === 'object') { - module.exports = factory(); - } else { - return factory(); - } -}(function () { - - XNAT.compute.computeEnvironmentConfigs.get = async (id) => { - console.debug("Fetching compute environment config " + id) - const url = XNAT.url.csrfUrl(`/xapi/compute-environment-configs/${id}`); - - const response = await fetch(url, { - method: 'GET', - headers: { - 'Content-Type': 'application/json' - } - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error(`Error fetching compute environment config ${id}`); - } - } - - XNAT.compute.computeEnvironmentConfigs.getAll = async (type) => { - console.debug("Fetching compute environment configs") - - const url = type ? - XNAT.url.csrfUrl(`/xapi/compute-environment-configs?type=${type}`) : - XNAT.url.csrfUrl(`/xapi/compute-environment-configs`); - - const response = await fetch(url, { - method: 'GET', - headers: { - 'Content-Type': 'application/json' - } - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error(`Error fetching compute environment configs`); - } - } - - XNAT.compute.computeEnvironmentConfigs.create = async (computeEnvironment) => { - console.debug("Creating compute environment config") - const url = XNAT.url.csrfUrl(`/xapi/compute-environment-configs`); - - const response = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(computeEnvironment) - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error(`Error creating compute environment config`); - } - } - - XNAT.compute.computeEnvironmentConfigs.update = async (computeEnvironment) => { - console.debug("Updating compute environment config") - const id = computeEnvironment['id']; - - if (!id) { - throw new Error(`Cannot update compute environment config without an ID`); - } - - const url = XNAT.url.csrfUrl(`/xapi/compute-environment-configs/${id}`); - - const response = await fetch(url, { - method: 'PUT', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(computeEnvironment) - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error(`Error updating compute environment config ${id}`); - } - } - - XNAT.compute.computeEnvironmentConfigs.save = async (computeEnvironment) => { - console.debug("Saving compute environment config") - const id = computeEnvironment['id']; - - if (id) { - return XNAT.compute.computeEnvironmentConfigs.update(computeEnvironment); - } else { - return XNAT.compute.computeEnvironmentConfigs.create(computeEnvironment); - } - } - - XNAT.compute.computeEnvironmentConfigs.delete = async (id) => { - console.debug("Deleting compute environment config " + id) - const url = XNAT.url.csrfUrl(`/xapi/compute-environment-configs/${id}`); - - const response = await fetch(url, { - method: 'DELETE', - }); - - if (!response.ok) { - throw new Error(`Error deleting compute environment config ${id}`); - } - } - - XNAT.compute.computeEnvironmentConfigs.available = async (type, executionScope) => { - console.debug(`Fetching available compute environment configs for type ${type} and execution scope ${executionScope}`) - let url = type ? - XNAT.url.csrfUrl(`/xapi/compute-environment-configs/available?type=${type}`): - XNAT.url.csrfUrl(`/xapi/compute-environment-configs/available?`); - - // add each scope to the url as a query parameter - for (const scope in executionScope) { - if (executionScope.hasOwnProperty(scope)) { - const value = executionScope[scope]; - if (value) { - url += `&${scope}=${value}`; - } - } - } - - const response = await fetch(url, { - method: 'GET', - headers: { - 'Content-Type': 'application/json' - } - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error(`Error fetching available compute environment configs`); - } - } - - XNAT.compute.computeEnvironmentConfigs.manager = async (containerId, computeEnvironmentType) => { - console.debug("Initializing compute environment manager") - - let container, - footer, - computeEnvironmentConfigs = [], - hardwareConfigs = [], - users = [], - projects = []; - - computeEnvironmentType = computeEnvironmentType || ''; - - const init = () => { - container = document.getElementById(containerId); - - if (!container) { - throw new Error(`Cannot find container with id ${containerId}`); - } - - clearContainer(); - renderNewButton(); - refreshTable(); - - getUsers().then(u => users = u.filter(u => u !== 'jupyterhub' && u !== 'guest')); - getProjects().then(p => projects = p); - getHardwareConfigs() - } - - const getUsers = async () => { - let response = await XNAT.plugin.jupyterhub.utils.fetchWithTimeout(`/xapi/users`); - - if (response.ok) { - return response.json(); - } else { - throw new Error(`Error fetching users`); - } - } - - const getProjects = async () => { - let response = await XNAT.plugin.jupyterhub.utils.fetchWithTimeout(`/data/projects`); - - if (response.ok) { - let projects = await response.json(); - projects = projects.ResultSet?.Result || []; - projects = projects.map(p => p['ID']); - return projects; - } else { - throw new Error(`Error fetching projects`); - } - } - - const getHardwareConfigs = () => { - XNAT.compute.hardwareConfigs.getAll().then(h => hardwareConfigs = h); - } - - const clearContainer = () => { - container.innerHTML = ''; - } - - const renderNewButton = () => { - footer = container.closest('.panel').querySelector('.panel-footer'); - footer.innerHTML = ''; - - let button = spawn('div', [ - spawn('div.pull-right', [ - spawn('button.btn.btn-sm.submit', { html: 'New ' + (computeEnvironmentType === 'JUPYTERHUB' ? 'Jupyter Environment' : 'computeEnvironment'), onclick: () => editor(null, 'new') }) - ]), - spawn('div.clear.clearFix') - ]) - - footer.appendChild(button); - } - - const enabledToggle = (config) => { - let enabled = config['scopes']['Site']['enabled']; - let ckbox = spawn('input', { - type: 'checkbox', - checked: enabled, - value: enabled ? 'true' : 'false', - data: {checked: enabled}, - onchange: () => { - let enabled = ckbox.checked; - config['scopes']['Site']['enabled'] = enabled; - - XNAT.compute.computeEnvironmentConfigs.update(config).then(() => { - XNAT.ui.banner.top(2000, `Compute Environment ${enabled ? 'Enabled' : 'Disabled'}`, 'success'); - }).catch((err) => { - console.error(err); - XNAT.ui.banner.top(4000, `Error ${enabled ? 'Enabling' : 'Disabling'} Compute Environment`, 'error'); - toggleCheckbox(!enabled); - }); - } - }); - - let toggleCheckbox = (enabled) => { - ckbox.checked = enabled; - ckbox.value = enabled ? 'true' : 'false'; - ckbox.dataset.checked = enabled; - } - - return spawn('label.switchbox', [ckbox, ['span.switchbox-outer', [['span.switchbox-inner']]]]); - } - - const displayUsers = (config) => { - let isAllUsersEnabled = config['scopes']['User']['enabled']; - let users = config['scopes']['User']['ids']; - - if (isAllUsersEnabled) { - return 'All Users'; - } else { - if (users.length > 4) { - function showUserModal(){ - XNAT.dialog.message.open({ - title: 'Enabled Users', - content: '
  • ' + users.join('
  • ') + '
', - }); - } - - return spawn('span.show-enabled-users',{ - style: { - 'border-bottom': '1px #ccc dashed', - 'cursor': 'pointer' - }, - data: { 'users': users.join(',') }, - title: 'Click to view users', - onclick: showUserModal - }, - `${users.length} Users Enabled` - ); - } else { - if (users.length === 0) { - return 'No Users Enabled'; - } - - return users.sort().join(', '); - } - } - } - - const displayProjects = (config) => { - let isAllProjectsEnabled = config['scopes']['Project']['enabled']; - let projects = config['scopes']['Project']['ids']; - - if (isAllProjectsEnabled) { - return 'All Projects'; - } else { - if (projects.length > 4) { - function showProjectModal(){ - XNAT.dialog.message.open({ - title: 'Enabled Projects', - content: '
  • ' + projects.join('
  • ') + '
', - }); - } - - return spawn('span.show-enabled-projects',{ - style: { - 'border-bottom': '1px #ccc dashed', - 'cursor': 'pointer' - }, - data: { 'projects': projects.join(',') }, - title: 'Click to view projects', - onclick: showProjectModal - }, - `${projects.length} Projects Enabled` - ); - } else { - if (projects.length === 0) { - return 'No Projects Enabled'; - } - - return projects.sort().join(', '); - } - } - } - - const displayHardware = (config) => { - let isAllHardwareEnabled = config['hardwareOptions']['allowAllHardware']; - let hardwareConfigs = config['hardwareOptions']['hardwareConfigs']; - let hardwareConfigNames = hardwareConfigs.map((config) => config['hardware']['name']); - - if (isAllHardwareEnabled) { - return 'All Hardware'; - } else { - if (hardwareConfigs.length > 4) { - function showHardwareModal(){ - XNAT.dialog.message.open({ - title: 'Enabled Hardware', - content: '
  • ' + hardwareConfigNames.join('
  • ') + '
', - }); - } - - return spawn('span.show-enabled-hardware',{ - style: { - 'border-bottom': '1px #ccc dashed', - 'cursor': 'pointer' - }, - data: { 'hardware': hardwareConfigNames.join(',') }, - title: 'Click to view hardware', - onclick: showHardwareModal - }, - `${hardwareConfigs.length} Hardware Enabled` - ); - } else { - if (hardwareConfigs.length === 0) { - return 'No Hardware Enabled'; - } - - return hardwareConfigNames.join(', '); - } - } - } - - /** - * Open the editor for a compute environment config - * @param config - the compute environment config to edit - * @param action - the action to perform (new, edit, or copy) - */ - const editor = (config, action) => { - console.debug("Opening compute environment config editor") - let isNew = action === 'new', - isCopy = action === 'copy', - isEdit = action === 'edit', - title = isNew || isCopy ? 'New ' : 'Edit ', - isJupyter = config ? config.configTypes.includes('JUPYTERHUB') : false; - - title = title + (isJupyter ? 'Jupyter Environment' : 'computeEnvironment'); - - - XNAT.dialog.open({ - title: title, - content: spawn('div', { id: 'compute-environment-editor' }), - width: 650, - maxBtn: true, - beforeShow: () => { - const formEl = document.getElementById('compute-environment-editor'); - formEl.classList.add('panel'); - - let id = isNew || isCopy ? '' : config.id; - let type = computeEnvironmentType; - let name = isNew || isCopy ? '' : config.computeEnvironment?.name || ''; - let image = isNew ? '' : config.computeEnvironment?.image; - let environmentVariables = isNew ? [] : config.computeEnvironment?.environmentVariables; - let mounts = isNew ? [] : config.computeEnvironment?.mounts; - - let siteEnabled = isNew ? true : config.scopes?.Site?.enabled; - let allUsersEnabled = isNew ? true : config.scopes?.User?.enabled; - let enabledUserIds = isNew ? [] : config.scopes?.User?.ids; - let allProjectsEnabled = isNew ? true : config.scopes?.Project?.enabled; - let enabledProjectIds = isNew ? [] : config.scopes?.Project?.ids; - - let allHardwareEnabled = isNew ? true : config.hardwareOptions?.allowAllHardware; - let enabledHardwareConfigs = isNew ? [] : config.hardwareOptions?.hardwareConfigs; - - let idEl = XNAT.ui.panel.input.text({ - name: 'id', - id: 'id', - label: 'ID *', - description: 'The ID', - value: id, - }); - - idEl.style.display = 'none'; - - let typeEl = XNAT.ui.panel.input.text({ - name: 'type', - id: 'type', - label: 'Type *', - description: 'The type (e.g. JupyterHub or Container Service)', - value: type, - }); - - typeEl.style.display = 'none'; - - let nameEl = XNAT.ui.panel.input.text({ - name: 'name', - id: 'name', - label: 'Name *', - description: 'User-friendly display name', - value: name, - }); - - let imageEl = XNAT.ui.panel.input.text({ - name: 'image', - id: 'image', - label: 'Image *', - description: 'The Docker image to use. This should be the full image name including the tag. ' + - 'The image must be available on the Docker host where the container will be run.', - value: image, - }); - - let environmentVariablesHeaderEl = spawn('div.environment-variables', [ - spawn('p', 'Environment Variables
Use this section to define additional ' + - 'environment variables for the container.'), - ]); - - let addEnvironmentVariableButtonEl = spawn('button.btn.btn-sm.add-environment-variable', { - html: 'Add Environment Variable', - style: { 'margin-top': '0.75em' }, - onclick: () => { - addEnvironmentVariable(); - } - }); - - let mountsEl = spawn('div.mounts', [ - spawn('p', 'Mounts
Use this section to define additional ' + - 'bind mounts to mount into the container.'), - ]); - - let addMountButton = spawn('button.btn.btn-sm.add-mount', { - html: 'Add Mount', - style: { 'margin-top': '0.75em' }, - onclick: () => { - addMount(); - } - }); - - let userAndProjectScopesDescription = spawn('div.user-and-project-scopes', [ - spawn('p', 'Projects and Users
Use this section to define which projects ' + - 'and users will have access to this.'), - ]); - - let siteEnabledEl = XNAT.ui.panel.input.checkbox({ - name: 'siteEnabled', - id: 'siteEnabled', - label: 'Site Enabled', - description: 'Enable this ComputeEnvironment site-wide.', - value: siteEnabled, - }); - - siteEnabledEl.style.display = 'none'; - - let allUsersEnabledEl = XNAT.ui.panel.input.checkbox({ - name: 'allUsersEnabled', - id: 'allUsersEnabled', - label: 'All Users', - description: 'Enable for all users', - value: allUsersEnabled, - }); - - let userOptions = users.map((user) => { - return { - value: user, - label: user, - selected: enabledUserIds.includes(user) - } - }) - - let userSelectEl = XNAT.ui.panel.select.multiple({ - name: 'userIds', - id: 'userIds', - label: 'Users', - description: 'Select the users who can access this', - options: userOptions, - }); - - // Disable the user select if all users are enabled - allUsersEnabledEl.querySelector('input').addEventListener('change', (event) => { - userSelectEl.querySelector('select').disabled = allUsersEnabledEl.querySelector('input').checked; - }); - - userSelectEl.querySelector('select').disabled = allUsersEnabledEl.querySelector('input').checked; - - // The user select is too small by default - userSelectEl.querySelector('select').style.minWidth = '200px'; - userSelectEl.querySelector('select').style.minHeight = '125px'; - - let allProjectsEnabledEl = XNAT.ui.panel.input.checkbox({ - name: 'allProjectsEnabled', - id: 'allProjectsEnabled', - label: 'All Projects', - description: 'Enable this for all projects', - value: allProjectsEnabled, - }); - - let projectOptions = projects.map((project) => { - return { - value: project, - label: project, - selected: enabledProjectIds.includes(project) - } - }); - - let projectSelectEl = XNAT.ui.panel.select.multiple({ - name: 'projectIds', - id: 'projectIds', - label: 'Projects', - description: 'Select the projects which can access this', - options: projectOptions, - }); - - // Disable the project select if all projects are enabled - allProjectsEnabledEl.querySelector('input').addEventListener('change', (event) => { - projectSelectEl.querySelector('select').disabled = allProjectsEnabledEl.querySelector('input').checked; - }); - - projectSelectEl.querySelector('select').disabled = allProjectsEnabledEl.querySelector('input').checked; - - // The project select is too small by default - projectSelectEl.querySelector('select').style.minWidth = '200px'; - projectSelectEl.querySelector('select').style.minHeight = '125px'; - - let hardwareScopesDescription = spawn('div.hardware-scopes', [ - spawn('p', 'Hardware
Use this section to define which Hardware ' + - 'this can be used with.'), - ]); - - let allHardwareEnabledEl = XNAT.ui.panel.input.checkbox({ - name: 'allHardwareEnabled', - id: 'allHardwareEnabled', - label: 'All Hardware', - description: 'Allow this to be used with any Hardware.', - value: allHardwareEnabled, - }); - - let hardwareConfigsEl = XNAT.ui.panel.select.multiple({ - name: 'hardwareConfigs', - id: 'hardwareConfigs', - label: 'Hardware Configs', - description: 'Select the Hardware that can be used with this', - options: hardwareConfigs.map((hardwareConfig) => { - return { - value: hardwareConfig.id, - label: hardwareConfig.hardware?.name, - selected: enabledHardwareConfigs.map((enabledHardwareConfig) => enabledHardwareConfig.id).includes(hardwareConfig.id), - } - }), - }); - - // Disable the hardware configs select if all hardware is enabled - allHardwareEnabledEl.querySelector('input').addEventListener('change', (event) => { - hardwareConfigsEl.querySelector('select').disabled = allHardwareEnabledEl.querySelector('input').checked; - }); - - hardwareConfigsEl.querySelector('select').disabled = allHardwareEnabledEl.querySelector('input').checked; - - // The hardware configs select is too small by default - hardwareConfigsEl.querySelector('select').style.minWidth = '200px'; - hardwareConfigsEl.querySelector('select').style.minHeight = '100px'; - - formEl.appendChild(spawn('!', [ - idEl, - typeEl, - nameEl, - imageEl, - spawn('hr'), - environmentVariablesHeaderEl, - addEnvironmentVariableButtonEl, - spawn('hr'), - mountsEl, - addMountButton, - spawn('hr'), - hardwareScopesDescription, - allHardwareEnabledEl, - hardwareConfigsEl, - spawn('hr'), - userAndProjectScopesDescription, - siteEnabledEl, - allProjectsEnabledEl, - projectSelectEl, - allUsersEnabledEl, - userSelectEl, - ])); - - // Add the environment variables - environmentVariables.forEach((environmentVariable) => { - addEnvironmentVariable(environmentVariable); - }); - - // Add the mounts - mounts.forEach((mount) => { - addMount(mount); - }); - }, - buttons: [ - { - label: 'Cancel', - isDefault: false, - close: true - }, - { - label: 'Save', - isDefault: true, - close: false, - action: function() { - const formEl = document.getElementById('compute-environment-editor'); - - const idEl = formEl.querySelector('#id'); - const typeEl = formEl.querySelector('#type'); - const nameEl = formEl.querySelector('#name'); - const imageEl = formEl.querySelector('#image'); - const siteEnabledEl = formEl.querySelector('#siteEnabled'); - const allUsersEnabledEl = formEl.querySelector('#allUsersEnabled'); - const userIdsEl = formEl.querySelector('#userIds'); - const allProjectsEnabledEl = formEl.querySelector('#allProjectsEnabled'); - const projectIdsEl = formEl.querySelector('#projectIds'); - const allHardwareEnabledEl = formEl.querySelector('#allHardwareEnabled'); - const hardwareConfigsEl = formEl.querySelector('#hardwareConfigs'); - - const validators = []; - - let validateNameEl = XNAT.validate(nameEl).reset().chain(); - validateNameEl.is('notEmpty').failure('Name is required'); - validators.push(validateNameEl); - - let validateImageEl = XNAT.validate(imageEl).reset().chain(); - validateImageEl.is('notEmpty').failure('Image is required'); - validators.push(validateImageEl); - - let envVarsPresent = document.querySelectorAll('input.key').length > 0; - if (envVarsPresent) { - let validateEnvironmentVariableKeys = XNAT.validate('input.key').chain(); - validateEnvironmentVariableKeys.is('notEmpty').failure('Keys are required') - .is('regex', /^[a-zA-Z_][a-zA-Z0-9_]*$/).failure('Keys must be valid environment variable names'); - validators.push(validateEnvironmentVariableKeys); - } - - let mountsPresent = document.querySelectorAll('.mount-group').length > 0; - if (mountsPresent) { - let validateLocalPaths = XNAT.validate('.mount-group .local-path').chain(); - validateLocalPaths.is('notEmpty').failure('Local paths are required') - .is('uri').failure('Local paths must be a valid URI'); - validators.push(validateLocalPaths); - - let validateContainerPaths = XNAT.validate('.mount-group .container-path').chain(); - validateContainerPaths.is('notEmpty').failure('Container paths are required') - .is('uri').failure('Container paths must be a valid URI'); - validators.push(validateContainerPaths); - } - - // validate fields - let errorMessages = []; - - validators.forEach((validator) => { - if (!validator.check()) { - validator.messages.forEach(message => errorMessages.push(message)); - } - }); - - if (errorMessages.length > 0) { - XNAT.dialog.open({ - title: 'Error', - width: 400, - content: '
  • ' + errorMessages.join('
  • ') + '
', - }) - return; - } - - config = { - id: idEl.value, - configTypes: [typeEl.value], - computeEnvironment: { - name: nameEl.value, - image: imageEl.value, - environmentVariables: getEnvironmentVariables(), - mounts: getMounts(), - }, - scopes: { - Site: { - scope: 'Site', - enabled: siteEnabledEl.checked, - ids: [], - }, - Project: { - scope: 'Project', - enabled: allProjectsEnabledEl.checked, - ids: Array.from(projectIdsEl.selectedOptions).map(option => option.value), - }, - User: { - scope: 'User', - enabled: allUsersEnabledEl.checked, - ids: Array.from(userIdsEl.selectedOptions).map(option => option.value), - } - }, - hardwareOptions: { - allowAllHardware: allHardwareEnabledEl.checked, - hardwareConfigs: Array.from(hardwareConfigsEl.selectedOptions).map(option => { - return { - id: option.value, - } - }), - } - } - - XNAT.compute.computeEnvironmentConfigs.save(config) - .then(() => { - refreshTable(); - XNAT.dialog.closeAll(); - XNAT.ui.banner.top(2000, 'Saved', 'success'); - }) - .catch((err) => { - console.error(err); - XNAT.ui.banner.top(2000, 'Error Saving', 'error'); - }); - } - } - ] - }); - } - - const refreshTable = () => { - XNAT.compute.computeEnvironmentConfigs.getAll(computeEnvironmentType) - .then((data) => { - computeEnvironmentConfigs = data; - - if (computeEnvironmentConfigs.length === 0) { - clearContainer() - container.innerHTML = `

No Jupyter environments found

` - return; - } - - table(); - }) - .catch((err) => { - console.error(err); - clearContainer(); - container.innerHTML = `

Error loading Jupyter environments

` - }); - } - - const deleteConfig = (id) => { - XNAT.compute.computeEnvironmentConfigs.delete(id) - .then(() => { - XNAT.ui.banner.top(2000, 'Delete successful', 'success'); - refreshTable(); - }) - .catch((err) => { - XNAT.ui.banner.top(4000, 'Error deleting', 'error'); - console.error(err); - }); - } - - const addEnvironmentVariable = (envVar) => { - const formEl = document.getElementById('compute-environment-editor'); - const environmentVariablesEl = formEl.querySelector('div.environment-variables'); - - const keyEl = spawn('input.form-control.key', { - id: 'key', - placeholder: 'Key', - type: 'text', - value: envVar ? envVar.key : '', - }); - - const equalsEl = spawn('span.input-group-addon', { - style: { - display: 'flex', - flexDirection: 'column', - justifyContent: 'center', - } - }, ['=']); - - const valueEl = spawn('input.form-control.value', { - id: 'value', - placeholder: 'Value', - type: 'text', - value: envVar ? envVar.value : '', - }); - - const removeButtonEl = spawn('button.btn.btn-danger', { - type: 'button', - title: 'Remove', - onclick: () => { - environmentVariableEl.remove(); - } - }, [ - spawn('i.fa.fa-trash'), - ]); - - const environmentVariableEl = spawn('div.form-group', { - style: { - marginBottom: '5px', - } - }, [ - spawn('div.input-group', { - style: { - display: 'flex', - flexDirection: 'row', - justifyContent: 'center', - columnGap: '10px', - } - }, [ - keyEl, - equalsEl, - valueEl, - spawn('span.input-group-btn', [ - removeButtonEl, - ]), - ]), - ]); - - environmentVariablesEl.appendChild(environmentVariableEl); - } - - const getEnvironmentVariables = () => { - const formEl = document.getElementById('compute-environment-editor'); - const environmentVariablesEl = formEl.querySelector('div.environment-variables'); - - let environmentVariables = []; - - Array.from(environmentVariablesEl.children).forEach((environmentVariableEl) => { - const keyEl = environmentVariableEl.querySelector('#key'); - const valueEl = environmentVariableEl.querySelector('#value'); - - if (keyEl === null || valueEl === null) return; - - environmentVariables.push({ - key: keyEl.value, - value: valueEl.value, - }); - }); - - return environmentVariables; - } - - const addMount = (mount) => { - const formEl = document.getElementById('compute-environment-editor'); - const mountsEl = formEl.querySelector('div.mounts'); - - let removeButton = spawn('a.close', { - html: '', - onclick: () => { - mountGroup.remove(); - } - }) - - let localPath = XNAT.ui.panel.input.text({ - name: 'localPath', - label: 'Local Path', - classes: 'required local-path', - description: 'The local path on the host to mount to the container', - value: mount ? mount.localPath : '', - }); - - let containerPath = XNAT.ui.panel.input.text({ - name: 'containerPath', - label: 'Container Path', - classes: 'required container-path', - description: 'The path to mount the local path to in the container', - value: mount ? mount.containerPath : '', - }); - - let readOnly = XNAT.ui.panel.input.checkbox({ - name: 'readOnly', - label: 'Read Only', - classes: 'required read-only', - description: 'Whether or not the mount should be read only', - value: mount ? mount.readOnly : true, - }); - - let mountGroup = spawn('div.mount-group', { - style: { - border: '1px solid #ccc', - padding: '5px', - margin: '5px', - borderRadius: '10px', - } - }, [ - removeButton, - localPath, - containerPath, - readOnly, - ]); - - mountsEl.appendChild(mountGroup); - } - - const getMounts = () => { - const formEl = document.getElementById('compute-environment-editor'); - const mountsEl = formEl.querySelector('div.mounts'); - - let mounts = []; - - Array.from(mountsEl.children).forEach((mountGroup) => { - const localPathEl = mountGroup.querySelector('.local-path'); - const containerPathEl = mountGroup.querySelector('.container-path'); - const readOnlyEl = mountGroup.querySelector('.read-only'); - - if (localPathEl === null || containerPathEl === null || readOnlyEl === null) return; - - mounts.push({ - volumeName: '', - localPath: localPathEl.value, - containerPath: containerPathEl.value, - readOnly: readOnlyEl.checked, - }); - }); - - return mounts; - } - - const table = () => { - const computeEnvironmentTable = XNAT.table.dataTable(computeEnvironmentConfigs, { - header: true, - sortable: 'name', - columns: { - name: { - label: 'Name', - filter: true, - td: { className: 'word-wrapped align-top' }, - apply: function () { - return this['computeEnvironment']['name']; - } - }, - image: { - label: 'Image', - filter: true, - apply: function () { - return this['computeEnvironment']['image']; - }, - }, - hardware: { - label: 'Hardware', - td: { className: 'hardware word-wrapped align-top' }, - filter: true, - apply: function () { - return displayHardware(this); - }, - }, - projects: { - label: 'Project(s)', - filter: true, - td: { className: 'projects word-wrapped align-top' }, - apply: function () { - return displayProjects(this); - }, - }, - users: { - label: 'User(s)', - filter: true, - td: { className: 'users word-wrapped align-top' }, - apply: function () { - return displayUsers(this); - }, - }, - enabled: { - label: 'Enabled', - apply: function () { - return spawn('div.center', [enabledToggle(this)]); - }, - }, - actions: { - label: 'Actions', - th: { style: { width: '150px' } }, - apply: function () { - return spawn('div.center', [ - spawn('button.btn.btn-sm', { onclick: () => editor(this, 'edit') }, ''), - spawn('span', { style: { display: 'inline-block', width: '4px' } }), - spawn('button.btn.btn-sm', { onclick: () => editor(this, 'copy') }, ''), - spawn('span', { style: { display: 'inline-block', width: '4px' } }), - spawn('button.btn.btn-sm', { onclick: () => deleteConfig(this.id) }, '') - ]); - }, - } - }, - }) - - clearContainer(); - computeEnvironmentTable.render(`#${containerId}`); - } - - init(); - - return { - container: container, - computeEnvironmentConfigs: computeEnvironmentConfigs, - refresh: refreshTable - }; - } - -})); diff --git a/src/main/resources/META-INF/resources/scripts/xnat/plugin/compute/constraint-configs.js b/src/main/resources/META-INF/resources/scripts/xnat/plugin/compute/constraint-configs.js deleted file mode 100644 index 13f19ad..0000000 --- a/src/main/resources/META-INF/resources/scripts/xnat/plugin/compute/constraint-configs.js +++ /dev/null @@ -1,610 +0,0 @@ -console.debug('Loading constraint-configs.js') - -var XNAT = getObject(XNAT || {}); -XNAT.compute = getObject(XNAT.compute|| {}); -XNAT.compute.constraintConfigs = getObject(XNAT.compute.constraintConfigs || {}); - -(function (factory) { - if (typeof define === 'function' && define.amd) { - define(factory); - } else if (typeof exports === 'object') { - module.exports = factory(); - } else { - return factory(); - } -}(function () { - - XNAT.compute.constraintConfigs.get = async (id) => { - console.debug(`Fetching constraint config ${id}`); - const url = XNAT.url.restUrl(`/xapi/constraint-configs/${id}`); - - const response = await fetch(url, { - method: 'GET', - headers: { - 'Content-Type': 'application/json' - } - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error(`Failed to fetch constraint config ${id}`); - } - } - - XNAT.compute.constraintConfigs.getAll = async () => { - console.debug('Fetching all constraint configs'); - const url = XNAT.url.restUrl('/xapi/constraint-configs'); - - const response = await fetch(url, { - method: 'GET', - headers: { - 'Content-Type': 'application/json' - } - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error('Failed to fetch constraint configs'); - } - } - - XNAT.compute.constraintConfigs.create = async (constraintConfig) => { - console.debug('Creating constraint config'); - const url = XNAT.url.restUrl('/xapi/constraint-configs'); - - const response = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(constraintConfig) - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error('Failed to create constraint config'); - } - } - - XNAT.compute.constraintConfigs.update = async (constraintConfig) => { - console.debug(`Updating constraint config ${constraintConfig.id}`); - const url = XNAT.url.restUrl(`/xapi/constraint-configs/${constraintConfig.id}`); - - const response = await fetch(url, { - method: 'PUT', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(constraintConfig) - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error(`Failed to update constraint config ${constraintConfig.id}`); - } - } - - XNAT.compute.constraintConfigs.delete = async (id) => { - console.debug(`Deleting constraint config ${id}`); - const url = XNAT.url.restUrl(`/xapi/constraint-configs/${id}`); - - const response = await fetch(url, { - method: 'DELETE', - }); - - if (!response.ok) { - throw new Error(`Failed to delete constraint config ${id}`); - } - } - - XNAT.compute.constraintConfigs.save = async (constraintConfig) => { - console.debug(`Saving constraint config ${constraintConfig.id}`); - if (constraintConfig.id) { - return XNAT.compute.constraintConfigs.update(constraintConfig); - } else { - return XNAT.compute.constraintConfigs.create(constraintConfig); - } - } - - XNAT.compute.constraintConfigs.manager = async (containerId) => { - console.debug(`Initializing constraint config manager in container ${containerId}`); - - let container, - footer, - constraintConfigs = [], - users = [], - projects = []; - - const init = () => { - container = document.getElementById(containerId); - - if (!container) { - throw new Error(`Cannot find container with id ${containerId}`); - } - - clearContainer(); - renderNewButton(); - loadProjects(); - refreshTable(); - } - - const clearContainer = () => { - container.innerHTML = ''; - } - - const renderNewButton = () => { - footer = container.closest('.panel').querySelector('.panel-footer'); - footer.innerHTML = ''; - - let button = spawn('div', [ - spawn('div.pull-right', [ - spawn('button.btn.btn-sm.submit', { html: 'New Constraint', onclick: () => editor(null, 'new') }) - ]), - spawn('div.clear.clearFix') - ]) - - footer.appendChild(button); - } - - const loadProjects = async () => { - let response = await XNAT.plugin.jupyterhub.utils.fetchWithTimeout(`/data/projects`); - - if (response.ok) { - let data = await response.json(); - data = data.ResultSet?.Result || []; - data = data.map(p => p['ID']); - projects = data; - } else { - throw new Error(`Error fetching projects`); - } - } - - const deleteConfig = (id) => { - XNAT.compute.constraintConfigs.delete(id).then(() => { - XNAT.ui.banner.top(2000, 'Constraint deleted', 'success'); - refreshTable(); - }).catch(err => { - XNAT.ui.banner.top(4000, 'Error deleting constraint', 'error'); - console.error(err); - }); - } - - const displayProjects = (config) => { - let isAllProjectsEnabled = config['scopes']['Project']['enabled']; - let projects = config['scopes']['Project']['ids']; - - if (isAllProjectsEnabled) { - return 'All Projects'; - } else { - if (projects.length > 4) { - function showProjectModal() { - XNAT.dialog.message.open({ - title: 'Enabled Projects', - content: '
  • ' + projects.join('
  • ') + '
', - }); - } - - return spawn('span.show-enabled-projects', { - style: { - 'border-bottom': '1px #ccc dashed', - 'cursor': 'pointer' - }, - data: { 'projects': projects.join(',') }, - title: 'Click to view projects', - onclick: showProjectModal - }, - `${projects.length} Projects Enabled` - ); - } else { - if (projects.length === 0) { - return 'No Projects Enabled'; - } - - return projects.sort().join(', '); - } - } - } - - const enabledToggle = (config) => { - let enabled = config['scopes']['Site']['enabled']; - let ckbox = spawn('input', { - type: 'checkbox', - checked: enabled, - value: enabled ? 'true' : 'false', - data: { checked: enabled }, - onchange: () => { - let enabled = ckbox.checked; - config['scopes']['Site']['enabled'] = enabled; - - XNAT.compute.constraintConfigs.update(config).then(() => { - XNAT.ui.banner.top(2000, `Constraint ${enabled ? 'Enabled' : 'Disabled'}`, 'success'); - }).catch((err) => { - console.error(err); - XNAT.ui.banner.top(4000, - `Error ${enabled ? 'Enabling' : 'Disabling'} Constraint`, - 'error' - ); - toggleCheckbox(!enabled); - }); - } - }); - - let toggleCheckbox = (enabled) => { - ckbox.checked = enabled; - ckbox.value = enabled ? 'true' : 'false'; - ckbox.dataset.checked = enabled; - } - - return spawn('label.switchbox', [ckbox, ['span.switchbox-outer', [['span.switchbox-inner']]]]); - } - - const editor = (config, mode) => { - console.debug(`Opening constraint config editor in ${mode} mode`); - - let isNew = mode === 'new', - isEdit = mode === 'edit', - isCopy = mode === 'copy'; - - let title = isNew || isCopy ? 'New Constraint' : 'Edit Constraint'; - - XNAT.dialog.open({ - title: title, - content: spawn('div', { id: 'config-editor' }), - width: 650, - maxBtn: true, - beforeShow: () => { - const form = document.getElementById('config-editor'); - form.classList.add('panel'); - - let id = isNew || isCopy ? '' : config.id; - let attribute = isNew ? '' : config.constraint?.key || ''; - let operator = isNew ? 'IN' : config.constraint?.operator || 'IN'; - let values = isNew ? '' : config.constraint?.values.join(',') || ''; - - let siteEnabled = isNew || isCopy ? true : config.scopes?.Site?.enabled || false; - let allUsersEnabled = isNew ? true : config.scopes?.User?.enabled || false; - let enabledUsers = isNew ? [] : config.scopes?.User?.ids || []; - let allProjectsEnabled = isNew ? true : config.scopes?.Project?.enabled || false; - let enabledProjects = isNew ? [] : config.scopes?.Project?.ids || []; - - let idInput = XNAT.ui.panel.input.text({ - name: 'id', - id: 'id', - label: 'ID *', - description: 'The ID of the constraint', - value: id, - }); - - idInput.style.display = 'none'; // hide the ID field - - let constraintHeader = spawn('div.placement-constraints.swarm', [ - spawn('p', 'Constraint
Use this section to define a placement ' + - 'constraint applicable to all jobs submitted to this cluster. ' + - 'See Docker Swarm documentation on ' + - 'service placement constraints and the ' + - 'docker service create command ' + - 'for more information about allowed constraints.'), - ]); - - let attributeInput = XNAT.ui.panel.input.text({ - name: `constraint-attribute`, - label: 'Node attribute', - classes: 'required swarm-constraint-attribute', - description: 'Attribute you wish to constrain. E.g., node.labels.mylabel or node.role', - value: attribute, - }); - - let operatorInput = XNAT.ui.panel.input.radioGroup({ - name: `constraint-operator`, // random ID to avoid collisions - label: 'Comparator', - classes: 'required swarm-constraint-operator', - items: { 0: { label: 'Equals', value: 'IN' }, 1: { label: 'Does not equal', value: 'NOT_IN' } }, - value: operator, - }) - - let valuesInput = XNAT.ui.panel.input.list({ - name: `constraint-values`, // random ID to avoid collisions - label: 'Possible Values For Constraint', - classes: 'required swarm-constraint-values', - description: 'Comma-separated list of values on which user can constrain the attribute (or a single value if not user-settable). E.g., "worker" or "spot,demand" (do not add quotes). ', - value: values, - }) - - let projectScopesDescription = spawn('div.user-and-project-scopes', [ - spawn('p', 'Projects
Use this section to limit the scope of a constraint to ' + - "specific projects (and it's subjects and experiments). "), - ]); - - let siteEnabledInput = XNAT.ui.panel.input.checkbox({ - name: 'siteEnabled', - id: 'siteEnabled', - label: 'Site Enabled', - description: 'Enable this hardware for all users and projects', - value: siteEnabled, - }); - - siteEnabledInput.style.display = 'none'; // hide the site enabled field - - let allUsersEnabledInput = XNAT.ui.panel.input.checkbox({ - name: 'allUsersEnabled', - id: 'allUsersEnabled', - label: 'All Users', - description: 'Enable this hardware for all users', - value: allUsersEnabled, - }); - - allUsersEnabledInput.style.display = 'none'; // hide the all users enabled field - - let userOptions = users.map((user) => { - return { - value: user, - label: user, - selected: enabledUsers.includes(user) - } - }); - - let userSelect = XNAT.ui.panel.select.multiple({ - name: 'enabledUsers', - id: 'enabledUsers', - label: 'Users', - description: 'Select the users to enable this hardware for', - options: userOptions, - }); - - userSelect.style.display = 'none'; // hide the user select - - // Disable the user select if all users are enabled - allUsersEnabledInput.querySelector('input').addEventListener('change', (event) => { - userSelect.querySelector('select').disabled = allUsersEnabledInput.querySelector('input').checked; - }); - - userSelect.querySelector('select').disabled = allUsersEnabledInput.querySelector('input').checked; - - // The user select is too small by default - userSelect.querySelector('select').style.minWidth = '200px'; - userSelect.querySelector('select').style.minHeight = '125px'; - - let allProjectsEnabledInput = XNAT.ui.panel.input.checkbox({ - name: 'allProjectsEnabled', - id: 'allProjectsEnabled', - label: 'All Projects', - description: 'Enable this constraint for all projects', - value: allProjectsEnabled, - }); - - let projectOptions = projects.map((project) => { - return { - value: project, - label: project, - selected: enabledProjects.includes(project) - } - }); - - let projectSelect = XNAT.ui.panel.select.multiple({ - name: 'enabledProjects', - id: 'enabledProjects', - label: 'Projects', - description: 'Select the projects to enable this constraint for', - options: projectOptions, - }); - - // Disable the project select if all projects are enabled - allProjectsEnabledInput.querySelector('input').addEventListener('change', (event) => { - projectSelect.querySelector('select').disabled = allProjectsEnabledInput.querySelector('input').checked; - }); - - projectSelect.querySelector('select').disabled = allProjectsEnabledInput.querySelector('input').checked; - - // The project select is too small by default - projectSelect.querySelector('select').style.minWidth = '200px'; - projectSelect.querySelector('select').style.minHeight = '125px'; - - let formFields = [ - idInput, - constraintHeader, - attributeInput, - operatorInput, - valuesInput, - spawn('hr'), - projectScopesDescription, - siteEnabledInput, - allUsersEnabledInput, - userSelect, - allProjectsEnabledInput, - projectSelect, - ]; - - form.appendChild(spawn('!', formFields)); - }, - buttons: [ - { - label: 'Save', - isDefault: true, - close: false, - action: function () { - const form = document.getElementById('config-editor'); - - let id = form.querySelector('#id'); - let attribute = form.querySelector('.swarm-constraint-attribute'); - let operator = form.querySelector('.swarm-constraint-operator input:checked'); - let values = form.querySelector('.swarm-constraint-values'); - - let siteEnabledElement = form.querySelector('#siteEnabled'); - let allUsersEnabledElement = form.querySelector('#allUsersEnabled'); - let enabledUsersElement = form.querySelector('#enabledUsers'); - let allProjectsEnabledElement = form.querySelector('#allProjectsEnabled'); - let enabledProjectsElement = form.querySelector('#enabledProjects'); - - let validators = [] - - let validateAttribute = XNAT.validate(attribute) - .reset().chain() - .is('notEmpty').failure('Attribute is required'); - validators.push(validateAttribute); - - let validateValues = XNAT.validate(values) - .reset().chain() - .is('notEmpty').failure('Value is required'); - validators.push(validateValues); - - let errors = []; - - validators.forEach((validator) => { - if (!validator.check()) { - validator.messages.forEach(message => errors.push(message)); - } - }); - - if (errors.length > 0) { - XNAT.dialog.open({ - title: 'Error', - width: 400, - content: '
  • ' + errors.join('
  • ') + '
', - }) - return; - } - - config = { - id: id.value, - constraint: { - key: attribute.value, - operator: operator.value, - values: values.value.split(',').map((value) => value.trim()), - }, - scopes: { - Site: { - scope: 'Site', - enabled: siteEnabledElement.checked, - }, - Project: { - scope: 'Project', - enabled: allProjectsEnabledElement.checked, - ids: Array.from(enabledProjectsElement.selectedOptions).map(option => option.value), - }, - User: { - scope: 'User', - enabled: allUsersEnabledElement.checked, - ids: Array.from(enabledUsersElement.selectedOptions).map(option => option.value), - }, - } - } - - XNAT.compute.constraintConfigs.save(config).then(() => { - XNAT.ui.banner.top(2000, 'Saved constraint config', 'success'); - XNAT.dialog.closeAll(); - refreshTable(); - }).catch(err => { - console.error(err); - XNAT.ui.banner.top(4000, 'Error saving constraint config', 'error'); - }); - } - }, - { - label: 'Cancel', - close: true, - isDefault: false - } - ] - }); - } - - const refreshTable = () => { - XNAT.compute.constraintConfigs.getAll().then(data => { - constraintConfigs = data; - - if (constraintConfigs.length === 0) { - clearContainer(); - container.innerHTML = `

No constraints found

`; - return; - } - - renderTable(); - }).catch(err => { - console.error(err); - clearContainer(); - container.innerHTML = `

Error fetching constraints

`; - }) - } - - const renderTable = () => { - let table = XNAT.table.dataTable(constraintConfigs, { - header: true, - sortable: 'nodeAttribute, comparator, values', - columns: { - nodeAttribute: { - label: 'Node Attribute', - td: { className: 'word-wrapped align-top' }, - apply: function() { - return this.constraint?.key; - } - }, - comparator: { - label: 'Comparator', - td: { className: 'word-wrapped align-top' }, - apply: function() { - return spawn('div.center', [this.constraint?.operator === 'IN' ? '==' : '!=']); - } - }, - values: { - label: 'Constraint Value(s)', - td: { className: 'word-wrapped align-top' }, - apply: function() { - return spawn('div.center', [this.constraint?.values?.join(', ')]); - } - }, - projects: { - label: 'Project(s)', - td: { className: 'projects word-wrapped align-top' }, - apply: function () { - return displayProjects(this); - } - }, - enabled: { - label: 'Enabled', - apply: function () { - return spawn('div.center', [enabledToggle(this)]); - }, - }, - actions: { - label: 'Actions', - th: { style: { width: '150px' } }, - apply: function () { - return spawn('div.center', [ - spawn('button.btn.btn-sm', - { onclick: () => editor(this, 'edit') }, - '' - ), - spawn('span', { style: { display: 'inline-block', width: '4px' } }), - spawn('button.btn.btn-sm', - { onclick: () => editor(this, 'copy') }, - '' - ), - spawn('span', { style: { display: 'inline-block', width: '4px' } }), - spawn('button.btn.btn-sm', - { onclick: () => deleteConfig(this.id) }, - '' - ) - ]); - }, - } - } - }); - - clearContainer(); - table.render(`#${containerId}`); - } - - init(); - - return { - container: container, - constraintConfigs: constraintConfigs, - refreshTable: refreshTable - } - } - -})); \ No newline at end of file diff --git a/src/main/resources/META-INF/resources/scripts/xnat/plugin/compute/hardware-configs.js b/src/main/resources/META-INF/resources/scripts/xnat/plugin/compute/hardware-configs.js deleted file mode 100644 index 6bbf31f..0000000 --- a/src/main/resources/META-INF/resources/scripts/xnat/plugin/compute/hardware-configs.js +++ /dev/null @@ -1,1085 +0,0 @@ -console.debug("Loading hardware-configs.js"); - -var XNAT = getObject(XNAT || {}); -XNAT.compute = getObject(XNAT.compute || {}); -XNAT.compute.hardwareConfigs = getObject(XNAT.compute.hardwareConfigs || {}); - -(function (factory) { - if (typeof define === 'function' && define.amd) { - define(factory); - } else if (typeof exports === 'object') { - module.exports = factory(); - } else { - return factory(); - } -}(function () { - - XNAT.compute.hardwareConfigs.get = async (id) => { - console.debug("Fetching hardware config with id: " + id); - const url = XNAT.url.restUrl('/xapi/hardware-configs/' + id); - - const response = await fetch(url, { - method: 'GET', - headers: { - 'Content-Type': 'application/json' - } - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error('Error fetching hardware config with id: ' + id); - } - } - - XNAT.compute.hardwareConfigs.getAll = async () => { - console.debug("Fetching all hardware configs"); - const url = XNAT.url.restUrl('/xapi/hardware-configs'); - - const response = await fetch(url, { - method: 'GET', - headers: { - 'Content-Type': 'application/json' - } - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error('Error fetching all hardware configs'); - } - } - - XNAT.compute.hardwareConfigs.create = async (config) => { - console.debug("Creating hardware config"); - const url = XNAT.url.restUrl('/xapi/hardware-configs'); - - const response = await fetch(url, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(config) - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error('Error creating hardware config'); - } - }; - - XNAT.compute.hardwareConfigs.update = async (config) => { - console.debug("Updating hardware config"); - const id = config.id; - - if (!id) { - throw new Error('Hardware config id is required'); - } - - const url = XNAT.url.restUrl(`/xapi/hardware-configs/${id}`); - - const response = await fetch(url, { - method: 'PUT', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(config) - }); - - if (response.ok) { - return response.json(); - } else { - throw new Error('Error updating hardware config'); - } - } - - XNAT.compute.hardwareConfigs.save = async (config) => { - console.debug("Saving hardware config"); - const id = config.id; - - if (!id) { - return XNAT.compute.hardwareConfigs.create(config); - } else { - return XNAT.compute.hardwareConfigs.update(config); - } - } - - XNAT.compute.hardwareConfigs.delete = async (id) => { - console.debug("Deleting hardware config with id: " + id); - const url = XNAT.url.restUrl('/xapi/hardware-configs/' + id); - - const response = await fetch(url, { - method: 'DELETE', - headers: { - 'Content-Type': 'application/json' - } - }); - - if (!response.ok) { - throw new Error('Error deleting hardware config with id: ' + id); - } - } - - XNAT.compute.hardwareConfigs.manager = async (containerId) => { - console.debug("Initializing hardware config manager"); - - let container, - footer, - hardwareConfigs = [], - users = [], - projects = []; - - const init = () => { - container = document.getElementById(containerId); - - if (!container) { - throw new Error('Container element wtih id: ' + containerId + ' not found'); - } - - clearContainer(); - renderNewButton(); - - loadUsers(); - loadProjects(); - - refreshTable(); - } - - const loadUsers = async () => { - let response = await XNAT.plugin.jupyterhub.utils.fetchWithTimeout(`/xapi/users`); - - if (response.ok) { - let data = await response.json(); - users = data.filter(u => u !== 'jupyterhub' && u !== 'guest'); - } else { - throw new Error(`Error fetching users`); - } - } - - const loadProjects = async () => { - let response = await XNAT.plugin.jupyterhub.utils.fetchWithTimeout(`/data/projects`); - - if (response.ok) { - let data = await response.json(); - data = data.ResultSet?.Result || []; - data = data.map(p => p['ID']); - projects = data; - } else { - throw new Error(`Error fetching projects`); - } - } - - const clearContainer = () => { - container.innerHTML = ''; - } - - const renderNewButton = () => { - footer = container.closest('.panel').querySelector('.panel-footer'); - footer.innerHTML = ''; - - let button = spawn('div', [ - spawn('div.pull-right', [ - spawn('button.btn.btn-sm.submit', { html: 'New Hardware', onclick: () => editor(null, 'new') }) - ]), - spawn('div.clear.clearFix') - ]) - - footer.appendChild(button); - } - - const enabledToggle = (config) => { - let enabled = config['scopes']['Site']['enabled']; - let ckbox = spawn('input', { - type: 'checkbox', - checked: enabled, - value: enabled ? 'true' : 'false', - data: { checked: enabled }, - onchange: () => { - let enabled = ckbox.checked; - config['scopes']['Site']['enabled'] = enabled; - - XNAT.compute.hardwareConfigs.update(config).then(() => { - XNAT.ui.banner.top(2000, `Hardware ${enabled ? 'Enabled' : 'Disabled'}`, 'success'); - }).catch((err) => { - console.error(err); - XNAT.ui.banner.top(4000, - `Error ${enabled ? 'Enabling' : 'Disabling'} Hardware`, - 'error' - ); - toggleCheckbox(!enabled); - }); - } - }); - - let toggleCheckbox = (enabled) => { - ckbox.checked = enabled; - ckbox.value = enabled ? 'true' : 'false'; - ckbox.dataset.checked = enabled; - } - - return spawn('label.switchbox', [ckbox, ['span.switchbox-outer', [['span.switchbox-inner']]]]); - } - - const displayUsers = (config) => { - let isAllUsersEnabled = config['scopes']['User']['enabled']; - let users = config['scopes']['User']['ids']; - - if (isAllUsersEnabled) { - return 'All Users'; - } else { - if (users.length > 4) { - function showUserModal() { - XNAT.dialog.message.open({ - title: 'Enabled Users', - content: '
  • ' + users.join('
  • ') + '
', - }); - } - - return spawn('span.show-enabled-users', { - style: { - 'border-bottom': '1px #ccc dashed', - 'cursor': 'pointer' - }, - data: { 'users': users.join(',') }, - title: 'Click to view users', - onclick: showUserModal - }, - `${users.length} Users Enabled` - ); - } else { - if (users.length === 0) { - return 'No Users Enabled'; - } - - return users.sort().join(', '); - } - } - } - - const displayProjects = (config) => { - let isAllProjectsEnabled = config['scopes']['Project']['enabled']; - let projects = config['scopes']['Project']['ids']; - - if (isAllProjectsEnabled) { - return 'All Projects'; - } else { - if (projects.length > 4) { - function showProjectModal() { - XNAT.dialog.message.open({ - title: 'Enabled Projects', - content: '
  • ' + projects.join('
  • ') + '
', - }); - } - - return spawn('span.show-enabled-projects', { - style: { - 'border-bottom': '1px #ccc dashed', - 'cursor': 'pointer' - }, - data: { 'projects': projects.join(',') }, - title: 'Click to view projects', - onclick: showProjectModal - }, - `${projects.length} Projects Enabled` - ); - } else { - if (projects.length === 0) { - return 'No Projects Enabled'; - } - - return projects.sort().join(', '); - } - } - } - - const editor = (config, mode) => { - console.debug(`Opening hardware config editor in ${mode} mode`); - - let isNew = mode === 'new', - isEdit = mode === 'edit', - isCopy = mode === 'copy'; - - let title = isNew || isCopy ? 'New Hardware' : 'Edit Hardware'; - - XNAT.dialog.open({ - title: title, - content: spawn('div', { id: 'config-editor' }), - width: 650, - maxBtn: true, - beforeShow: () => { - const form = document.getElementById('config-editor'); - form.classList.add('panel'); - - let id = isNew || isCopy ? '' : config.id; - let name = isNew || isCopy ? '' : config.hardware?.name; - - let cpuLimit = isNew ? '' : config.hardware?.cpuLimit || ''; - let cpuReservation = isNew ? '' : config.hardware?.cpuReservation || ''; - let memoryLimit = isNew ? '' : config.hardware?.memoryLimit || ''; - let memoryReservation = isNew ? '' : config.hardware?.memoryReservation || ''; - - let environmentVariables = isNew ? [] : config.hardware?.environmentVariables || []; - let constraints = isNew ? [] : config.hardware?.constraints || []; - let genericResources = isNew ? [] : config.hardware?.genericResources || []; - - let siteEnabled = isNew || isCopy ? true : config.scopes?.Site?.enabled || false; - let allUsersEnabled = isNew ? true : config.scopes?.User?.enabled || false; - let enabledUsers = isNew ? [] : config.scopes?.User?.ids || []; - let allProjectsEnabled = isNew ? true : config.scopes?.Project?.enabled || false; - let enabledProjects = isNew ? [] : config.scopes?.Project?.ids || []; - - let idInput = XNAT.ui.panel.input.text({ - name: 'id', - id: 'id', - label: 'ID *', - description: 'The ID of the hardware configuration', - value: id, - }); - - idInput.style.display = 'none'; // hide the ID field - - let nameInput = XNAT.ui.panel.input.text({ - name: 'name', - id: 'name', - label: 'Name *', - description: 'Provide a user-friendly name for this hardware', - value: name, - }); - - let cpuAndMemDescriptionSwarm = spawn('div.cpu-mem-header.swarm', [ - spawn('p', 'CPU and Memory
By default, a container has no resource ' + - 'constraints and can use as much of a given resource as the host’s kernel scheduler allows.' + - ' Docker provides ways to control how much memory, or CPU a container can use, setting ' + - 'runtime configuration flags of the docker run command. ' + - 'For more information, see the Docker documentation on ' + - '' + - 'resource constraints.'), - ]); - - let cpuReservationInput = XNAT.ui.panel.input.text({ - name: 'cpuReservation', - id: 'cpuReservation', - label: 'CPU Reservation', - description: 'The number of CPUs to reserve', - value: cpuReservation, - }); - - let cpuLimitInput = XNAT.ui.panel.input.text({ - name: 'cpuLimit', - id: 'cpuLimit', - label: 'CPU Limit', - description: 'The maximum number of CPUs that can be used', - value: cpuLimit, - }); - - let memoryReservationInput = XNAT.ui.panel.input.text({ - name: 'memoryReservation', - id: 'memoryReservation', - label: 'Memory Reservation', - description: 'The amount of memory that this container will reserve. Allows for suffixes like "0.5G" or "512M".', - value: memoryReservation, - }); - - let memoryLimitInput = XNAT.ui.panel.input.text({ - name: 'memoryLimit', - id: 'memoryLimit', - label: 'Memory Limit', - description: 'The maximum amount of memory that this container can use. Allows for suffixes like "8G" or "4G".', - value: memoryLimit, - }); - - let environmentVariablesHeaderEl = spawn('div.environment-variables', [ - spawn('p', 'Environment Variables
Use this section to define additional ' + - 'environment variables for the container.'), - ]); - - let addEnvironmentVariableButtonEl = spawn('button.btn.btn-sm.add-environment-variable', { - html: 'Add Environment Variable', - style: { 'margin-top': '0.75em' }, - onclick: () => { - addEnvironmentVariable(); - } - }); - - let genericResourcesDescription = spawn('div.generic-resources.swarm', [ - spawn('p', 'Generic Resources
Use this section to request generic ' + - 'resources when the container is scheduled. ' + - 'See Docker Swarm documentation on ' + - 'generic resources ' + - 'for more information about allowed constraints.'), - ]); - - let addGenericResourceButton = spawn('button.btn.btn-sm.add-generic-resource.swarm', { - html: 'Add Generic Resource', - style: { 'margin-top': '0.75em' }, - onclick: () => { - addGenericResource(); - } - }); - - let placementConstraintHeaderEl = spawn('div.placement-constraints.swarm', [ - spawn('p', 'Placement Constraints
Use this section to define placement ' + - 'constraints when the container is scheduled. ' + - 'See Docker Swarm documentation on ' + - 'service placement constraints and the ' + - 'docker service create command ' + - 'for more information about allowed constraints.'), - ]); - - let addSwarmConstraintButtonEl = spawn('button.btn.btn-sm.add-placement-constraint.swarm', { - html: 'Add Constraint', - style: { 'margin-top': '0.75em' }, - onclick: () => { - addSwarmConstraint(); - } - }); - - let userAndProjectScopesDescription = spawn('div.user-and-project-scopes', [ - spawn('p', 'Projects and Users
Use this section to define which projects ' + - 'and users will have access to this hardware.'), - ]); - - let siteEnabledInput = XNAT.ui.panel.input.checkbox({ - name: 'siteEnabled', - id: 'siteEnabled', - label: 'Site Enabled', - description: 'Enable this hardware for all users and projects', - value: siteEnabled, - }); - - siteEnabledInput.style.display = 'none'; // hide the site enabled field - - let allUsersEnabledInput = XNAT.ui.panel.input.checkbox({ - name: 'allUsersEnabled', - id: 'allUsersEnabled', - label: 'All Users', - description: 'Enable this hardware for all users', - value: allUsersEnabled, - }); - - let userOptions = users.map((user) => { - return { - value: user, - label: user, - selected: enabledUsers.includes(user) - } - }); - - let userSelect = XNAT.ui.panel.select.multiple({ - name: 'enabledUsers', - id: 'enabledUsers', - label: 'Users', - description: 'Select the users to enable this hardware for', - options: userOptions, - }); - - // Disable the user select if all users are enabled - allUsersEnabledInput.querySelector('input').addEventListener('change', (event) => { - userSelect.querySelector('select').disabled = allUsersEnabledInput.querySelector('input').checked; - }); - - userSelect.querySelector('select').disabled = allUsersEnabledInput.querySelector('input').checked; - - // The user select is too small by default - userSelect.querySelector('select').style.minWidth = '200px'; - userSelect.querySelector('select').style.minHeight = '125px'; - - let allProjectsEnabledInput = XNAT.ui.panel.input.checkbox({ - name: 'allProjectsEnabled', - id: 'allProjectsEnabled', - label: 'All Projects', - description: 'Enable this hardware for all projects', - value: allProjectsEnabled, - }); - - let projectOptions = projects.map((project) => { - return { - value: project, - label: project, - selected: enabledProjects.includes(project) - } - }); - - let projectSelect = XNAT.ui.panel.select.multiple({ - name: 'enabledProjects', - id: 'enabledProjects', - label: 'Projects', - description: 'Select the projects to enable this hardware for', - options: projectOptions, - }); - - // Disable the project select if all projects are enabled - allProjectsEnabledInput.querySelector('input').addEventListener('change', (event) => { - projectSelect.querySelector('select').disabled = allProjectsEnabledInput.querySelector('input').checked; - }); - - projectSelect.querySelector('select').disabled = allProjectsEnabledInput.querySelector('input').checked; - - // The project select is too small by default - projectSelect.querySelector('select').style.minWidth = '200px'; - projectSelect.querySelector('select').style.minHeight = '125px'; - - let formFields = [ - idInput, - nameInput, - spawn('hr'), - cpuAndMemDescriptionSwarm, - cpuReservationInput, - cpuLimitInput, - memoryReservationInput, - memoryLimitInput, - spawn('hr'), - environmentVariablesHeaderEl, - addEnvironmentVariableButtonEl, - spawn('hr'), - genericResourcesDescription, - addGenericResourceButton, - spawn('hr'), - placementConstraintHeaderEl, - addSwarmConstraintButtonEl, - spawn('hr'), - userAndProjectScopesDescription, - siteEnabledInput, - allProjectsEnabledInput, - projectSelect, - allUsersEnabledInput, - userSelect, - ]; - - form.appendChild(spawn('!', [ - ...formFields - ])); - - // add the environment variables - environmentVariables.forEach((environmentVariable) => { - addEnvironmentVariable(environmentVariable); - }); - - // add the placement constraints - constraints.forEach((constraint) => { - addSwarmConstraint(constraint); - }); - - // add the generic resources - genericResources.forEach((genericResource) => { - addGenericResource(genericResource); - }); - }, - buttons: [ - { - label: 'Save', - isDefault: true, - close: false, - action: function () { - const form = document.getElementById('config-editor'); - - const idElement = form.querySelector('#id'); - const nameElement = form.querySelector('#name'); - - const cpuReservationElement = form.querySelector('#cpuReservation'); - const cpuLimitElement = form.querySelector('#cpuLimit'); - const memoryReservationElement = form.querySelector('#memoryReservation'); - const memoryLimitElement = form.querySelector('#memoryLimit'); - - const siteEnabledElement = form.querySelector('#siteEnabled'); - const allUsersEnabledElement = form.querySelector('#allUsersEnabled'); - const enabledUsersElement = form.querySelector('#enabledUsers'); - const allProjectsEnabledElement = form.querySelector('#allProjectsEnabled'); - const enabledProjectsElement = form.querySelector('#enabledProjects'); - - const validators = []; - - let validateNameElement = XNAT.validate(nameElement).reset().chain(); - validateNameElement.is('notEmpty').failure('Name is required'); - validators.push(validateNameElement); - - let validateCpuReservationElement = XNAT.validate(cpuReservationElement).reset().chain(); - validateCpuReservationElement.is('allow-empty') - .is('decimal') - .is('greater-than', 0) - .failure('CPU Reservation must be a positive number or empty'); - validators.push(validateCpuReservationElement); - - let validateCpuLimitElement = XNAT.validate(cpuLimitElement).reset().chain(); - validateCpuLimitElement.is('allow-empty') - .is('decimal') - .is('greater-than', 0) - .failure('CPU Limit must be a positive number or empty'); - validators.push(validateCpuLimitElement); - - let validateMemoryReservationElement = XNAT.validate(memoryReservationElement).reset().chain(); - validateMemoryReservationElement.is('allow-empty') - .is('regex', /^$|^([1-9]+[0-9]*)+[KMGT]$/) // 512M, 2G, etc. - .failure('Memory Reservation must be a number followed by a suffix of K, M, G, or T or be empty'); - validators.push(validateMemoryReservationElement); - - let validateMemoryLimitElement = XNAT.validate(memoryLimitElement).reset().chain(); - validateMemoryLimitElement.is('allow-empty') - .is('regex', /^$|^([1-9]+[0-9]*)+[KMGT]$/) // 512M, 2G, etc. - .failure('Memory Limit must be a number followed by a suffix of K, M, G, or T or be empty'); - validators.push(validateMemoryLimitElement); - - let envVarsPresent = document.querySelectorAll('input.key').length > 0; - if (envVarsPresent) { - let validateEnvironmentVariableKeys = XNAT.validate('input.key').chain(); - validateEnvironmentVariableKeys.is('notEmpty') - .is('regex', /^[a-zA-Z_][a-zA-Z0-9_]*$/) // must start with a letter or underscore, and only contain letters, numbers, and underscores - .failure('Keys are required and must be a valid environment variable name'); - validators.push(validateEnvironmentVariableKeys); - } - - let swarmConstraintsPresent = document.querySelectorAll('div.swarm-constraint-group').length > 0; - if (swarmConstraintsPresent) { - let validateSwarmConstraintAttributes = XNAT.validate('input.swarm-constraint-attribute').chain(); - validateSwarmConstraintAttributes.is('notEmpty') - .is('regex', /^[a-zA-Z_][a-zA-Z0-9_.-]*$/) // must start with a letter or underscore, and only contain letters, numbers, underscores, hyphens, and periods - .failure('Attributes are required and must be a valid swarm constraint attribute'); - validators.push(validateSwarmConstraintAttributes); - - let validateSwarmConstraintValues = XNAT.validate('input.swarm-constraint-values').chain(); - validateSwarmConstraintValues.is('notEmpty') - .failure('Constraint values are required'); - validators.push(validateSwarmConstraintValues); - } - - let genericResourcesPresent = document.querySelectorAll('div.resource-group').length > 0; - if (genericResourcesPresent) { - let validateGenericResourceNames = XNAT.validate('input.resource-name').chain(); - validateGenericResourceNames.is('notEmpty').failure('Resource names are required') - .is('regex', /^[a-zA-Z_][a-zA-Z0-9_.-]*$/).failure('Invalid resource name'); - validators.push(validateGenericResourceNames); - - let validateGenericResourceValues = XNAT.validate('input.resource-value').chain(); - validateGenericResourceValues.is('notEmpty').failure('Resource values are required'); - validators.push(validateGenericResourceValues); - } - - // Validate the form - let errorMessages = []; - - validators.forEach((validator) => { - if (!validator.check()) { - validator.messages.forEach(message => errorMessages.push(message)); - } - }); - - if (errorMessages.length > 0) { - XNAT.dialog.open({ - title: 'Error', - width: 400, - content: '
  • ' + errorMessages.join('
  • ') + '
', - }) - return; - } - - config = { - id: idElement.value, - hardware: { - name: nameElement.value, - cpuReservation: cpuReservationElement.value, - cpuLimit: cpuLimitElement.value, - memoryReservation: memoryReservationElement.value, - memoryLimit: memoryLimitElement.value, - environmentVariables: getEnvironmentVariables(), - constraints: getSwarmConstraints(), - genericResources: getGenericResources(), - }, - scopes: { - Site: { - scope: 'Site', - enabled: siteEnabledElement.checked, - }, - Project: { - scope: 'Project', - enabled: allProjectsEnabledElement.checked, - ids: Array.from(enabledProjectsElement.selectedOptions).map(option => option.value), - }, - User: { - scope: 'User', - enabled: allUsersEnabledElement.checked, - ids: Array.from(enabledUsersElement.selectedOptions).map(option => option.value), - }, - } - } - - XNAT.compute.hardwareConfigs.save(config).then(() => { - XNAT.ui.banner.top(2000, 'Hardware saved', 'success'); - XNAT.dialog.closeAll(); - refreshTable(); - }).catch(err => { - XNAT.ui.banner.top(4000, 'Error Saving Hardware', 'error'); - console.error(err); - }); - } - }, - { - label: 'Cancel', - close: true, - isDefault: false - } - ] - }) - - } - - const refreshTable = () => { - XNAT.compute.hardwareConfigs.getAll().then(data => { - hardwareConfigs = data; - - if (hardwareConfigs.length === 0) { - clearContainer(); - container.innerHTML = `

No Hardware found

`; - return; - } - - // Sort the hardware configs by name - hardwareConfigs = hardwareConfigs.sort((a, b) => { - if (a.name < b.name) { - return -1; - } - if (a.name > b.name) { - return 1; - } - return 0; - }); - - renderTable(); - }).catch(err => { - console.error(err); - clearContainer(); - container.innerHTML = `

Error loading Hardware

`; - }); - } - - const deleteConfig = (id) => { - XNAT.compute.hardwareConfigs.delete(id).then(() => { - XNAT.ui.banner.top(2000, 'Hardware config deleted', 'success'); - refreshTable(); - }).catch(err => { - XNAT.ui.banner.top(4000, 'Error deleting hardware config', 'error'); - console.error(err); - }); - } - - const addEnvironmentVariable = (envVar) => { - const formEl = document.getElementById('config-editor'); - const environmentVariablesEl = formEl.querySelector('div.environment-variables'); - - const keyEl = spawn('input.form-control.key', { - id: 'key', - placeholder: 'Key', - type: 'text', - value: envVar ? envVar.key : '', - }); - - const equalsEl = spawn('span.input-group-addon', { - style: { - display: 'flex', - flexDirection: 'column', - justifyContent: 'center', - } - }, ['=']); - - const valueEl = spawn('input.form-control.value', { - id: 'value', - placeholder: 'Value', - type: 'text', - value: envVar ? envVar.value : '', - }); - - const removeButtonEl = spawn('button.btn.btn-danger', { - type: 'button', - title: 'Remove', - onclick: () => { - environmentVariableEl.remove(); - } - }, [ - spawn('i.fa.fa-trash'), - ]); - - const environmentVariableEl = spawn('div.form-group', { - style: { - marginBottom: '5px', - } - }, [ - spawn('div.input-group', { - style: { - display: 'flex', - flexDirection: 'row', - justifyContent: 'center', - columnGap: '10px', - } - }, [ - keyEl, - equalsEl, - valueEl, - spawn('span.input-group-btn', [ - removeButtonEl, - ]), - ]), - ]); - - environmentVariablesEl.appendChild(environmentVariableEl); - } - - const getEnvironmentVariables = () => { - const formEl = document.getElementById('config-editor'); - const environmentVariablesEl = formEl.querySelector('div.environment-variables'); - - let environmentVariables = []; - - Array.from(environmentVariablesEl.children).forEach((environmentVariableEl) => { - const keyEl = environmentVariableEl.querySelector('#key'); - const valueEl = environmentVariableEl.querySelector('#value'); - - if (keyEl === null || valueEl === null) return; - - environmentVariables.push({ - key: keyEl.value, - value: valueEl.value, - }); - }); - - return environmentVariables; - } - - const addSwarmConstraint = (placementConstraint) => { - const formEl = document.getElementById('config-editor'); - const placementConstraintsEl = formEl.querySelector('div.placement-constraints.swarm'); - - let removeButton = spawn('a.close', { - html: '', - onclick: () => { - placementConstraintGroup.remove(); - } - }); - - let attributeInput = XNAT.ui.panel.input.text({ - name: `swarm-constraint-attribute-${Math.floor(Math.random() * 1000000)}`, // random ID to avoid collisions - label: 'Node attribute', - classes: 'required swarm-constraint-attribute', - description: 'Attribute you wish to constrain. E.g., node.labels.mylabel or node.role', - value: placementConstraint ? placementConstraint.key : '', - }); - - let operatorInput = XNAT.ui.panel.input.radioGroup({ - name: `constraint-operator-${Math.floor(Math.random() * 1000000)}`, // random ID to avoid collisions - label: 'Comparator', - classes: 'required swarm-constraint-operator', - items: { 0: { label: 'Equals', value: 'IN' }, 1: { label: 'Does not equal', value: 'NOT_IN' } }, - value: placementConstraint ? placementConstraint.operator : 'IN', - }) - - let valuesInput = XNAT.ui.panel.input.list({ - name: `placement-constraint-values-${Math.floor(Math.random() * 1000000)}`, // random ID to avoid collisions - label: 'Possible Values For Constraint', - classes: 'required swarm-constraint-values', - description: 'Comma-separated list of values on which user can constrain the attribute (or a single value if not user-settable). E.g., "worker" or "spot,demand" (do not add quotes). ', - value: placementConstraint ? placementConstraint.values.join(',') : '', - }) - - let placementConstraintGroup = spawn('div.swarm-constraint-group', { - style: { - border: '1px solid #ccc', - padding: '5px', - margin: '5px', - borderRadius: '10px', - } - }, [ - spawn('div.input-group', [ - removeButton, - attributeInput, - operatorInput, - valuesInput, - ]), - ]); - - placementConstraintsEl.appendChild(placementConstraintGroup); - } - - const getSwarmConstraints = () => { - const formEl = document.getElementById('config-editor'); - const constraintGroups = formEl.querySelectorAll('.swarm-constraint-group'); - - let placementConstraints = []; - - Array.from(constraintGroups).forEach((group) => { - if (group === null) return; - - const attributeEl = group.querySelector('.swarm-constraint-attribute'); - const operatorEl = group.querySelector('.swarm-constraint-operator input:checked'); - const valuesEl = group.querySelector('.swarm-constraint-values'); - - if (attributeEl === null || operatorEl === null || valuesEl === null) return; - - placementConstraints.push({ - key: attributeEl.value, - operator: operatorEl.value, - values: valuesEl.value.split(',').map((value) => value.trim()), - }); - }); - - return placementConstraints; - } - - const addGenericResource = (resource) => { - const formEl = document.getElementById('config-editor'); - const resourcesEl = formEl.querySelector('div.generic-resources'); - - let removeButton = spawn('a.close', { - html: '', - onclick: () => { - resourceGroup.remove(); - } - }); - - let nameInput = XNAT.ui.panel.input.text({ - name: `resource-name-${Math.floor(Math.random() * 1000000)}`, // random ID to avoid collisions - label: 'Name', - classes: 'required resource-name', - description: 'Name of the resource. E.g., GPU', - value: resource ? resource.name : '', - }); - - let valueInput = XNAT.ui.panel.input.text({ - name: `resource-value-${Math.floor(Math.random() * 1000000)}`, // random ID to avoid collisions - label: 'Value', - classes: 'required resource-value', - description: 'Value of the resource. E.g., 1', - value: resource ? resource.value : '', - }); - - let resourceGroup = spawn('div.resource-group', { - style: { - border: '1px solid #ccc', - padding: '5px', - margin: '5px', - borderRadius: '10px', - } - }, [ - spawn('div.input-group', [ - removeButton, - nameInput, - valueInput, - ]), - ]); - - resourcesEl.appendChild(resourceGroup); - } - - const getGenericResources = () => { - const formEl = document.getElementById('config-editor'); - const resourceGroups = formEl.querySelectorAll('.resource-group'); - - let resources = []; - - Array.from(resourceGroups).forEach((group) => { - if (group === null) return; - - const nameEl = group.querySelector('.resource-name'); - const valueEl = group.querySelector('.resource-value'); - - if (nameEl === null || valueEl === null) return; - - resources.push({ - name: nameEl.value, - value: valueEl.value, - }); - }); - - return resources; - } - - const renderTable = () => { - let table = XNAT.table.dataTable(hardwareConfigs, { - header: true, - sortable: 'name', - columns: { - name: { - label: 'Name', - filter: true, - td: { className: 'word-wrapped align-top' }, - apply: function () { - return this.hardware?.name || 'N/A'; - } - }, - cpu: { - label: 'CPU Res / Lim', - filter: true, - apply: function () { - let cpuReservation = this.hardware?.cpuReservation || '-'; - let cpuLimit = this.hardware?.cpuLimit || '-'; - return spawn('div.center', `${cpuReservation} / ${cpuLimit}`); - } - }, - memory: { - label: 'Memory Res / Lim', - filter: true, - apply: function () { - let memoryReservation = this.hardware?.memoryReservation || '-'; - let memoryLimit = this.hardware?.memoryLimit || '-'; - return spawn('div.center', `${memoryReservation} / ${memoryLimit}`); - } - }, - projects: { - label: 'Project(s)', - filter: true, - td: { className: 'projects word-wrapped align-top' }, - apply: function () { - return displayProjects(this); - } - }, - users: { - label: 'User(s)', - filter: true, - td: { className: 'users word-wrapped align-top' }, - apply: function () { - return displayUsers(this); - }, - }, - enabled: { - label: 'Enabled', - apply: function () { - return spawn('div.center', [enabledToggle(this)]); - }, - }, - actions: { - label: 'Actions', - th: { style: { width: '150px' } }, - apply: function () { - return spawn('div.center', [ - spawn('button.btn.btn-sm', - { onclick: () => editor(this, 'edit') }, - '' - ), - spawn('span', { style: { display: 'inline-block', width: '4px' } }), - spawn('button.btn.btn-sm', - { onclick: () => editor(this, 'copy') }, - '' - ), - spawn('span', { style: { display: 'inline-block', width: '4px' } }), - spawn('button.btn.btn-sm', - { onclick: () => deleteConfig(this.id) }, - '' - ) - ]); - }, - } - } - }) - - clearContainer(); - table.render(`#${containerId}`); - } - - init(); - - return { - container: container, - hardwareConfigs: hardwareConfigs, - refreshTable: refreshTable - } - } - -})); \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/config/ComputeEnvironmentConfigsApiConfig.java b/src/test/java/org/nrg/xnat/compute/config/ComputeEnvironmentConfigsApiConfig.java deleted file mode 100644 index bd20e1c..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/ComputeEnvironmentConfigsApiConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.nrg.framework.services.ContextService; -import org.nrg.xnat.compute.rest.ComputeEnvironmentConfigsApi; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigService; -import org.nrg.xdat.security.services.RoleHolder; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.security.authentication.TestingAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -@Configuration -@EnableWebMvc -@EnableWebSecurity -@Import({MockConfig.class, RestApiTestConfig.class}) -public class ComputeEnvironmentConfigsApiConfig extends WebSecurityConfigurerAdapter { - - @Bean - public ComputeEnvironmentConfigsApi computeEnvironmentConfigsApi(final UserManagementServiceI mockUserManagementService, - final RoleHolder mockRoleHolder, - final ComputeEnvironmentConfigService mockComputeEnvironmentConfigService) { - return new ComputeEnvironmentConfigsApi( - mockUserManagementService, - mockRoleHolder, - mockComputeEnvironmentConfigService - ); - } - - @Bean - public ContextService contextService(final ApplicationContext applicationContext) { - final ContextService contextService = new ContextService(); - contextService.setApplicationContext(applicationContext); - return contextService; - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) { - auth.authenticationProvider(new TestingAuthenticationProvider()); - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/ConstraintConfigsApiTestConfig.java b/src/test/java/org/nrg/xnat/compute/config/ConstraintConfigsApiTestConfig.java deleted file mode 100644 index 5e7fb16..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/ConstraintConfigsApiTestConfig.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.nrg.framework.services.ContextService; -import org.nrg.xnat.compute.rest.ConstraintConfigsApi; -import org.nrg.xnat.compute.services.ConstraintConfigService; -import org.nrg.xdat.security.services.RoleHolder; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.security.authentication.TestingAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -@Configuration -@EnableWebMvc -@EnableWebSecurity -@Import({MockConfig.class, RestApiTestConfig.class}) -public class ConstraintConfigsApiTestConfig extends WebSecurityConfigurerAdapter { - - @Bean - public ConstraintConfigsApi placementConstraintConfigsApi(final UserManagementServiceI mockUserManagementService, - final RoleHolder mockRoleHolder, - final ConstraintConfigService mockConstraintConfigService) { - return new ConstraintConfigsApi( - mockUserManagementService, - mockRoleHolder, - mockConstraintConfigService - ); - } - - @Bean - public ContextService contextService(final ApplicationContext applicationContext) { - final ContextService contextService = new ContextService(); - contextService.setApplicationContext(applicationContext); - return contextService; - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) { - auth.authenticationProvider(new TestingAuthenticationProvider()); - } -} diff --git a/src/test/java/org/nrg/xnat/compute/config/DefaultComputeEnvironmentConfigServiceTestConfig.java b/src/test/java/org/nrg/xnat/compute/config/DefaultComputeEnvironmentConfigServiceTestConfig.java deleted file mode 100644 index 5064e54..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/DefaultComputeEnvironmentConfigServiceTestConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigEntityService; -import org.nrg.xnat.compute.services.HardwareConfigEntityService; -import org.nrg.xnat.compute.services.impl.DefaultComputeEnvironmentConfigService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -@Configuration -@Import({HibernateEntityServicesConfig.class}) -public class DefaultComputeEnvironmentConfigServiceTestConfig { - - @Bean - public DefaultComputeEnvironmentConfigService defaultComputeEnvironmentConfigService(final ComputeEnvironmentConfigEntityService computeEnvironmentConfigEntityService, - final HardwareConfigEntityService hardwareConfigEntityService) { - return new DefaultComputeEnvironmentConfigService( - computeEnvironmentConfigEntityService, - hardwareConfigEntityService - ); - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/DefaultConstraintConfigServiceTestConfig.java b/src/test/java/org/nrg/xnat/compute/config/DefaultConstraintConfigServiceTestConfig.java deleted file mode 100644 index d984e94..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/DefaultConstraintConfigServiceTestConfig.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.nrg.xnat.compute.services.ConstraintConfigEntityService; -import org.nrg.xnat.compute.services.impl.DefaultConstraintConfigService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -@Configuration -@Import({HibernateEntityServicesConfig.class}) -public class DefaultConstraintConfigServiceTestConfig { - - @Bean - public DefaultConstraintConfigService defaultConstraintConfigService(final ConstraintConfigEntityService constraintConfigEntityService) { - return new DefaultConstraintConfigService( - constraintConfigEntityService - ); - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/DefaultHardwareConfigServiceTestConfig.java b/src/test/java/org/nrg/xnat/compute/config/DefaultHardwareConfigServiceTestConfig.java deleted file mode 100644 index a53ef0d..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/DefaultHardwareConfigServiceTestConfig.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigEntityService; -import org.nrg.xnat.compute.services.HardwareConfigEntityService; -import org.nrg.xnat.compute.services.impl.DefaultHardwareConfigService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -@Configuration -@Import({HibernateEntityServicesConfig.class}) -public class DefaultHardwareConfigServiceTestConfig { - - @Bean - public DefaultHardwareConfigService defaultHardwareConfigService(final HardwareConfigEntityService hardwareConfigEntityService, - final ComputeEnvironmentConfigEntityService computeEnvironmentConfigEntityService) { - return new DefaultHardwareConfigService( - hardwareConfigEntityService, - computeEnvironmentConfigEntityService - ); - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/DefaultJobTemplateServiceTestConfig.java b/src/test/java/org/nrg/xnat/compute/config/DefaultJobTemplateServiceTestConfig.java deleted file mode 100644 index 190e3be..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/DefaultJobTemplateServiceTestConfig.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigService; -import org.nrg.xnat.compute.services.ConstraintConfigService; -import org.nrg.xnat.compute.services.HardwareConfigService; -import org.nrg.xnat.compute.services.impl.DefaultJobTemplateService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -@Configuration -@Import({MockConfig.class}) -public class DefaultJobTemplateServiceTestConfig { - - @Bean - public DefaultJobTemplateService defaultJobTemplateService(final ComputeEnvironmentConfigService mockComputeEnvironmentConfigService, - final HardwareConfigService mockHardwareConfigService, - final ConstraintConfigService mockConstraintConfigService) { - return new DefaultJobTemplateService( - mockComputeEnvironmentConfigService, - mockHardwareConfigService, - mockConstraintConfigService - ); - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/HardwareConfigsApiConfig.java b/src/test/java/org/nrg/xnat/compute/config/HardwareConfigsApiConfig.java deleted file mode 100644 index 0571b52..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/HardwareConfigsApiConfig.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.nrg.framework.services.ContextService; -import org.nrg.xnat.compute.rest.HardwareConfigsApi; -import org.nrg.xnat.compute.services.HardwareConfigService; -import org.nrg.xdat.security.services.RoleHolder; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.security.authentication.TestingAuthenticationProvider; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.web.servlet.config.annotation.EnableWebMvc; - -@Configuration -@EnableWebMvc -@EnableWebSecurity -@Import({MockConfig.class, RestApiTestConfig.class}) -public class HardwareConfigsApiConfig extends WebSecurityConfigurerAdapter { - - @Bean - public HardwareConfigsApi hardwareConfigsApi(final UserManagementServiceI mockUserManagementService, - final RoleHolder mockRoleHolder, - final HardwareConfigService mockHardwareConfigService) { - return new HardwareConfigsApi( - mockUserManagementService, - mockRoleHolder, - mockHardwareConfigService - ); - } - - @Bean - public ContextService contextService(final ApplicationContext applicationContext) { - final ContextService contextService = new ContextService(); - contextService.setApplicationContext(applicationContext); - return contextService; - } - - @Override - protected void configure(AuthenticationManagerBuilder auth) { - auth.authenticationProvider(new TestingAuthenticationProvider()); - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/HibernateComputeEnvironmentConfigEntityServiceTestConfig.java b/src/test/java/org/nrg/xnat/compute/config/HibernateComputeEnvironmentConfigEntityServiceTestConfig.java deleted file mode 100644 index d8c46dc..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/HibernateComputeEnvironmentConfigEntityServiceTestConfig.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.hibernate.SessionFactory; -import org.nrg.xnat.compute.entities.*; -import org.nrg.xnat.compute.repositories.ComputeEnvironmentConfigDao; -import org.nrg.xnat.compute.repositories.ConstraintConfigDao; -import org.nrg.xnat.compute.repositories.HardwareConfigDao; -import org.nrg.xnat.compute.services.impl.HibernateComputeEnvironmentConfigEntityService; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; -import org.springframework.transaction.support.ResourceTransactionManager; - -import javax.sql.DataSource; -import java.util.Properties; - -@Configuration -@Import({HibernateConfig.class}) -public class HibernateComputeEnvironmentConfigEntityServiceTestConfig { - - @Bean - public HibernateComputeEnvironmentConfigEntityService hibernateComputeEnvironmentConfigEntityServiceTest(@Qualifier("computeEnvironmentConfigDaoImpl") final ComputeEnvironmentConfigDao computeEnvironmentConfigDaoImpl, - @Qualifier("hardwareConfigDaoImpl") final HardwareConfigDao hardwareConfigDaoImpl) { - return new HibernateComputeEnvironmentConfigEntityService( - computeEnvironmentConfigDaoImpl, - hardwareConfigDaoImpl); - } - - @Bean - public LocalSessionFactoryBean sessionFactory(final DataSource dataSource, @Qualifier("hibernateProperties") final Properties properties) { - final LocalSessionFactoryBean bean = new LocalSessionFactoryBean(); - bean.setDataSource(dataSource); - bean.setHibernateProperties(properties); - bean.setAnnotatedClasses( - ConstraintConfigEntity.class, - ConstraintEntity.class, - ConstraintScopeEntity.class, - ComputeEnvironmentConfigEntity.class, - ComputeEnvironmentEntity.class, - ComputeEnvironmentScopeEntity.class, - ComputeEnvironmentHardwareOptionsEntity.class, - HardwareConfigEntity.class, - HardwareEntity.class, - HardwareScopeEntity.class, - HardwareConstraintEntity.class, - EnvironmentVariableEntity.class, - MountEntity.class, - GenericResourceEntity.class - ); - return bean; - } - - @Bean - public ResourceTransactionManager transactionManager(final SessionFactory sessionFactory) throws Exception { - return new HibernateTransactionManager(sessionFactory); - } - - @Bean - public ConstraintConfigDao constraintConfigDao(final SessionFactory sessionFactory) { - return new ConstraintConfigDao(sessionFactory); - } - - @Bean - @Qualifier("hardwareConfigDaoImpl") - public HardwareConfigDao hardwareConfigDaoImpl(final SessionFactory sessionFactory) { - return new HardwareConfigDao(sessionFactory); - } - - @Bean - @Qualifier("computeEnvironmentConfigDaoImpl") - public ComputeEnvironmentConfigDao computeEnvironmentConfigDaoImpl(final SessionFactory sessionFactory, - final @Qualifier("hardwareConfigDaoImpl") HardwareConfigDao hardwareConfigDaoImpl) { - return new ComputeEnvironmentConfigDao(sessionFactory, hardwareConfigDaoImpl); - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/HibernateConfig.java b/src/test/java/org/nrg/xnat/compute/config/HibernateConfig.java deleted file mode 100644 index 472d9af..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/HibernateConfig.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.apache.commons.dbcp2.BasicDataSource; -import org.hibernate.SessionFactory; -import org.nrg.xnat.compute.entities.*; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.config.PropertiesFactoryBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; -import org.springframework.transaction.support.ResourceTransactionManager; - -import javax.sql.DataSource; -import java.io.IOException; -import java.util.Properties; - -@Configuration -public class HibernateConfig { - @Bean - public Properties hibernateProperties() throws IOException { - Properties properties = new Properties(); - - // Use HSQLDialect instead of H2Dialect to work around issue - // with h2 version 1.4.200 in hibernate < 5.4 (or so) - // where the generated statements to drop tables between tests can't be executed - // as they do not cascade. - // See https://hibernate.atlassian.net/browse/HHH-13711 - // Solution from https://github.com/hibernate/hibernate-orm/pull/3093#issuecomment-562752874 - properties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); - properties.put("hibernate.hbm2ddl.auto", "create"); - properties.put("hibernate.cache.use_second_level_cache", false); - properties.put("hibernate.cache.use_query_cache", false); - - PropertiesFactoryBean hibernate = new PropertiesFactoryBean(); - hibernate.setProperties(properties); - hibernate.afterPropertiesSet(); - return hibernate.getObject(); - } - - @Bean - public DataSource dataSource() { - BasicDataSource basicDataSource = new BasicDataSource(); - basicDataSource.setDriverClassName(org.h2.Driver.class.getName()); - basicDataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); - basicDataSource.setUsername("sa"); - return basicDataSource; - } - - @Bean - public LocalSessionFactoryBean sessionFactory(final DataSource dataSource, @Qualifier("hibernateProperties") final Properties properties) { - final LocalSessionFactoryBean bean = new LocalSessionFactoryBean(); - bean.setDataSource(dataSource); - bean.setHibernateProperties(properties); - bean.setAnnotatedClasses( - ConstraintConfigEntity.class, - ConstraintEntity.class, - ConstraintScopeEntity.class, - ComputeEnvironmentConfigEntity.class, - ComputeEnvironmentEntity.class, - ComputeEnvironmentScopeEntity.class, - ComputeEnvironmentHardwareOptionsEntity.class, - HardwareConfigEntity.class, - HardwareEntity.class, - HardwareScopeEntity.class, - HardwareConstraintEntity.class, - EnvironmentVariableEntity.class, - MountEntity.class, - GenericResourceEntity.class - ); - return bean; - } - - @Bean - public ResourceTransactionManager transactionManager(final SessionFactory sessionFactory) throws Exception { - return new HibernateTransactionManager(sessionFactory); - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/HibernateConstraintConfigEntityServiceTestConfig.java b/src/test/java/org/nrg/xnat/compute/config/HibernateConstraintConfigEntityServiceTestConfig.java deleted file mode 100644 index b1f228c..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/HibernateConstraintConfigEntityServiceTestConfig.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.hibernate.SessionFactory; -import org.nrg.xnat.compute.entities.*; -import org.nrg.xnat.compute.repositories.ConstraintConfigDao; -import org.nrg.xnat.compute.services.impl.HibernateConstraintConfigEntityService; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; -import org.springframework.transaction.support.ResourceTransactionManager; - -import javax.sql.DataSource; -import java.util.Properties; - -@Configuration -@Import({MockConfig.class, HibernateConfig.class}) -public class HibernateConstraintConfigEntityServiceTestConfig { - - @Bean - public HibernateConstraintConfigEntityService hibernateConstraintConfigEntityServiceTest() { - return new HibernateConstraintConfigEntityService(); - } - - @Bean - public LocalSessionFactoryBean sessionFactory(final DataSource dataSource, @Qualifier("hibernateProperties") final Properties properties) { - final LocalSessionFactoryBean bean = new LocalSessionFactoryBean(); - bean.setDataSource(dataSource); - bean.setHibernateProperties(properties); - bean.setAnnotatedClasses( - ConstraintConfigEntity.class, - ConstraintEntity.class, - ConstraintScopeEntity.class, - ComputeEnvironmentConfigEntity.class, - ComputeEnvironmentEntity.class, - ComputeEnvironmentScopeEntity.class, - ComputeEnvironmentHardwareOptionsEntity.class, - HardwareConfigEntity.class, - HardwareEntity.class, - HardwareScopeEntity.class, - HardwareConstraintEntity.class, - EnvironmentVariableEntity.class, - MountEntity.class, - GenericResourceEntity.class - ); - return bean; - } - - @Bean - public ResourceTransactionManager transactionManager(final SessionFactory sessionFactory) throws Exception { - return new HibernateTransactionManager(sessionFactory); - } - - @Bean - public ConstraintConfigDao constraintConfigDao(final SessionFactory sessionFactory) { - return new ConstraintConfigDao(sessionFactory); - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/HibernateEntityServicesConfig.java b/src/test/java/org/nrg/xnat/compute/config/HibernateEntityServicesConfig.java deleted file mode 100644 index eb3ef86..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/HibernateEntityServicesConfig.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.hibernate.SessionFactory; -import org.nrg.xnat.compute.repositories.ComputeEnvironmentConfigDao; -import org.nrg.xnat.compute.repositories.ConstraintConfigDao; -import org.nrg.xnat.compute.repositories.HardwareConfigDao; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigEntityService; -import org.nrg.xnat.compute.services.ConstraintConfigEntityService; -import org.nrg.xnat.compute.services.HardwareConfigEntityService; -import org.nrg.xnat.compute.services.impl.HibernateComputeEnvironmentConfigEntityService; -import org.nrg.xnat.compute.services.impl.HibernateConstraintConfigEntityService; -import org.nrg.xnat.compute.services.impl.HibernateHardwareConfigEntityService; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -@Configuration -@Import({HibernateConfig.class}) -public class HibernateEntityServicesConfig { - - @Bean - public ConstraintConfigDao constraintConfigDao(final SessionFactory sessionFactory) { - return new ConstraintConfigDao(sessionFactory); - } - - @Bean - public ConstraintConfigEntityService constraintConfigEntityService(final ConstraintConfigDao constraintConfigDao) { - HibernateConstraintConfigEntityService service = new HibernateConstraintConfigEntityService(); - service.setDao(constraintConfigDao); - return service; - } - - @Bean - public HardwareConfigDao hardwareConfigDao(final SessionFactory sessionFactory) { - return new HardwareConfigDao(sessionFactory); - } - - @Bean - public ComputeEnvironmentConfigDao computeEnvironmentConfigDao(final SessionFactory sessionFactory, - final HardwareConfigDao hardwareConfigDao) { - return new ComputeEnvironmentConfigDao(sessionFactory, hardwareConfigDao); - } - - @Bean - public ComputeEnvironmentConfigEntityService computeEnvironmentConfigEntityService(final ComputeEnvironmentConfigDao computeEnvironmentConfigDao, - final HardwareConfigDao hardwareConfigDao) { - return new HibernateComputeEnvironmentConfigEntityService( - computeEnvironmentConfigDao, - hardwareConfigDao - ); - } - - @Bean - public HardwareConfigEntityService hardwareConfigEntityService(final HardwareConfigDao hardwareConfigDao) { - HibernateHardwareConfigEntityService service = new HibernateHardwareConfigEntityService(); - service.setDao(hardwareConfigDao); - return service; - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/HibernateHardwareConfigEntityServiceTestConfig.java b/src/test/java/org/nrg/xnat/compute/config/HibernateHardwareConfigEntityServiceTestConfig.java deleted file mode 100644 index 71efe1b..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/HibernateHardwareConfigEntityServiceTestConfig.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.hibernate.SessionFactory; -import org.nrg.xnat.compute.entities.*; -import org.nrg.xnat.compute.repositories.ConstraintConfigDao; -import org.nrg.xnat.compute.services.impl.HibernateHardwareConfigEntityService; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.orm.hibernate4.HibernateTransactionManager; -import org.springframework.orm.hibernate4.LocalSessionFactoryBean; -import org.springframework.transaction.support.ResourceTransactionManager; - -import javax.sql.DataSource; -import java.util.Properties; - -@Configuration -@Import({MockConfig.class, HibernateConfig.class}) -public class HibernateHardwareConfigEntityServiceTestConfig { - - @Bean - public HibernateHardwareConfigEntityService hibernateHardwareConfigEntityServiceTest() { - return new HibernateHardwareConfigEntityService(); - } - - @Bean - public LocalSessionFactoryBean sessionFactory(final DataSource dataSource, @Qualifier("hibernateProperties") final Properties properties) { - final LocalSessionFactoryBean bean = new LocalSessionFactoryBean(); - bean.setDataSource(dataSource); - bean.setHibernateProperties(properties); - bean.setAnnotatedClasses( - ConstraintConfigEntity.class, - ConstraintEntity.class, - ConstraintScopeEntity.class, - ComputeEnvironmentConfigEntity.class, - ComputeEnvironmentEntity.class, - ComputeEnvironmentScopeEntity.class, - ComputeEnvironmentHardwareOptionsEntity.class, - HardwareConfigEntity.class, - HardwareEntity.class, - HardwareScopeEntity.class, - HardwareConstraintEntity.class, - EnvironmentVariableEntity.class, - MountEntity.class, - GenericResourceEntity.class - ); - return bean; - } - - @Bean - public ResourceTransactionManager transactionManager(final SessionFactory sessionFactory) throws Exception { - return new HibernateTransactionManager(sessionFactory); - } - - @Bean - public ConstraintConfigDao constraintConfigDao(final SessionFactory sessionFactory) { - return new ConstraintConfigDao(sessionFactory); - } - -} diff --git a/src/test/java/org/nrg/xnat/compute/config/MockConfig.java b/src/test/java/org/nrg/xnat/compute/config/MockConfig.java deleted file mode 100644 index 11ff2ec..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/MockConfig.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.nrg.xnat.compute.config; - -import org.mockito.Mockito; -import org.nrg.framework.services.SerializerService; -import org.nrg.xnat.compute.repositories.ComputeEnvironmentConfigDao; -import org.nrg.xnat.compute.repositories.HardwareConfigDao; -import org.nrg.xdat.security.services.RoleHolder; -import org.nrg.xdat.security.services.RoleServiceI; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.nrg.xnat.compute.services.*; -import org.nrg.xnat.services.XnatAppInfo; -import org.nrg.xnatx.plugins.jupyterhub.utils.XFTManagerHelper; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; - -@Configuration -public class MockConfig { - - @Bean - public NamedParameterJdbcTemplate mockNamedParameterJdbcTemplate() { - return Mockito.mock(NamedParameterJdbcTemplate.class); - } - - @Bean - public UserManagementServiceI mockUserManagementServiceI() { - return Mockito.mock(UserManagementServiceI.class); - } - - @Bean - @Qualifier("mockRoleService") - public RoleServiceI mockRoleService() { - return Mockito.mock(RoleServiceI.class); - } - - @Bean - public RoleHolder mockRoleHolder(@Qualifier("mockRoleService") final RoleServiceI mockRoleService, - final NamedParameterJdbcTemplate mockNamedParameterJdbcTemplate) { - return new RoleHolder(mockRoleService, mockNamedParameterJdbcTemplate); - } - - @Bean - public XFTManagerHelper mockXFTManagerHelper() { - return Mockito.mock(XFTManagerHelper.class); - } - - @Bean - public SerializerService mockSerializerService() { - return Mockito.mock(SerializerService.class); - } - - @Bean - public XnatAppInfo mockXnatAppInfo() { - return Mockito.mock(XnatAppInfo.class); - } - - @Bean - public ConstraintConfigService mockPlacementConstraintConfigService() { - return Mockito.mock(ConstraintConfigService.class); - } - - @Bean - public ComputeEnvironmentConfigService mockComputeEnvironmentConfigService() { - return Mockito.mock(ComputeEnvironmentConfigService.class); - } - - @Bean - @Qualifier("mockComputeEnvironmentConfigEntityService") - public ComputeEnvironmentConfigEntityService mockComputeEnvironmentConfigEntityService() { - return Mockito.mock(ComputeEnvironmentConfigEntityService.class); - } - - @Bean - public HardwareConfigService mockHardwareConfigService() { - return Mockito.mock(HardwareConfigService.class); - } - - @Bean - @Qualifier("mockHardwareConfigEntityService") - public HardwareConfigEntityService mockHardwareConfigEntityService() { - return Mockito.mock(HardwareConfigEntityService.class); - } - - @Bean - @Qualifier("mockHardwareConfigDao") - public HardwareConfigDao mockHardwareConfigDao() { - return Mockito.mock(HardwareConfigDao.class); - } - - @Bean - @Qualifier("mockComputeEnvironmentConfigDao") - public ComputeEnvironmentConfigDao mockComputeEnvironmentConfigDao() { - return Mockito.mock(ComputeEnvironmentConfigDao.class); - } - - @Bean - public JobTemplateService mockJobTemplateService() { - return Mockito.mock(JobTemplateService.class); - } - - @Bean - public ConstraintConfigEntityService mockConstraintConfigEntityService() { - return Mockito.mock(ConstraintConfigEntityService.class); - } -} diff --git a/src/test/java/org/nrg/xnat/compute/config/ObjectMapperConfig.java b/src/test/java/org/nrg/xnat/compute/config/ObjectMapperConfig.java deleted file mode 100644 index eb5b5ad..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/ObjectMapperConfig.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.nrg.xnat.compute.config; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.guava.GuavaModule; -import com.fasterxml.jackson.datatype.hibernate4.Hibernate4Module; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; - -@Configuration -public class ObjectMapperConfig { - @Bean - public Jackson2ObjectMapperBuilder objectMapperBuilder() { - return new Jackson2ObjectMapperBuilder() - .serializationInclusion(JsonInclude.Include.NON_NULL) - .failOnEmptyBeans(false) - .featuresToEnable(JsonParser.Feature.ALLOW_SINGLE_QUOTES, JsonParser.Feature.ALLOW_YAML_COMMENTS) - .featuresToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS, SerializationFeature.WRITE_NULL_MAP_VALUES) - .modulesToInstall(new Hibernate4Module(), new GuavaModule()); - } - - @Bean - public ObjectMapper objectMapper() { - return objectMapperBuilder().build(); - } -} diff --git a/src/test/java/org/nrg/xnat/compute/config/RestApiTestConfig.java b/src/test/java/org/nrg/xnat/compute/config/RestApiTestConfig.java deleted file mode 100644 index 6016ff6..0000000 --- a/src/test/java/org/nrg/xnat/compute/config/RestApiTestConfig.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.nrg.xnat.compute.config; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.mockito.Mockito; -import org.nrg.mail.services.MailService; -import org.nrg.xdat.security.services.RoleHolder; -import org.nrg.xdat.security.services.RoleServiceI; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.nrg.xnat.services.XnatAppInfo; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; -import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; -import org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; - -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import static org.mockito.Mockito.when; - -@Configuration -@Import({ObjectMapperConfig.class}) -public class RestApiTestConfig extends WebMvcConfigurerAdapter { - @Bean - @Qualifier("mockXnatAppInfo") - public XnatAppInfo mockAppInfo() { - XnatAppInfo mockXnatAppInfo = Mockito.mock(XnatAppInfo.class); - when(mockXnatAppInfo.isPrimaryNode()).thenReturn(true); - return mockXnatAppInfo; - } - - @Bean - public ExecutorService executorService() { - return Executors.newCachedThreadPool(); - } - - @Bean - public ThreadPoolExecutorFactoryBean syncThreadPoolExecutorFactoryBean(ExecutorService executorService) { - ThreadPoolExecutorFactoryBean tBean = Mockito.mock(ThreadPoolExecutorFactoryBean.class); - when(tBean.getObject()).thenReturn(executorService); - return tBean; - } - - @Bean - public MailService mockMailService() { - return Mockito.mock(MailService.class); - } - - @Bean - @Qualifier("mockRoleService") - public RoleServiceI mockRoleService() { - return Mockito.mock(RoleServiceI.class); - } - - @Bean - public RoleHolder mockRoleHolder(@Qualifier("mockRoleService") final RoleServiceI roleServiceI, - final NamedParameterJdbcTemplate namedParameterJdbcTemplate) { - return new RoleHolder(roleServiceI, namedParameterJdbcTemplate); - } - - @Bean - public NamedParameterJdbcTemplate mockNamedParameterJdbcTemplate() { - return Mockito.mock(NamedParameterJdbcTemplate.class); - } - - @Bean - public UserManagementServiceI mockUserManagementService() { - return Mockito.mock(UserManagementServiceI.class); - } - - @Override - public void configureMessageConverters(List> converters) { - converters.add(new StringHttpMessageConverter()); - converters.add(new MappingJackson2HttpMessageConverter(objectMapper)); - } - - @Autowired - private ObjectMapper objectMapper; -} diff --git a/src/test/java/org/nrg/xnat/compute/models/ConstraintTest.java b/src/test/java/org/nrg/xnat/compute/models/ConstraintTest.java deleted file mode 100644 index cfcb81d..0000000 --- a/src/test/java/org/nrg/xnat/compute/models/ConstraintTest.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.nrg.xnat.compute.models; - -import org.junit.Test; -import org.nrg.xnat.compute.models.Constraint; - -import java.util.Arrays; -import java.util.HashSet; - -import static org.junit.Assert.*; - -public class ConstraintTest { - - @Test - public void testListConversion_IN() { - Constraint constraint = Constraint.builder() - .key("node.instance.type") - .operator(Constraint.Operator.IN) - .values(new HashSet<>(Arrays.asList("spot", "demand"))) - .build(); - - assertEquals(Arrays.asList("node.instance.type==spot", "node.instance.type==demand"), constraint.toList()); - } - - @Test - public void testListConversion_NOT_IN() { - Constraint constraint = Constraint.builder() - .key("node.instance.type") - .operator(Constraint.Operator.NOT_IN) - .values(new HashSet<>(Arrays.asList("spot", "demand"))) - .build(); - - assertEquals(Arrays.asList("node.instance.type!=spot", "node.instance.type!=demand"), constraint.toList()); - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/rest/ComputeEnvironmentConfigsApiTest.java b/src/test/java/org/nrg/xnat/compute/rest/ComputeEnvironmentConfigsApiTest.java deleted file mode 100644 index 879a36d..0000000 --- a/src/test/java/org/nrg/xnat/compute/rest/ComputeEnvironmentConfigsApiTest.java +++ /dev/null @@ -1,239 +0,0 @@ -package org.nrg.xnat.compute.rest; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.nrg.framework.constants.Scope; -import org.nrg.xnat.compute.config.ComputeEnvironmentConfigsApiConfig; -import org.nrg.xnat.compute.models.ComputeEnvironmentConfig; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigService; -import org.nrg.xdat.security.services.RoleServiceI; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.nrg.xft.security.UserI; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.util.NestedServletException; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -import static org.mockito.Mockito.*; -import static org.springframework.http.MediaType.APPLICATION_JSON; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; -import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@WebAppConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {ComputeEnvironmentConfigsApiConfig.class}) -public class ComputeEnvironmentConfigsApiTest { - - @Autowired private WebApplicationContext wac; - @Autowired private ObjectMapper mapper; - @Autowired private RoleServiceI mockRoleService; - @Autowired private UserManagementServiceI mockUserManagementService; - @Autowired private ComputeEnvironmentConfigService mockComputeEnvironmentConfigService; - - private MockMvc mockMvc; - private UserI mockUser; - private Authentication mockAuthentication; - - private ComputeEnvironmentConfig computeEnvironmentConfig; - - @Before - public void before() throws Exception { - mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(springSecurity()).build(); - - // Mock the user - mockUser = Mockito.mock(UserI.class); - when(mockUser.getLogin()).thenReturn("mockUser"); - when(mockUser.getEmail()).thenReturn("mockUser@mockuser.com"); - when(mockUser.getPassword()).thenReturn("mockUserPassword"); - when(mockUser.getID()).thenReturn(1); - when(mockRoleService.isSiteAdmin(mockUser)).thenReturn(true); - mockAuthentication = new TestingAuthenticationToken(mockUser, mockUser.getPassword()); - - // Setup the compute environment config - computeEnvironmentConfig = new ComputeEnvironmentConfig(); - computeEnvironmentConfig.setId(1L); - } - - @After - public void after() throws Exception { - Mockito.reset( - mockRoleService, - mockUserManagementService, - mockComputeEnvironmentConfigService, - mockUser - ); - } - - @Test - public void testGetAllComputeEnvironmentConfigs() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/compute-environment-configs") - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify that the service was called - verify(mockComputeEnvironmentConfigService, times(1)).getAll(); - verify(mockComputeEnvironmentConfigService, never()).getByType(any()); - } - - @Test - public void testGetComputeEnvironmentConfigsByType() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/compute-environment-configs") - .param("type", "JUPYTERHUB") - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify that the service was called - verify(mockComputeEnvironmentConfigService, never()).getAll(); - verify(mockComputeEnvironmentConfigService, times(1)).getByType(any()); - } - - @Test - public void testGetComputeEnvironmentConfigById() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/compute-environment-configs/1") - .accept(APPLICATION_JSON) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - when(mockComputeEnvironmentConfigService.retrieve(any())).thenReturn(Optional.of(computeEnvironmentConfig)); - - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify that the service was called - verify(mockComputeEnvironmentConfigService, times(1)).retrieve(any()); - } - - @Test - public void testGetComputeEnvironmentConfigByIdNotFound() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/compute-environment-configs/1") - .accept(APPLICATION_JSON) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - when(mockComputeEnvironmentConfigService.retrieve(any())).thenReturn(Optional.empty()); - - mockMvc.perform(request).andExpect(status().isNotFound()); - - // Verify that the service was called - verify(mockComputeEnvironmentConfigService, times(1)).retrieve(any()); - } - - @Test - public void testCreateComputeEnvironmentConfig() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .post("/compute-environment-configs") - .accept(APPLICATION_JSON) - .contentType(APPLICATION_JSON) - .content(mapper.writeValueAsString(new ComputeEnvironmentConfig())) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - mockMvc.perform(request).andExpect(status().isCreated()); - - // Verify that the service was called - verify(mockComputeEnvironmentConfigService, times(1)).create(any()); - } - - @Test - public void testUpdateComputeEnvironmentConfig() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .put("/compute-environment-configs/1") - .accept(APPLICATION_JSON) - .contentType(APPLICATION_JSON) - .content(mapper.writeValueAsString(computeEnvironmentConfig)) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - when(mockComputeEnvironmentConfigService.retrieve(any())).thenReturn(Optional.of(computeEnvironmentConfig)); - - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify that the service was called - verify(mockComputeEnvironmentConfigService, times(1)).update(eq(computeEnvironmentConfig)); - } - - @Test(expected = NestedServletException.class) - public void testUpdateComputeEnvironmentConfig_IdMismatch() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .put("/compute-environment-configs/2") - .accept(APPLICATION_JSON) - .contentType(APPLICATION_JSON) - .content(mapper.writeValueAsString(computeEnvironmentConfig)) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - // Throws NestedServletException in response to IllegalArgumentException - mockMvc.perform(request).andExpect(status().isBadRequest()); - - // Verify that the service was not called - verify(mockComputeEnvironmentConfigService, never()).update(any()); - } - - @Test - public void testDeleteComputeEnvironmentConfig() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .delete("/compute-environment-configs/1") - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - mockMvc.perform(request).andExpect(status().isNoContent()); - - // Verify that the service was called - verify(mockComputeEnvironmentConfigService, times(1)).delete(eq(1L)); - } - - @Test - public void testGetAvailableComputeEnvironmentConfigs() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/compute-environment-configs/available") - .param("user", mockUser.getLogin()) - .param("prj", "projectId") - .param("datatype", "xnat:mrSessionData") - .param("type", "JUPYTERHUB") - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify that the service was called - Map expectedScopeMap = new HashMap<>(); - expectedScopeMap.put(Scope.User, mockUser.getLogin()); - expectedScopeMap.put(Scope.Project, "projectId"); - expectedScopeMap.put(Scope.DataType, "xnat:mrSessionData"); - verify(mockComputeEnvironmentConfigService, times(1)).getAvailable(eq(ComputeEnvironmentConfig.ConfigType.JUPYTERHUB), eq(expectedScopeMap)); - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/rest/ConstraintConfigsApiTest.java b/src/test/java/org/nrg/xnat/compute/rest/ConstraintConfigsApiTest.java deleted file mode 100644 index 9a08639..0000000 --- a/src/test/java/org/nrg/xnat/compute/rest/ConstraintConfigsApiTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package org.nrg.xnat.compute.rest; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.nrg.xnat.compute.config.ConstraintConfigsApiTestConfig; -import org.nrg.xnat.compute.models.ConstraintConfig; -import org.nrg.xnat.compute.services.ConstraintConfigService; -import org.nrg.xdat.security.services.RoleServiceI; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.nrg.xft.security.UserI; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.util.NestedServletException; - -import java.util.Optional; - -import static org.mockito.Mockito.*; -import static org.springframework.http.MediaType.APPLICATION_JSON; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; -import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@WebAppConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {ConstraintConfigsApiTestConfig.class}) -public class ConstraintConfigsApiTest { - - @Autowired private WebApplicationContext wac; - @Autowired private ObjectMapper mapper; - @Autowired private RoleServiceI mockRoleService; - @Autowired private UserManagementServiceI mockUserManagementService; - @Autowired private ConstraintConfigService mockConstraintConfigService; - - private MockMvc mockMvc; - private UserI mockUser; - private Authentication mockAuthentication; - - private ConstraintConfig constraintConfig; - - @Before - public void before() { - mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(springSecurity()).build(); - - // Mock the user - mockUser = Mockito.mock(UserI.class); - when(mockUser.getLogin()).thenReturn("mockUser"); - when(mockUser.getEmail()).thenReturn("mockUser@mockuser.com"); - when(mockUser.getPassword()).thenReturn("mockUserPassword"); - when(mockUser.getID()).thenReturn(1); - when(mockRoleService.isSiteAdmin(mockUser)).thenReturn(true); - mockAuthentication = new TestingAuthenticationToken(mockUser, mockUser.getPassword()); - - // Set up a PlacementConstraintConfig - constraintConfig = new ConstraintConfig(); - constraintConfig.setId(1L); - } - - @After - public void after() { - Mockito.reset( - mockRoleService, - mockUserManagementService, - mockConstraintConfigService - ); - } - - @Test - public void testGetPlacementConstraintConfig() throws Exception { - // Set up the request - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/constraint-configs/1") - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - // Set up the mocks - when(mockConstraintConfigService.retrieve(1L)).thenReturn(Optional.of(constraintConfig)); - - // Make the call - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify the mocks - verify(mockConstraintConfigService).retrieve(1L); - } - - @Test - public void testGetPlacementConstraintConfigNotFound() throws Exception { - // Set up the request - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/constraint-configs/1") - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - // Set up the mocks - when(mockConstraintConfigService.retrieve(1L)).thenReturn(Optional.empty()); - - // Make the call - mockMvc.perform(request).andExpect(status().isNotFound()); - - // Verify the mocks - verify(mockConstraintConfigService).retrieve(1L); - } - - @Test - public void testGetAllPlacementConstraintConfigs() throws Exception { - // Set up the request - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/constraint-configs") - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - // Make the call - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify the mocks - verify(mockConstraintConfigService).getAll(); - } - - @Test - public void testCreatePlacementConstraintConfig() throws Exception { - // Set up the request - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .post("/constraint-configs") - .contentType(APPLICATION_JSON) - .accept(APPLICATION_JSON) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()) - .content(mapper.writeValueAsString(constraintConfig)); - - // Make the call - mockMvc.perform(request).andExpect(status().isCreated()); - - // Verify the mocks - verify(mockConstraintConfigService).create(constraintConfig); - } - - @Test - public void testUpdatePlacementConstraintConfig() throws Exception { - // Set up the request - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .put("/constraint-configs/1") - .contentType(APPLICATION_JSON) - .accept(APPLICATION_JSON) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()) - .content(mapper.writeValueAsString(constraintConfig)); - - // Make the call - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify the mocks - verify(mockConstraintConfigService).update(constraintConfig); - } - - @Test(expected = NestedServletException.class) - public void testUpdatePlacementConstraintConfig_IdMismatch() throws Exception { - // Set up the request - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .put("/constraint-configs/2") - .contentType(APPLICATION_JSON) - .accept(APPLICATION_JSON) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()) - .content(mapper.writeValueAsString(constraintConfig)); - - // Make the call - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify the mocks - verify(mockConstraintConfigService, never()).update(constraintConfig); - } - - @Test - public void testDeletePlacementConstraintConfig() throws Exception { - // Set up the request - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .delete("/constraint-configs/1") - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - // Make the call - mockMvc.perform(request).andExpect(status().isNoContent()); - - // Verify the mocks - verify(mockConstraintConfigService).delete(1L); - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/rest/HardwareConfigsApiTest.java b/src/test/java/org/nrg/xnat/compute/rest/HardwareConfigsApiTest.java deleted file mode 100644 index 1348e96..0000000 --- a/src/test/java/org/nrg/xnat/compute/rest/HardwareConfigsApiTest.java +++ /dev/null @@ -1,201 +0,0 @@ -package org.nrg.xnat.compute.rest; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.nrg.xnat.compute.config.HardwareConfigsApiConfig; -import org.nrg.xnat.compute.models.HardwareConfig; -import org.nrg.xnat.compute.services.HardwareConfigService; -import org.nrg.xdat.security.services.RoleServiceI; -import org.nrg.xdat.security.services.UserManagementServiceI; -import org.nrg.xft.security.UserI; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.TestingAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; -import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.util.NestedServletException; - -import java.util.Optional; - -import static org.mockito.Mockito.*; -import static org.springframework.http.MediaType.APPLICATION_JSON; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; -import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -@WebAppConfiguration -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = {HardwareConfigsApiConfig.class}) -public class HardwareConfigsApiTest { - - @Autowired private WebApplicationContext wac; - @Autowired private ObjectMapper mapper; - @Autowired private RoleServiceI mockRoleService; - @Autowired private UserManagementServiceI mockUserManagementService; - @Autowired private HardwareConfigService mockHardwareConfigService; - - private MockMvc mockMvc; - private UserI mockUser; - private Authentication mockAuthentication; - - private HardwareConfig hardwareConfig; - - @Before - public void before() throws Exception { - mockMvc = MockMvcBuilders.webAppContextSetup(wac).apply(springSecurity()).build(); - - // Mock the user - mockUser = Mockito.mock(UserI.class); - when(mockUser.getLogin()).thenReturn("mockUser"); - when(mockUser.getEmail()).thenReturn("mockUser@mockuser.com"); - when(mockUser.getPassword()).thenReturn("mockUserPassword"); - when(mockUser.getID()).thenReturn(1); - when(mockRoleService.isSiteAdmin(mockUser)).thenReturn(true); - mockAuthentication = new TestingAuthenticationToken(mockUser, mockUser.getPassword()); - - // Set up a hardware config - hardwareConfig = new HardwareConfig(); - hardwareConfig.setId(1L); - } - - @After - public void after() throws Exception { - // Reset the mock - Mockito.reset( - mockRoleService, - mockUserManagementService, - mockHardwareConfigService, - mockUser - ); - } - - @Test - public void testGetAllHardwareConfigs() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/hardware-configs") - .accept(APPLICATION_JSON) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify that the service was called - verify(mockHardwareConfigService, times(1)).retrieveAll(); - } - - @Test - public void testGetHardwareConfigById() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/hardware-configs/1") - .accept(APPLICATION_JSON) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - when(mockHardwareConfigService.retrieve(1L)).thenReturn(Optional.of(hardwareConfig)); - - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify that the service was called - verify(mockHardwareConfigService, times(1)).retrieve(1L); - } - - @Test - public void testGetHardwareConfigByIdNotFound() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .get("/hardware-configs/1") - .accept(APPLICATION_JSON) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - when(mockHardwareConfigService.retrieve(1L)).thenReturn(Optional.empty()); - - mockMvc.perform(request).andExpect(status().isNotFound()); - - // Verify that the service was called - verify(mockHardwareConfigService, times(1)).retrieve(1L); - } - - @Test - public void testCreateHardwareConfig() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .post("/hardware-configs") - .accept(APPLICATION_JSON) - .contentType(APPLICATION_JSON) - .content(mapper.writeValueAsString(hardwareConfig)) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - when(mockHardwareConfigService.create(hardwareConfig)).thenReturn(hardwareConfig); - - mockMvc.perform(request).andExpect(status().isCreated()); - - // Verify that the service was called - verify(mockHardwareConfigService, times(1)).create(hardwareConfig); - } - - @Test - public void testUpdateHardwareConfig() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .put("/hardware-configs/1") - .accept(APPLICATION_JSON) - .contentType(APPLICATION_JSON) - .content(mapper.writeValueAsString(hardwareConfig)) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - when(mockHardwareConfigService.update(hardwareConfig)).thenReturn(hardwareConfig); - - mockMvc.perform(request).andExpect(status().isOk()); - - // Verify that the service was called - verify(mockHardwareConfigService, times(1)).update(hardwareConfig); - } - - @Test(expected = NestedServletException.class) - public void testUpdateHardwareConfig_IdMismatch() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .put("/hardware-configs/2") - .accept(APPLICATION_JSON) - .contentType(APPLICATION_JSON) - .content(mapper.writeValueAsString(hardwareConfig)) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - mockMvc.perform(request).andExpect(status().isBadRequest()); - - // Verify that the service was not called - verify(mockHardwareConfigService, never()).update(hardwareConfig); - } - - @Test - public void testDeleteHardwareConfig() throws Exception { - final MockHttpServletRequestBuilder request = MockMvcRequestBuilders - .delete("/hardware-configs/1") - .accept(APPLICATION_JSON) - .with(authentication(mockAuthentication)) - .with(csrf()) - .with(testSecurityContext()); - - mockMvc.perform(request).andExpect(status().isNoContent()); - - // Verify that the service was called - verify(mockHardwareConfigService, times(1)).delete(1L); - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/services/impl/DefaultComputeEnvironmentConfigServiceTest.java b/src/test/java/org/nrg/xnat/compute/services/impl/DefaultComputeEnvironmentConfigServiceTest.java deleted file mode 100644 index 90e271a..0000000 --- a/src/test/java/org/nrg/xnat/compute/services/impl/DefaultComputeEnvironmentConfigServiceTest.java +++ /dev/null @@ -1,875 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.nrg.xnat.compute.config.DefaultComputeEnvironmentConfigServiceTestConfig; -import org.nrg.xnat.compute.models.*; -import org.nrg.framework.constants.Scope; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xnat.compute.entities.HardwareConfigEntity; -import org.nrg.xnat.compute.services.HardwareConfigEntityService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.transaction.Transactional; -import java.util.*; - -import static org.hamcrest.CoreMatchers.*; -import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.*; -import static org.nrg.framework.constants.Scope.*; -import static org.nrg.xnat.compute.models.ComputeEnvironmentConfig.ConfigType.CONTAINER_SERVICE; -import static org.nrg.xnat.compute.models.ComputeEnvironmentConfig.ConfigType.JUPYTERHUB; -import static org.nrg.xnat.compute.utils.TestingUtils.commitTransaction; - -@RunWith(SpringJUnit4ClassRunner.class) -@Transactional -@ContextConfiguration(classes = DefaultComputeEnvironmentConfigServiceTestConfig.class) -public class DefaultComputeEnvironmentConfigServiceTest { - - @Autowired private DefaultComputeEnvironmentConfigService defaultComputeEnvironmentConfigService; - @Autowired private HardwareConfigEntityService hardwareConfigEntityService; - - private ComputeEnvironmentConfig computeEnvironmentConfig1; - private ComputeEnvironmentConfig computeEnvironmentConfig2; - private ComputeEnvironmentConfig computeEnvironmentConfig3; - private ComputeEnvironmentConfig computeEnvironmentConfigInvalid; - - private HardwareConfig hardwareConfig1; - private HardwareConfig hardwareConfig2; - private HardwareConfig hardwareConfig3; - - @Before - public void before() { - createDummyConfigs(); - } - - @Test - @DirtiesContext - public void testExists() { - // Test - ComputeEnvironmentConfig created = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - boolean exists = defaultComputeEnvironmentConfigService.exists(created.getId()); - - // Verify - assertTrue(exists); - } - - @Test - @DirtiesContext - public void testDoesNotExist() { - // Test - ComputeEnvironmentConfig created = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - boolean exists = defaultComputeEnvironmentConfigService.exists(created.getId() + 1); - - // Verify - assertFalse(exists); - } - - @Test - @DirtiesContext - public void testGetDoesNotExist() { - // Test - Optional computeEnvironmentConfig = defaultComputeEnvironmentConfigService.retrieve(1L); - - // Verify - assertFalse(computeEnvironmentConfig.isPresent()); - } - - @Test - @DirtiesContext - public void testGet() { - // Test - ComputeEnvironmentConfig created = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - Optional computeEnvironmentConfig = defaultComputeEnvironmentConfigService.retrieve(created.getId()); - - // Verify - assertTrue(computeEnvironmentConfig.isPresent()); - assertEquals(created, computeEnvironmentConfig.get()); - - assertEquals(computeEnvironmentConfig1.getComputeEnvironment(), computeEnvironmentConfig.get().getComputeEnvironment()); - assertEquals(computeEnvironmentConfig1.getConfigTypes(), computeEnvironmentConfig.get().getConfigTypes()); - assertEquals(computeEnvironmentConfig1.getScopes(), computeEnvironmentConfig.get().getScopes()); - } - - @Test - @DirtiesContext - public void testGetAll() { - // Test - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - ComputeEnvironmentConfig created3 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig3); - commitTransaction(); - - List computeEnvironmentConfigs = defaultComputeEnvironmentConfigService.getAll(); - - // Verify - assertThat(computeEnvironmentConfigs.size(), is(3)); - assertThat(computeEnvironmentConfigs, hasItems(created1, created2, created3)); - } - - @Test - @DirtiesContext - public void testGetByType() { - // Create ComputeEnvironmentConfigs - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - ComputeEnvironmentConfig created3 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig3); - commitTransaction(); - - // Test - List computeEnvironmentConfigs = defaultComputeEnvironmentConfigService.getByType(CONTAINER_SERVICE); - - // Verify - assertThat(computeEnvironmentConfigs.size(), is(2)); - assertThat(computeEnvironmentConfigs, hasItems(created2, created3)); - - // Test - computeEnvironmentConfigs = defaultComputeEnvironmentConfigService.getByType(JUPYTERHUB); - - // Verify - assertEquals(2, computeEnvironmentConfigs.size()); - assertThat(computeEnvironmentConfigs, containsInAnyOrder(created1, created3)); - } - - @Test - @DirtiesContext - public void testGetAvailable_WrongUser() { - // Create ComputeEnvironmentConfigs - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - ComputeEnvironmentConfig created3 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig3); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User2"); - executionScope.put(Project, "Project1"); - executionScope.put(Experiment, "XNAT_E00001"); - executionScope.put(DataType, "xnat:petSessionData"); - List computeEnvironmentConfigs = defaultComputeEnvironmentConfigService.getAvailable(null, executionScope); - - // Verify - assertThat(computeEnvironmentConfigs.size(), is(1)); - assertThat(computeEnvironmentConfigs, hasItems(created1)); - } - - @Test - @DirtiesContext - public void testGetAvailable_WrongProject() { - // Create ComputeEnvironmentConfigs - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - ComputeEnvironmentConfig created3 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig3); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User1"); - executionScope.put(Project, "Project2"); - executionScope.put(Experiment, "XNAT_E00001"); - executionScope.put(DataType, "xnat:petSessionData"); - List computeEnvironmentConfigs = defaultComputeEnvironmentConfigService.getAvailable(executionScope); - - // Verify - assertThat(computeEnvironmentConfigs.size(), is(1)); - assertThat(computeEnvironmentConfigs, hasItem(created1)); - } - - @Test - @DirtiesContext - public void testGetAvailable() { - // Create hardware configs - HardwareConfigEntity hardwareConfigEntity1 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig1)); - HardwareConfigEntity hardwareConfigEntity2 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig2)); - HardwareConfigEntity hardwareConfigEntity3 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig3)); - commitTransaction(); - - hardwareConfig1.setId(hardwareConfigEntity1.getId()); - hardwareConfig2.setId(hardwareConfigEntity2.getId()); - hardwareConfig3.setId(hardwareConfigEntity3.getId()); - - // Create ComputeEnvironmentConfigs - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - ComputeEnvironmentConfig created3 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig3); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User1"); - executionScope.put(Project, "Project1"); - executionScope.put(Experiment, "XNAT_E00001"); - executionScope.put(DataType, "xnat:ctSessionData"); - List computeEnvironmentConfigs = defaultComputeEnvironmentConfigService.getAvailable(executionScope); - - // Verify - assertThat(computeEnvironmentConfigs.size(), is(2)); - assertThat(computeEnvironmentConfigs.get(0).getHardwareOptions().getHardwareConfigs().size(), is(2)); - assertThat(computeEnvironmentConfigs.get(0).getHardwareOptions().getHardwareConfigs(), hasItems(hardwareConfig1, hardwareConfig2)); - assertThat(computeEnvironmentConfigs.get(0).getHardwareOptions().getHardwareConfigs(), not(hasItems(hardwareConfig3))); - assertThat(computeEnvironmentConfigs.get(1).getHardwareOptions().getHardwareConfigs().size(), is(1)); - assertThat(computeEnvironmentConfigs.get(1).getHardwareOptions().getHardwareConfigs(), hasItems(hardwareConfig2)); - } - - @Test - @DirtiesContext - public void testGetAvailable_SpecificType() { - // Create ComputeEnvironmentConfigs - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - ComputeEnvironmentConfig created3 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig3); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User1"); - executionScope.put(Project, "Project1"); - executionScope.put(Experiment, "XNAT_E00001"); - executionScope.put(DataType, "xnat:petSessionData"); - List computeEnvironmentConfigs = defaultComputeEnvironmentConfigService.getAvailable(CONTAINER_SERVICE, executionScope); - - // Verify - assertThat(computeEnvironmentConfigs.size(), is(1)); - assertThat(computeEnvironmentConfigs, hasItems(created2)); - } - - @Test - @DirtiesContext - public void testIsAvailable() { - // Create ComputeEnvironmentConfigs - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - ComputeEnvironmentConfig created3 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig3); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User1"); - executionScope.put(Project, "Project1"); - executionScope.put(Experiment, "XNAT_E00001"); - executionScope.put(DataType, "xnat:petSessionData"); - boolean result = defaultComputeEnvironmentConfigService.isAvailable(created1.getId(), executionScope); - - // Verify - assertTrue(result); - - // Test - result = defaultComputeEnvironmentConfigService.isAvailable(created2.getId(), executionScope); - - // Verify - assertTrue(result); - - // Test - result = defaultComputeEnvironmentConfigService.isAvailable(created3.getId(), executionScope); - - // Verify - assertFalse(result); - } - - @Test - @DirtiesContext - public void testNotAvailable_WrongUser() { - // Create ComputeEnvironmentConfigs - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - ComputeEnvironmentConfig created3 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig3); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User2"); - executionScope.put(Project, "Project1"); - executionScope.put(Experiment, "XNAT_E00001"); - executionScope.put(DataType, "xnat:petSessionData"); - boolean result = defaultComputeEnvironmentConfigService.isAvailable(created1.getId(), executionScope); - - // Verify - assertTrue(result); - - // Test - result = defaultComputeEnvironmentConfigService.isAvailable(created2.getId(), executionScope); - - // Verify - assertFalse(result); - - // Test - result = defaultComputeEnvironmentConfigService.isAvailable(created3.getId(), executionScope); - - // Verify - assertFalse(result); - } - - @Test - @DirtiesContext - public void testNotAvailable_WrongProject() { - // Create ComputeEnvironmentConfigs - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - ComputeEnvironmentConfig created3 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig3); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User1"); - executionScope.put(Project, "Project2"); - executionScope.put(Experiment, "XNAT_E00001"); - executionScope.put(DataType, "xnat:petSessionData"); - boolean result = defaultComputeEnvironmentConfigService.isAvailable(created1.getId(), executionScope); - - // Verify - assertTrue(result); - - // Test - result = defaultComputeEnvironmentConfigService.isAvailable(created2.getId(), executionScope); - - // Verify - assertFalse(result); - - // Test - result = defaultComputeEnvironmentConfigService.isAvailable(created3.getId(), executionScope); - - // Verify - assertFalse(result); - } - - @Test - @DirtiesContext - public void testNotAvailable_WrongDataType() { - // Create ComputeEnvironmentConfigs - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - ComputeEnvironmentConfig created3 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig3); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User1"); - executionScope.put(Project, "Project1"); - executionScope.put(Experiment, "XNAT_E00001"); - executionScope.put(DataType, "xnat:projectData"); // Wrong data type - boolean result = defaultComputeEnvironmentConfigService.isAvailable(created1.getId(), executionScope); - - // Verify - assertTrue(result); - - // Test - result = defaultComputeEnvironmentConfigService.isAvailable(created2.getId(), executionScope); - - // Verify - assertFalse(result); - - // Test - result = defaultComputeEnvironmentConfigService.isAvailable(created3.getId(), executionScope); - - // Verify - assertFalse(result); - } - - @Test - @DirtiesContext - public void testCreate_AllowAllHardware() { - // First create hardware configs - HardwareConfigEntity hardwareConfigEntity1 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig1)); - HardwareConfigEntity hardwareConfigEntity2 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig2)); - HardwareConfigEntity hardwareConfigEntity3 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig3)); - commitTransaction(); - - hardwareConfig1.setId(hardwareConfigEntity1.getId()); - hardwareConfig2.setId(hardwareConfigEntity2.getId()); - hardwareConfig3.setId(hardwareConfigEntity3.getId()); - - // Next create compute environment config - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - - // Verify that all hardware configs are associated with the compute environment config - assertThat(created1.getHardwareOptions().getHardwareConfigs().size(), is(3)); - assertThat(created1.getHardwareOptions().getHardwareConfigs(), hasItems(hardwareConfig1, hardwareConfig2, hardwareConfig3)); - } - - @Test - @DirtiesContext - public void testCreate_SelectHardware() { - // First create hardware configs - HardwareConfigEntity hardwareConfigEntity1 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig1)); - HardwareConfigEntity hardwareConfigEntity2 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig2)); - HardwareConfigEntity hardwareConfigEntity3 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig3)); - commitTransaction(); - - hardwareConfig1.setId(hardwareConfigEntity1.getId()); - hardwareConfig2.setId(hardwareConfigEntity2.getId()); - hardwareConfig3.setId(hardwareConfigEntity3.getId()); - - // Next create compute environment config - ComputeEnvironmentConfig created2 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig2); - commitTransaction(); - - // Verify that only the selected hardware config is associated with the compute environment config - assertThat(created2.getHardwareOptions().getHardwareConfigs().size(), is(2)); - assertThat(created2.getHardwareOptions().getHardwareConfigs(), hasItems(hardwareConfig2, hardwareConfig3)); - } - - @Test - @DirtiesContext - public void testUpdate() throws NotFoundException { - // First create hardware configs - HardwareConfigEntity hardwareConfigEntity1 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig1)); - HardwareConfigEntity hardwareConfigEntity2 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig2)); - commitTransaction(); - - hardwareConfig1.setId(hardwareConfigEntity1.getId()); - hardwareConfig2.setId(hardwareConfigEntity2.getId()); - - // Next create compute environment config - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - - // Verify that all hardware configs are associated with the compute environment config - assertThat(created1.getHardwareOptions().getHardwareConfigs().size(), is(2)); - assertThat(created1.getHardwareOptions().getHardwareConfigs(), hasItems(hardwareConfig1, hardwareConfig2)); - - // Update the compute environment config - created1.getHardwareOptions().setAllowAllHardware(false); - created1.getHardwareOptions().getHardwareConfigs().remove(hardwareConfig1); - - // Update other fields - created1.getComputeEnvironment().setName("UpdatedName"); - created1.getComputeEnvironment().setImage("UpdatedImage"); - created1.getComputeEnvironment().getEnvironmentVariables().add(new EnvironmentVariable("UpdatedKey", "UpdatedValue")); - - // Update the compute environment config - defaultComputeEnvironmentConfigService.update(created1); - commitTransaction(); - - // Verify that only the selected hardware config is associated with the compute environment config - assertThat(created1.getHardwareOptions().getHardwareConfigs().size(), is(1)); - assertThat(created1.getHardwareOptions().getHardwareConfigs(), hasItem(hardwareConfig2)); - - // Verify that the other fields were updated - assertThat(created1.getComputeEnvironment().getName(), is("UpdatedName")); - assertThat(created1.getComputeEnvironment().getImage(), is("UpdatedImage")); - assertThat(created1.getComputeEnvironment().getEnvironmentVariables(), hasItem(new EnvironmentVariable("UpdatedKey", "UpdatedValue"))); - } - - @Test - @DirtiesContext - public void testDelete() throws Exception { - // First create hardware configs - HardwareConfigEntity hardwareConfigEntity1 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig1)); - HardwareConfigEntity hardwareConfigEntity2 = hardwareConfigEntityService.create(HardwareConfigEntity.fromPojo(hardwareConfig2)); - commitTransaction(); - - hardwareConfig1.setId(hardwareConfigEntity1.getId()); - hardwareConfig2.setId(hardwareConfigEntity2.getId()); - - // Next create compute environment config - ComputeEnvironmentConfig created1 = defaultComputeEnvironmentConfigService.create(computeEnvironmentConfig1); - commitTransaction(); - - // Verify that all hardware configs are associated with the compute environment config - assertThat(created1.getHardwareOptions().getHardwareConfigs().size(), is(2)); - assertThat(created1.getHardwareOptions().getHardwareConfigs(), hasItems(hardwareConfig1, hardwareConfig2)); - - hardwareConfigEntity1 = hardwareConfigEntityService.retrieve(hardwareConfigEntity1.getId()); - hardwareConfigEntity2 = hardwareConfigEntityService.retrieve(hardwareConfigEntity2.getId()); - - assertThat(hardwareConfigEntity1.getComputeEnvironmentHardwareOptions().size(), is(1)); - assertThat(hardwareConfigEntity2.getComputeEnvironmentHardwareOptions().size(), is(1)); - - // Delete the compute environment config - defaultComputeEnvironmentConfigService.delete(created1.getId()); - commitTransaction(); - - // Verify that the compute environment config was deleted - assertThat(defaultComputeEnvironmentConfigService.exists(created1.getId()), is(false)); - - // Verify that the hardware config entities were deleted - hardwareConfigEntity1 = hardwareConfigEntityService.retrieve(hardwareConfigEntity1.getId()); - hardwareConfigEntity2 = hardwareConfigEntityService.retrieve(hardwareConfigEntity2.getId()); - - assertThat(hardwareConfigEntity1.getComputeEnvironmentHardwareOptions().size(), is(0)); - assertThat(hardwareConfigEntity2.getComputeEnvironmentHardwareOptions().size(), is(0)); - } - - @Test - public void testValidate() { - try { - defaultComputeEnvironmentConfigService.validate(computeEnvironmentConfigInvalid); - fail("Expected exception to be thrown"); - } catch (IllegalArgumentException e) { - // Verify that the exception message contains the expected validation errors - // Note: the order of the validation errors is not guaranteed - // Trying not to be too brittle here - assertThat(e.getMessage(), containsString("name cannot be blank")); - assertThat(e.getMessage(), containsString("image cannot be blank")); - assertThat(e.getMessage(), containsString("must have at least one scope")); - assertThat(e.getMessage(), containsString("hardware configs cannot be null")); - assertThat(e.getMessage(), containsString("must have at least one config type")); - } - } - - public void createDummyConfigs() { - // Setup hardware - Hardware hardware1 = Hardware.builder() - .name("Small") - .cpuReservation(2.0) - .cpuLimit(4.0) - .memoryReservation("4G") - .memoryLimit("8G") - .build(); - - // Setup hardware constraints - Constraint hardwareConstraint1 = Constraint.builder() - .key("node.role") - .operator(Constraint.Operator.IN) - .values(new HashSet<>(Collections.singletonList("worker"))) - .build(); - - Constraint hardwareConstraint2 = Constraint.builder() - .key("node.instance.type") - .operator(Constraint.Operator.NOT_IN) - .values(new HashSet<>(Arrays.asList("spot", "demand"))) - .build(); - - hardware1.setConstraints(Arrays.asList(hardwareConstraint1, hardwareConstraint2)); - - // Setup hardware environment variables - EnvironmentVariable hardwareEnvironmentVariable1 = new EnvironmentVariable("MATLAB_LICENSE_FILE", "12345@myserver"); - EnvironmentVariable hardwareEnvironmentVariable2 = new EnvironmentVariable("NVIDIA_VISIBLE_DEVICES", "all"); - - hardware1.setEnvironmentVariables(Arrays.asList(hardwareEnvironmentVariable1, hardwareEnvironmentVariable2)); - - // Setup hardware generic resources - GenericResource hardwareGenericResource1 = new GenericResource("nvidia.com/gpu", "2"); - GenericResource hardwareGenericResource2 = new GenericResource("fpga.com/fpga", "1"); - - hardware1.setGenericResources(Arrays.asList(hardwareGenericResource1, hardwareGenericResource2)); - - // Setup hardware scopes - HardwareScope hardwareSiteScope1 = HardwareScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope hardwareProjectScope1 = HardwareScope.builder() - .scope(Project) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope userHardwareScope1 = HardwareScope.builder() - .scope(User) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - Map hardwareScopes1 = new HashMap<>(); - hardwareScopes1.put(Site, hardwareSiteScope1); - hardwareScopes1.put(Project, hardwareProjectScope1); - hardwareScopes1.put(User, userHardwareScope1); - - // Setup a hardware config entity - hardwareConfig1 = HardwareConfig.builder() - .hardware(hardware1) - .scopes(hardwareScopes1) - .build(); - - // Setup second hardware config - Hardware hardware2 = Hardware.builder() - .name("Medium") - .cpuReservation(4.0) - .cpuLimit(4.0) - .memoryReservation("8G") - .memoryLimit("8G") - .build(); - - // Setup hardware constraints - Constraint hardwareConstraint3 = Constraint.builder() - .key("node.role") - .operator(Constraint.Operator.IN) - .values(new HashSet<>(Collections.singletonList("worker"))) - .build(); - - Constraint hardwareConstraint4 = Constraint.builder() - .key("node.instance.type") - .operator(Constraint.Operator.NOT_IN) - .values(new HashSet<>(Arrays.asList("spot", "demand"))) - .build(); - - hardware2.setConstraints(Arrays.asList(hardwareConstraint3, hardwareConstraint4)); - - // Setup hardware environment variables - EnvironmentVariable hardwareEnvironmentVariable3 = new EnvironmentVariable("MATLAB_LICENSE_FILE", "12345@myserver"); - EnvironmentVariable hardwareEnvironmentVariable4 = new EnvironmentVariable("NVIDIA_VISIBLE_DEVICES", "all"); - - hardware2.setEnvironmentVariables(Arrays.asList(hardwareEnvironmentVariable3, hardwareEnvironmentVariable4)); - - // Setup hardware generic resources - GenericResource hardwareGenericResource3 = new GenericResource("nvidia.com/gpu", "2"); - GenericResource hardwareGenericResource4 = new GenericResource("fpga.com/fpga", "1"); - - hardware2.setGenericResources(Arrays.asList(hardwareGenericResource3, hardwareGenericResource4)); - - // Setup hardware scopes - HardwareScope hardwareSiteScope2 = HardwareScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope hardwareProjectScope2 = HardwareScope.builder() - .scope(Project) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope userHardwareScope2 = HardwareScope.builder() - .scope(User) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - Map hardwareScopes2 = new HashMap<>(); - hardwareScopes2.put(Site, hardwareSiteScope2); - hardwareScopes2.put(Project, hardwareProjectScope2); - hardwareScopes2.put(User, userHardwareScope2); - - // Setup second hardware config entity - hardwareConfig2 = HardwareConfig.builder() - .hardware(hardware2) - .scopes(hardwareScopes2) - .build(); - - // Setup second hardware config - Hardware hardware3 = Hardware.builder() - .name("Large") - .cpuReservation(8.0) - .cpuLimit(8.0) - .memoryReservation("16G") - .memoryLimit("16G") - .build(); - - // No constraints, environment variables or generic resources - hardware3.setConstraints(Collections.emptyList()); - hardware3.setEnvironmentVariables(Collections.emptyList()); - hardware3.setGenericResources(Collections.emptyList()); - - // Setup hardware scopes - HardwareScope hardwareSiteScope3 = HardwareScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope hardwareProjectScope3 = HardwareScope.builder() - .scope(Project) - .enabled(false) - .ids(new HashSet<>(Collections.singletonList("ProjectABCDE"))) - .build(); - - HardwareScope userHardwareScope3 = HardwareScope.builder() - .scope(User) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - Map hardwareScopes3 = new HashMap<>(); - hardwareScopes3.put(Site, hardwareSiteScope3); - hardwareScopes3.put(Project, hardwareProjectScope3); - hardwareScopes3.put(User, userHardwareScope3); - - // Setup second hardware config entity - hardwareConfig3 = HardwareConfig.builder() - .hardware(hardware3) - .scopes(hardwareScopes3) - .build(); - - // Setup first compute environment - ComputeEnvironment computeEnvironment1 = ComputeEnvironment.builder() - .name("Jupyter Datascience Notebook") - .image("jupyter/datascience-notebook:hub-3.0.0") - .environmentVariables(new ArrayList<>()) - .mounts(new ArrayList<>()) - .build(); - - ComputeEnvironmentScope computeEnvironmentSiteScope1 = ComputeEnvironmentScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentProjectScope1 = ComputeEnvironmentScope.builder() - .scope(Project) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentUserScope1 = ComputeEnvironmentScope.builder() - .scope(User) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - Map computeEnvironmentScopes1 = new HashMap<>(); - computeEnvironmentScopes1.put(Site, computeEnvironmentSiteScope1); - computeEnvironmentScopes1.put(Project, computeEnvironmentProjectScope1); - computeEnvironmentScopes1.put(User, computeEnvironmentUserScope1); - - ComputeEnvironmentHardwareOptions computeEnvironmentHardwareOptions1 = ComputeEnvironmentHardwareOptions.builder() - .allowAllHardware(true) - .hardwareConfigs(new HashSet<>(Arrays.asList(hardwareConfig1, hardwareConfig2, hardwareConfig3))) - .build(); - - computeEnvironmentConfig1 = ComputeEnvironmentConfig.builder() - .configTypes(new HashSet<>(Collections.singletonList(ComputeEnvironmentConfig.ConfigType.JUPYTERHUB))) - .computeEnvironment(computeEnvironment1) - .scopes(computeEnvironmentScopes1) - .hardwareOptions(computeEnvironmentHardwareOptions1) - .build(); - - // Setup second compute environment - ComputeEnvironment computeEnvironment2 = ComputeEnvironment.builder() - .name("XNAT Datascience Notebook") - .image("xnat/datascience-notebook:latest") - .environmentVariables(new ArrayList<>()) - .mounts(new ArrayList<>()) - .build(); - - ComputeEnvironmentScope computeEnvironmentSiteScope2 = ComputeEnvironmentScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentProjectScope2 = ComputeEnvironmentScope.builder() - .scope(Project) - .enabled(false) - .ids(new HashSet<>(new ArrayList<>(Arrays.asList("Project1", "Project10", "Project100")))) - .build(); - - ComputeEnvironmentScope computeEnvironmentUserScope2 = ComputeEnvironmentScope.builder() - .scope(User) - .enabled(false) - .ids(new HashSet<>(new ArrayList<>(Arrays.asList("User1", "User10", "User100")))) - .build(); - - ComputeEnvironmentScope computeEnvironmentDatatypeScope2 = ComputeEnvironmentScope.builder() - .scope(DataType) - .enabled(false) - .ids(new HashSet<>(Arrays.asList("xnat:mrSessionData", "xnat:petSessionData", "xnat:ctSessionData"))) - .build(); - - Map computeEnvironmentScopes2 = new HashMap<>(); - computeEnvironmentScopes2.put(Site, computeEnvironmentSiteScope2); - computeEnvironmentScopes2.put(Project, computeEnvironmentProjectScope2); - computeEnvironmentScopes2.put(User, computeEnvironmentUserScope2); - computeEnvironmentScopes2.put(DataType, computeEnvironmentDatatypeScope2); - - ComputeEnvironmentHardwareOptions computeEnvironmentHardwareOptions2 = ComputeEnvironmentHardwareOptions.builder() - .allowAllHardware(false) - .hardwareConfigs(new HashSet<>(Arrays.asList(hardwareConfig2, hardwareConfig3))) - .build(); - - computeEnvironmentConfig2 = ComputeEnvironmentConfig.builder() - .id(2L) - .configTypes(new HashSet<>(Collections.singletonList(CONTAINER_SERVICE))) - .computeEnvironment(computeEnvironment2) - .scopes(computeEnvironmentScopes2) - .hardwareOptions(computeEnvironmentHardwareOptions2) - .build(); - - // Setup third compute environment - ComputeEnvironment computeEnvironment3 = ComputeEnvironment.builder() - .name("MATLAB Datascience Notebook") - .image("matlab/datascience-notebook:latest") - .environmentVariables(new ArrayList<>()) - .mounts(new ArrayList<>()) - .build(); - - ComputeEnvironmentScope computeEnvironmentSiteScope3 = ComputeEnvironmentScope.builder() - .scope(Site) - .enabled(false) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentProjectScope3 = ComputeEnvironmentScope.builder() - .scope(Project) - .enabled(true) - .ids(new HashSet<>()) - .build(); - - ComputeEnvironmentScope computeEnvironmentUserScope3 = ComputeEnvironmentScope.builder() - .scope(User) - .enabled(true) - .ids(new HashSet<>()) - .build(); - - Map computeEnvironmentScopes3 = new HashMap<>(); - computeEnvironmentScopes3.put(Site, computeEnvironmentSiteScope3); - computeEnvironmentScopes3.put(Project, computeEnvironmentProjectScope3); - computeEnvironmentScopes3.put(User, computeEnvironmentUserScope3); - - ComputeEnvironmentHardwareOptions computeEnvironmentHardwareOptions3 = ComputeEnvironmentHardwareOptions.builder() - .allowAllHardware(true) - .hardwareConfigs(new HashSet<>()) - .build(); - - computeEnvironmentConfig3 = ComputeEnvironmentConfig.builder() - .configTypes(new HashSet<>(Arrays.asList(CONTAINER_SERVICE, JUPYTERHUB))) - .computeEnvironment(computeEnvironment3) - .scopes(computeEnvironmentScopes3) - .hardwareOptions(computeEnvironmentHardwareOptions3) - .build(); - - // Setup invalid compute environment config - ComputeEnvironment computeEnvironmentInvalid = ComputeEnvironment.builder() - .name("") // invalid - .image("") // invalid - .environmentVariables(new ArrayList<>()) - .mounts(new ArrayList<>()) - .build(); - - Map computeEnvironmentScopesInvalid = new HashMap<>(); // invalid, no scopes - - ComputeEnvironmentHardwareOptions computeEnvironmentHardwareOptionsInvalid = ComputeEnvironmentHardwareOptions.builder() - .allowAllHardware(true) - .hardwareConfigs(null) // invalid - .build(); - - computeEnvironmentConfigInvalid = ComputeEnvironmentConfig.builder() - .configTypes(null) // invalid - .computeEnvironment(computeEnvironmentInvalid) - .scopes(computeEnvironmentScopesInvalid) - .hardwareOptions(computeEnvironmentHardwareOptionsInvalid) - .build(); - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/services/impl/DefaultConstraintConfigServiceTest.java b/src/test/java/org/nrg/xnat/compute/services/impl/DefaultConstraintConfigServiceTest.java deleted file mode 100644 index 5af7261..0000000 --- a/src/test/java/org/nrg/xnat/compute/services/impl/DefaultConstraintConfigServiceTest.java +++ /dev/null @@ -1,278 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.nrg.framework.constants.Scope; -import org.nrg.framework.exceptions.NotFoundException; -import org.nrg.xnat.compute.config.DefaultConstraintConfigServiceTestConfig; -import org.nrg.xnat.compute.models.Constraint; -import org.nrg.xnat.compute.models.ConstraintConfig; -import org.nrg.xnat.compute.models.ConstraintScope; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.transaction.Transactional; -import java.util.*; - -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.nrg.xnat.compute.utils.TestingUtils.commitTransaction; - -@RunWith(SpringJUnit4ClassRunner.class) -@Transactional -@ContextConfiguration(classes = DefaultConstraintConfigServiceTestConfig.class) -public class DefaultConstraintConfigServiceTest { - - @Autowired private DefaultConstraintConfigService constraintConfigService; - - private ConstraintConfig constraintConfig1; - private ConstraintConfig constraintConfig2; - private ConstraintConfig constraintConfig3; - private ConstraintConfig constraintConfigInvalid; - - @Before - public void before() { - createDummyConstraintConfigs(); - } - - @Test - @DirtiesContext - public void testRetrieve() { - // Test - ConstraintConfig created = constraintConfigService.create(constraintConfig1); - commitTransaction(); - Optional retrieved = constraintConfigService.retrieve(created.getId()); - - // Verify - assertTrue(retrieved.isPresent()); - assertEquals(created, retrieved.get()); - - constraintConfig1.setId(created.getId()); - assertThat(retrieved.get(), is(constraintConfig1)); - } - - @Test - @DirtiesContext - public void testRetrieveDoesNotExist() { - // Test - Optional retrieved = constraintConfigService.retrieve(1L); - - // Verify - assertFalse(retrieved.isPresent()); - } - - @Test - @DirtiesContext - public void testGetAll() { - // Test - ConstraintConfig created1 = constraintConfigService.create(constraintConfig1); - commitTransaction(); - ConstraintConfig created2 = constraintConfigService.create(constraintConfig2); - commitTransaction(); - ConstraintConfig created3 = constraintConfigService.create(constraintConfig3); - commitTransaction(); - - List retrieved = constraintConfigService.getAll(); - - // Verify - assertEquals(3, retrieved.size()); - assertThat(retrieved, hasItems(created1, created2, created3)); - } - - @Test - @DirtiesContext - public void testCreate() { - // Test - ConstraintConfig created = constraintConfigService.create(constraintConfig1); - commitTransaction(); - - // Verify - assertNotNull(created.getId()); - constraintConfig1.setId(created.getId()); - assertEquals(created, constraintConfig1); - } - - @Test - @DirtiesContext - public void testUpdate() throws NotFoundException { - // Test - ConstraintConfig created = constraintConfigService.create(constraintConfig1); - commitTransaction(); - created.getConstraint().setKey("newKey"); - ConstraintConfig updated = constraintConfigService.update(created); - commitTransaction(); - - // Verify - assertEquals(created, updated); - } - - @Test - @DirtiesContext - public void testDelete() { - // Test - ConstraintConfig created = constraintConfigService.create(constraintConfig1); - commitTransaction(); - constraintConfigService.delete(created.getId()); - commitTransaction(); - - // Verify - Optional retrieved = constraintConfigService.retrieve(created.getId()); - assertFalse(retrieved.isPresent()); - } - - @Test - @DirtiesContext - public void testGetAvailable() { - // Setup - ConstraintConfig created1 = constraintConfigService.create(constraintConfig1); - commitTransaction(); - ConstraintConfig created2 = constraintConfigService.create(constraintConfig2); - commitTransaction(); - ConstraintConfig created3 = constraintConfigService.create(constraintConfig3); - commitTransaction(); - - // Test - Map executionScopes = new HashMap<>(); - executionScopes.put(Scope.Project, "ProjectA"); - List retrieved = constraintConfigService.getAvailable(executionScopes); - - // Verify - assertEquals(2, retrieved.size()); - assertThat(retrieved, hasItems(created1, created3)); - - // Test - executionScopes.put(Scope.Project, "ProjectB"); - retrieved = constraintConfigService.getAvailable(executionScopes); - - // Verify - assertEquals(2, retrieved.size()); - assertThat(retrieved, hasItems(created1, created3)); - - // Test - executionScopes.put(Scope.Project, "ProjectC"); - retrieved = constraintConfigService.getAvailable(executionScopes); - - // Verify - assertEquals(1, retrieved.size()); - assertThat(retrieved, hasItem(created1)); - } - - @Test - public void testValidate() { - try { - constraintConfigService.validate(constraintConfigInvalid); - fail("Should have thrown an exception"); - } catch (Exception e) { - assertThat(e.getMessage(), containsString("key cannot be null or blank")); - assertThat(e.getMessage(), containsString("values cannot be null or empty")); - assertThat(e.getMessage(), containsString("operator cannot be null")); - assertThat(e.getMessage(), containsString("Scopes cannot be null or empty")); - } - } - - protected void createDummyConstraintConfigs() { - createDummyConstraintConfig1(); - createDummyConstraintConfig2(); - createDummyConstraintConfig3(); - createDummyConstraintConfigInvalid(); - } - - protected void createDummyConstraintConfig1() { - constraintConfig1 = new ConstraintConfig(); - - Constraint constraint1 = new Constraint(); - constraint1.setKey("node.role"); - constraint1.setOperator(Constraint.Operator.IN); - constraint1.setValues(new HashSet<>(Collections.singletonList("worker"))); - constraintConfig1.setConstraint(constraint1); - - ConstraintScope siteScope1 = ConstraintScope.builder() - .scope(Scope.Site) - .enabled(true) - .ids(Collections.emptySet()) - .build(); - ConstraintScope projectScope1 = ConstraintScope.builder() - .scope(Scope.Project) - .enabled(true) - .ids(Collections.emptySet()) - .build(); - - Map scopes1 = new HashMap<>(); - scopes1.put(Scope.Site, siteScope1); - scopes1.put(Scope.Project, projectScope1); - - constraintConfig1.setScopes(scopes1); - } - - protected void createDummyConstraintConfig2() { - constraintConfig2 = new ConstraintConfig(); - - Constraint constraint2 = new Constraint(); - constraint2.setKey("node.role"); - constraint2.setOperator(Constraint.Operator.IN); - constraint2.setValues(new HashSet<>(Collections.singletonList("worker"))); - constraintConfig2.setConstraint(constraint2); - - ConstraintScope siteScope2 = ConstraintScope.builder() - .scope(Scope.Site) - .enabled(false) - .ids(Collections.emptySet()) - .build(); - ConstraintScope projectScope2 = ConstraintScope.builder() - .scope(Scope.Project) - .enabled(true) - .ids(Collections.emptySet()) - .build(); - - Map scopes2 = new HashMap<>(); - scopes2.put(Scope.Site, siteScope2); - scopes2.put(Scope.Project, projectScope2); - - constraintConfig2.setScopes(scopes2); - } - - protected void createDummyConstraintConfig3() { - constraintConfig3 = new ConstraintConfig(); - - Constraint constraint3 = new Constraint(); - constraint3.setKey("node.label.projects"); - constraint3.setOperator(Constraint.Operator.IN); - constraint3.setValues(new HashSet<>(Arrays.asList("ProjectA", "ProjectB"))); - constraintConfig3.setConstraint(constraint3); - - ConstraintScope siteScope3 = ConstraintScope.builder() - .scope(Scope.Site) - .enabled(true) - .ids(Collections.emptySet()) - .build(); - ConstraintScope projectScope3 = ConstraintScope.builder() - .scope(Scope.Project) - .enabled(false) - .ids(new HashSet<>(Arrays.asList("ProjectA", "ProjectB"))) - .build(); - - Map scopes3 = new HashMap<>(); - scopes3.put(Scope.Site, siteScope3); - scopes3.put(Scope.Project, projectScope3); - - constraintConfig3.setScopes(scopes3); - } - - protected void createDummyConstraintConfigInvalid() { - constraintConfigInvalid = new ConstraintConfig(); - - Constraint constraintInvalid = new Constraint(); - constraintInvalid.setKey(""); - constraintInvalid.setOperator(null); - constraintInvalid.setValues(new HashSet<>()); - constraintConfigInvalid.setConstraint(constraintInvalid); - - Map scopesInvalid = new HashMap<>(); - - constraintConfigInvalid.setScopes(scopesInvalid); - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/services/impl/DefaultHardwareConfigServiceTest.java b/src/test/java/org/nrg/xnat/compute/services/impl/DefaultHardwareConfigServiceTest.java deleted file mode 100644 index e876dbd..0000000 --- a/src/test/java/org/nrg/xnat/compute/services/impl/DefaultHardwareConfigServiceTest.java +++ /dev/null @@ -1,480 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.nrg.xnat.compute.models.*; -import org.nrg.framework.constants.Scope; -import org.nrg.xnat.compute.config.DefaultHardwareConfigServiceTestConfig; -import org.nrg.xnat.compute.entities.ComputeEnvironmentConfigEntity; -import org.nrg.xnat.compute.entities.HardwareConfigEntity; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigEntityService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.transaction.Transactional; -import java.util.*; -import java.util.stream.Collectors; - -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.nrg.framework.constants.Scope.*; -import static org.nrg.xnat.compute.utils.TestingUtils.commitTransaction; - -@RunWith(SpringJUnit4ClassRunner.class) -@Transactional -@ContextConfiguration(classes = DefaultHardwareConfigServiceTestConfig.class) -public class DefaultHardwareConfigServiceTest { - - @Autowired private DefaultHardwareConfigService defaultHardwareConfigService; - @Autowired private ComputeEnvironmentConfigEntityService computeEnvironmentConfigEntityService; - - private ComputeEnvironmentConfig computeEnvironmentConfig1; - private ComputeEnvironmentConfig computeEnvironmentConfig2; - private HardwareConfig hardwareConfig1; - private HardwareConfig hardwareConfig2; - private HardwareConfig hardwareConfigInvalid; - - @Before - public void before() throws Exception { - createDummyConfigsAndEntities(); - } - - @Test - @DirtiesContext - public void testExists() { - // Test - HardwareConfig hardwareConfig = defaultHardwareConfigService.create(hardwareConfig1); - commitTransaction(); - boolean exists = defaultHardwareConfigService.exists(hardwareConfig.getId()); - - // Verify - assertTrue(exists); - } - - @Test - @DirtiesContext - public void testDoesNotExist() { - // Test - boolean exists = defaultHardwareConfigService.exists(3L); - - // Verify - assertFalse(exists); - } - - @Test - @DirtiesContext - public void testRetrieve() { - // Setup - HardwareConfig created = defaultHardwareConfigService.create(hardwareConfig1); - commitTransaction(); - Optional retrieved = defaultHardwareConfigService.retrieve(created.getId()); - - // Verify - assertTrue(retrieved.isPresent()); - assertThat(retrieved.get(), is(created)); - - hardwareConfig1.setId(retrieved.get().getId()); - assertThat(retrieved.get(), is(hardwareConfig1)); - } - - @Test - @DirtiesContext - public void testRetrieve_DoesNotExist() { - // Setup - Optional retrieved = defaultHardwareConfigService.retrieve(3L); - - // Verify - assertFalse(retrieved.isPresent()); - } - - @Test - @DirtiesContext - public void testRetrieveAll() { - // Setup - HardwareConfig created1 = defaultHardwareConfigService.create(hardwareConfig1); - HardwareConfig created2 = defaultHardwareConfigService.create(hardwareConfig2); - commitTransaction(); - - // Test - List retrieved = defaultHardwareConfigService.retrieveAll(); - - // Verify - assertEquals(2, retrieved.size()); - assertThat(retrieved, hasItems(created1, created2)); - } - - @Test - @DirtiesContext - public void testCreate() { - // First, create the compute environment configs - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity1 = computeEnvironmentConfigEntityService.create(ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig1)); - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity2 = computeEnvironmentConfigEntityService.create(ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig2)); - commitTransaction(); - - // Now create a hardware config - HardwareConfig created1 = defaultHardwareConfigService.create(hardwareConfig1); - commitTransaction(); - HardwareConfig created2 = defaultHardwareConfigService.create(hardwareConfig2); - commitTransaction(); - - // Then retrieve the compute environment configs - computeEnvironmentConfigEntity1 = computeEnvironmentConfigEntityService.retrieve(computeEnvironmentConfigEntity1.getId()); - computeEnvironmentConfigEntity2 = computeEnvironmentConfigEntityService.retrieve(computeEnvironmentConfigEntity2.getId()); - - // Verify that the hardware config were added only to the first compute environment config - assertThat(computeEnvironmentConfigEntity1.getHardwareOptions().getHardwareConfigs().size(), is(2)); - assertThat(computeEnvironmentConfigEntity2.getHardwareOptions().getHardwareConfigs().size(), is(0)); - assertThat(computeEnvironmentConfigEntity1 - .getHardwareOptions() - .getHardwareConfigs().stream() - .map(HardwareConfigEntity::toPojo) - .collect(Collectors.toList()), - hasItems(created1, created2)); - } - - @Test - @DirtiesContext - public void testUpdate() throws Exception { - // Setup - HardwareConfig created1 = defaultHardwareConfigService.create(hardwareConfig1); - commitTransaction(); - - // Test - created1.getHardware().setName("Updated"); - created1.getHardware().setCpuLimit(6.5); - created1.getHardware().setMemoryLimit("10G"); - - defaultHardwareConfigService.update(created1); - commitTransaction(); - - // Verify - HardwareConfig retrieved = defaultHardwareConfigService.retrieve(created1.getId()).get(); - - assertThat(retrieved, is(created1)); - assertThat(retrieved.getHardware().getName(), is("Updated")); - assertThat(retrieved.getHardware().getCpuLimit(), is(6.5)); - assertThat(retrieved.getHardware().getMemoryLimit(), is("10G")); - } - - @Test - @DirtiesContext - public void testDelete() throws Exception { - // Setup - HardwareConfig created1 = defaultHardwareConfigService.create(hardwareConfig1); - commitTransaction(); - - // Test - defaultHardwareConfigService.delete(created1.getId()); - commitTransaction(); - - // Verify - assertFalse(defaultHardwareConfigService.exists(created1.getId())); - } - - @Test - @DirtiesContext - public void testIsAvailable() { - // Setup - HardwareConfig created1 = defaultHardwareConfigService.create(hardwareConfig1); - HardwareConfig created2 = defaultHardwareConfigService.create(hardwareConfig2); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User1"); - executionScope.put(Project, "Project1"); - boolean isAvailable1 = defaultHardwareConfigService.isAvailable(created1.getId(), executionScope); - boolean isAvailable2 = defaultHardwareConfigService.isAvailable(created2.getId(), executionScope); - - // Verify - assertTrue(isAvailable1); - assertTrue(isAvailable2); - } - - @Test - @DirtiesContext - public void testIsAvailable_WrongUser() { - // Setup - HardwareConfig created1 = defaultHardwareConfigService.create(hardwareConfig1); - HardwareConfig created2 = defaultHardwareConfigService.create(hardwareConfig2); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User2"); - executionScope.put(Project, "Project1"); - boolean isAvailable1 = defaultHardwareConfigService.isAvailable(created1.getId(), executionScope); - boolean isAvailable2 = defaultHardwareConfigService.isAvailable(created2.getId(), executionScope); - - // Verify - assertTrue(isAvailable1); - assertFalse(isAvailable2); - } - - @Test - @DirtiesContext - public void testIsAvailable_WrongProject() { - // Setup - HardwareConfig created1 = defaultHardwareConfigService.create(hardwareConfig1); - HardwareConfig created2 = defaultHardwareConfigService.create(hardwareConfig2); - commitTransaction(); - - // Test - Map executionScope = new HashMap<>(); - executionScope.put(User, "User1"); - executionScope.put(Project, "Project2"); - boolean isAvailable1 = defaultHardwareConfigService.isAvailable(created1.getId(), executionScope); - boolean isAvailable2 = defaultHardwareConfigService.isAvailable(created2.getId(), executionScope); - - // Verify - assertTrue(isAvailable1); - assertFalse(isAvailable2); - } - - @Test - public void testValidate() { - try { - defaultHardwareConfigService.validate(hardwareConfigInvalid); - fail("Expected an IllegalArgumentException to be thrown"); - } catch (IllegalArgumentException e) { - // Verify that the exception message contains the expected validation errors - // Note: the order of the validation errors is not guaranteed - // Trying not to be too brittle here - assertThat(e.getMessage(), containsString("name cannot be blank")); - assertThat(e.getMessage(), containsString("scopes cannot be null or empty")); - } - } - - public void createDummyConfigsAndEntities() { - // Setup hardware - Hardware hardware1 = Hardware.builder() - .name("Small") - .cpuReservation(2.0) - .cpuLimit(4.0) - .memoryReservation("4G") - .memoryLimit("8G") - .build(); - - // Setup hardware constraints - Constraint hardwareConstraint1 = Constraint.builder() - .key("node.role") - .operator(Constraint.Operator.IN) - .values(new HashSet<>(Collections.singletonList("worker"))) - .build(); - - Constraint hardwareConstraint2 = Constraint.builder() - .key("node.instance.type") - .operator(Constraint.Operator.NOT_IN) - .values(new HashSet<>(Arrays.asList("spot", "demand"))) - .build(); - - hardware1.setConstraints(Arrays.asList(hardwareConstraint1, hardwareConstraint2)); - - // Setup hardware environment variables - EnvironmentVariable hardwareEnvironmentVariable1 = new EnvironmentVariable("MATLAB_LICENSE_FILE", "12345@myserver"); - EnvironmentVariable hardwareEnvironmentVariable2 = new EnvironmentVariable("NVIDIA_VISIBLE_DEVICES", "all"); - - hardware1.setEnvironmentVariables(Arrays.asList(hardwareEnvironmentVariable1, hardwareEnvironmentVariable2)); - - // Setup hardware generic resources - GenericResource hardwareGenericResource1 = new GenericResource("nvidia.com/gpu", "2"); - GenericResource hardwareGenericResource2 = new GenericResource("fpga.com/fpga", "1"); - - hardware1.setGenericResources(Arrays.asList(hardwareGenericResource1, hardwareGenericResource2)); - - // Setup hardware scopes - HardwareScope hardwareSiteScope1 = HardwareScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope hardwareProjectScope1 = HardwareScope.builder() - .scope(Project) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope userHardwareScope1 = HardwareScope.builder() - .scope(User) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - Map hardwareScopes1 = new HashMap<>(); - hardwareScopes1.put(Site, hardwareSiteScope1); - hardwareScopes1.put(Project, hardwareProjectScope1); - hardwareScopes1.put(User, userHardwareScope1); - - // Build hardware config - hardwareConfig1 = HardwareConfig.builder() - .hardware(hardware1) - .scopes(hardwareScopes1) - .build(); - - // Setup second hardware config - Hardware hardware2 = Hardware.builder() - .name("Medium") - .cpuReservation(4.0) - .cpuLimit(4.0) - .memoryReservation("8G") - .memoryLimit("8G") - .build(); - - // Setup hardware constraints - Constraint hardwareConstraint3 = Constraint.builder() - .key("node.role") - .operator(Constraint.Operator.IN) - .values(new HashSet<>(Collections.singletonList("worker"))) - .build(); - - Constraint hardwareConstraint4 = Constraint.builder() - .key("node.instance.type") - .operator(Constraint.Operator.NOT_IN) - .values(new HashSet<>(Arrays.asList("spot", "demand"))) - .build(); - - hardware2.setConstraints(Arrays.asList(hardwareConstraint3, hardwareConstraint4)); - - // Setup hardware environment variables - EnvironmentVariable hardwareEnvironmentVariable3 = new EnvironmentVariable("MATLAB_LICENSE_FILE", "12345@myserver"); - EnvironmentVariable hardwareEnvironmentVariable4 = new EnvironmentVariable("NVIDIA_VISIBLE_DEVICES", "all"); - - hardware2.setEnvironmentVariables(Arrays.asList(hardwareEnvironmentVariable3, hardwareEnvironmentVariable4)); - - // Setup hardware generic resources - GenericResource hardwareGenericResource3 = new GenericResource("nvidia.com/gpu", "2"); - GenericResource hardwareGenericResource4 = new GenericResource("fpga.com/fpga", "1"); - - hardware2.setGenericResources(Arrays.asList(hardwareGenericResource3, hardwareGenericResource4)); - - // Setup hardware scopes - HardwareScope hardwareSiteScope2 = HardwareScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope hardwareProjectScope2 = HardwareScope.builder() - .scope(Project) - .enabled(false) - .ids(new HashSet<>(Collections.singletonList("Project1"))) - .build(); - - HardwareScope userHardwareScope2 = HardwareScope.builder() - .scope(User) - .enabled(false) - .ids(new HashSet<>(Collections.singletonList("User1"))) - .build(); - - Map hardwareScopes2 = new HashMap<>(); - hardwareScopes2.put(Site, hardwareSiteScope2); - hardwareScopes2.put(Project, hardwareProjectScope2); - hardwareScopes2.put(User, userHardwareScope2); - - // Build second hardware config - hardwareConfig2 = HardwareConfig.builder() - .hardware(hardware2) - .scopes(hardwareScopes2) - .build(); - - // Setup invalid hardware config - Hardware hardwareInvalid = Hardware.builder().build(); - Map hardwareScopesInvalid = new HashMap<>(); - hardwareConfigInvalid = HardwareConfig.builder() - .hardware(hardwareInvalid) - .scopes(hardwareScopesInvalid) - .build(); - - // Setup first compute environment - ComputeEnvironment computeEnvironment1 = ComputeEnvironment.builder() - .name("Jupyter Datascience Notebook") - .image("jupyter/datascience-notebook:hub-3.0.0") - .environmentVariables(new ArrayList<>()) - .mounts(new ArrayList<>()) - .build(); - - ComputeEnvironmentScope computeEnvironmentSiteScope1 = ComputeEnvironmentScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentProjectScope1 = ComputeEnvironmentScope.builder() - .scope(Project) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentUserScope1 = ComputeEnvironmentScope.builder() - .scope(User) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - Map computeEnvironmentScopes1 = new HashMap<>(); - computeEnvironmentScopes1.put(Site, computeEnvironmentSiteScope1); - computeEnvironmentScopes1.put(Project, computeEnvironmentProjectScope1); - computeEnvironmentScopes1.put(User, computeEnvironmentUserScope1); - - ComputeEnvironmentHardwareOptions computeEnvironmentHardwareOptions1 = ComputeEnvironmentHardwareOptions.builder() - .allowAllHardware(true) - .hardwareConfigs(new HashSet<>(Arrays.asList(hardwareConfig1, hardwareConfig2))) - .build(); - - computeEnvironmentConfig1 = ComputeEnvironmentConfig.builder() - .configTypes(new HashSet<>(Collections.singletonList(ComputeEnvironmentConfig.ConfigType.JUPYTERHUB))) - .computeEnvironment(computeEnvironment1) - .scopes(computeEnvironmentScopes1) - .hardwareOptions(computeEnvironmentHardwareOptions1) - .build(); - - // Setup second compute environment - ComputeEnvironment computeEnvironment2 = ComputeEnvironment.builder() - .name("XNAT Datascience Notebook") - .image("xnat/datascience-notebook:latest") - .environmentVariables(new ArrayList<>()) - .mounts(new ArrayList<>()) - .build(); - - ComputeEnvironmentScope computeEnvironmentSiteScope2 = ComputeEnvironmentScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentProjectScope2 = ComputeEnvironmentScope.builder() - .scope(Project) - .enabled(false) - .ids(new HashSet<>(Collections.singletonList("Project1"))) - .build(); - - ComputeEnvironmentScope computeEnvironmentUserScope2 = ComputeEnvironmentScope.builder() - .scope(User) - .enabled(false) - .ids(new HashSet<>(Collections.singletonList("User1"))) - .build(); - - Map computeEnvironmentScopes2 = new HashMap<>(); - computeEnvironmentScopes2.put(Site, computeEnvironmentSiteScope2); - computeEnvironmentScopes2.put(Project, computeEnvironmentProjectScope2); - computeEnvironmentScopes2.put(User, computeEnvironmentUserScope2); - - ComputeEnvironmentHardwareOptions computeEnvironmentHardwareOptions2 = ComputeEnvironmentHardwareOptions.builder() - .allowAllHardware(false) - .hardwareConfigs(new HashSet<>(Arrays.asList(hardwareConfig2))) - .build(); - - computeEnvironmentConfig2 = ComputeEnvironmentConfig.builder() - .configTypes(new HashSet<>(Collections.singletonList(ComputeEnvironmentConfig.ConfigType.JUPYTERHUB))) - .computeEnvironment(computeEnvironment2) - .scopes(computeEnvironmentScopes2) - .hardwareOptions(computeEnvironmentHardwareOptions2) - .build(); - - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/services/impl/DefaultJobTemplateServiceTest.java b/src/test/java/org/nrg/xnat/compute/services/impl/DefaultJobTemplateServiceTest.java deleted file mode 100644 index 8a0b2a8..0000000 --- a/src/test/java/org/nrg/xnat/compute/services/impl/DefaultJobTemplateServiceTest.java +++ /dev/null @@ -1,229 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.nrg.framework.constants.Scope; -import org.nrg.xnat.compute.models.*; -import org.nrg.xnat.compute.config.DefaultJobTemplateServiceTestConfig; -import org.nrg.xnat.compute.services.ComputeEnvironmentConfigService; -import org.nrg.xnat.compute.services.ConstraintConfigService; -import org.nrg.xnat.compute.services.HardwareConfigService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.util.*; - -import static org.junit.Assert.*; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = DefaultJobTemplateServiceTestConfig.class) -public class DefaultJobTemplateServiceTest { - - @Autowired private DefaultJobTemplateService jobTemplateService; - @Autowired private ComputeEnvironmentConfigService mockComputeEnvironmentConfigService; - @Autowired private HardwareConfigService mockHardwareConfigService; - @Autowired private ConstraintConfigService mockConstraintConfigService; - - @Before - public void before() { - } - - @After - public void after() { - Mockito.reset( - mockComputeEnvironmentConfigService, - mockHardwareConfigService, - mockConstraintConfigService - ); - } - - @Test - public void testIsAvailable_ComputeEnvironmentNotAvailable() { - // Setup - when(mockComputeEnvironmentConfigService.isAvailable(any(), any())).thenReturn(false); - when(mockHardwareConfigService.isAvailable(any(), any())).thenReturn(true); - - Map executionScope = new HashMap<>(); - executionScope.put(Scope.Site, "site"); - executionScope.put(Scope.Project, "project"); - executionScope.put(Scope.User, "user"); - executionScope.put(Scope.DataType, "xnat:petSessionData"); - executionScope.put(Scope.Experiment, "XNAT_E00001"); - - // Run - boolean isAvailable = jobTemplateService.isAvailable(1L, 1L, executionScope); - - // Verify - assertFalse(isAvailable); - } - - @Test - public void testIsAvailable_HardwareNotAvailable() { - // Setup - when(mockComputeEnvironmentConfigService.isAvailable(any(), any())).thenReturn(true); - when(mockHardwareConfigService.isAvailable(any(), any())).thenReturn(false); - - Map executionScope = new HashMap<>(); - executionScope.put(Scope.Project, "project"); - executionScope.put(Scope.User, "user"); - - // Run - boolean isAvailable = jobTemplateService.isAvailable(1L, 1L, executionScope); - - // Verify - assertFalse(isAvailable); - } - - @Test - public void testIsAvailable_ComputeEnvironmentAndHardwareNotAvailable() { - // Setup - when(mockComputeEnvironmentConfigService.isAvailable(any(), any())).thenReturn(false); - when(mockHardwareConfigService.isAvailable(any(), any())).thenReturn(false); - - // Run - Map executionScope = new HashMap<>(); - executionScope.put(Scope.Project, "project"); - executionScope.put(Scope.User, "user"); - boolean isAvailable = jobTemplateService.isAvailable(1L, 1L, executionScope); - - // Verify - assertFalse(isAvailable); - } - - @Test - public void testIsAvailable_ComputeEnvironmentConfigAllHardwareIsAvailable() { - // Setup - when(mockComputeEnvironmentConfigService.isAvailable(any(), any())).thenReturn(true); - when(mockHardwareConfigService.isAvailable(any(), any())).thenReturn(true); - - ComputeEnvironmentConfig computeEnvironmentConfig = ComputeEnvironmentConfig.builder().build(); - ComputeEnvironmentHardwareOptions hardwareOptions = ComputeEnvironmentHardwareOptions.builder().build(); - hardwareOptions.setAllowAllHardware(true); - computeEnvironmentConfig.setHardwareOptions(hardwareOptions); - when(mockComputeEnvironmentConfigService.retrieve(any())).thenReturn(Optional.of(computeEnvironmentConfig)); - - Map executionScope = new HashMap<>(); - executionScope.put(Scope.Project, "project"); - executionScope.put(Scope.User, "user"); - - // Run - boolean isAvailable = jobTemplateService.isAvailable(1L, 1L, executionScope); - - // Verify - assertTrue(isAvailable); - } - - @Test - public void testIsAvailable_ComputeEnvironmentConfigSpecificHardwareAllowed() { - // Setup - when(mockComputeEnvironmentConfigService.isAvailable(any(), any())).thenReturn(true); - when(mockHardwareConfigService.isAvailable(any(), any())).thenReturn(true); - - ComputeEnvironmentConfig computeEnvironmentConfig = ComputeEnvironmentConfig.builder().id(1L).build(); - ComputeEnvironmentHardwareOptions hardwareOptions = ComputeEnvironmentHardwareOptions.builder().build(); - hardwareOptions.setAllowAllHardware(false); - computeEnvironmentConfig.setHardwareOptions(hardwareOptions); - HardwareConfig hardwareConfig = HardwareConfig.builder().id(1L).build(); - hardwareOptions.setHardwareConfigs(new HashSet<>(Arrays.asList(hardwareConfig))); - when(mockComputeEnvironmentConfigService.retrieve(any())).thenReturn(Optional.of(computeEnvironmentConfig)); - - Map executionScope = new HashMap<>(); - executionScope.put(Scope.Project, "project"); - executionScope.put(Scope.User, "user"); - executionScope.put(Scope.DataType, "xnat:petSessionData"); - executionScope.put(Scope.Experiment, "XNAT_E00001"); - - // Run - boolean isAvailable = jobTemplateService.isAvailable(1L, 1L, executionScope); - - // Verify - assertTrue(isAvailable); - } - - @Test - public void testIsAvailable_ComputeEnvironmentConfigSpecificHardwareNotAllowed() { - // Setup - when(mockComputeEnvironmentConfigService.isAvailable(any(), any())).thenReturn(true); - when(mockHardwareConfigService.isAvailable(any(), any())).thenReturn(true); - - ComputeEnvironmentConfig computeEnvironmentConfig = ComputeEnvironmentConfig.builder().id(1L).build(); - ComputeEnvironmentHardwareOptions hardwareOptions = ComputeEnvironmentHardwareOptions.builder().build(); - hardwareOptions.setAllowAllHardware(false); - computeEnvironmentConfig.setHardwareOptions(hardwareOptions); - HardwareConfig hardwareConfig = HardwareConfig.builder().id(1L).build(); - hardwareOptions.setHardwareConfigs(new HashSet<>(Arrays.asList(hardwareConfig))); - when(mockComputeEnvironmentConfigService.retrieve(any())).thenReturn(Optional.of(computeEnvironmentConfig)); - - Map executionScope = new HashMap<>(); - executionScope.put(Scope.Project, "project"); - executionScope.put(Scope.User, "user"); - executionScope.put(Scope.DataType, "xnat:petSessionData"); - executionScope.put(Scope.Experiment, "XNAT_E00002"); - - // Run - boolean isAvailable = jobTemplateService.isAvailable(1L, 2L, executionScope); - - // Verify - assertFalse(isAvailable); - } - - @Test - public void testResolve() { - // Setup - when(mockComputeEnvironmentConfigService.isAvailable(any(), any())).thenReturn(true); - when(mockHardwareConfigService.isAvailable(any(), any())).thenReturn(true); - - ComputeEnvironmentConfig computeEnvironmentConfig = ComputeEnvironmentConfig.builder().id(1L).build(); - ComputeEnvironment computeEnvironment = ComputeEnvironment.builder() - .name("JupyterHub Data Science Notebook") - .image("jupyter/datascience-notebook:latest") - .build(); - computeEnvironmentConfig.setComputeEnvironment(computeEnvironment); - ComputeEnvironmentHardwareOptions hardwareOptions = ComputeEnvironmentHardwareOptions.builder().build(); - hardwareOptions.setAllowAllHardware(false); - computeEnvironmentConfig.setHardwareOptions(hardwareOptions); - HardwareConfig hardwareConfig = HardwareConfig.builder().id(1L).build(); - Hardware hardware = Hardware.builder() - .name("Standard") - .cpuLimit(1.0) - .memoryLimit("4G") - .build(); - hardwareConfig.setHardware(hardware); - hardwareOptions.setHardwareConfigs(new HashSet<>(Arrays.asList(hardwareConfig))); - - Constraint constraint = Constraint.builder() - .key("node.role") - .operator(Constraint.Operator.IN) - .values(new HashSet<>(Arrays.asList("worker"))) - .build(); - - ConstraintConfig constraintConfig = ConstraintConfig.builder() - .id(1L) - .constraint(constraint) - .build(); - - when(mockComputeEnvironmentConfigService.retrieve(any())).thenReturn(Optional.of(computeEnvironmentConfig)); - when(mockHardwareConfigService.retrieve(any())).thenReturn(Optional.of(hardwareConfig)); - when(mockConstraintConfigService.getAvailable(any())).thenReturn(Collections.singletonList(constraintConfig)); - - Map executionScope = new HashMap<>(); - executionScope.put(Scope.Project, "project"); - executionScope.put(Scope.User, "user"); - - // Run - JobTemplate jobTemplate = jobTemplateService.resolve(1L, 1L, executionScope); - - // Verify - assertNotNull(jobTemplate); - assertEquals(computeEnvironmentConfig.getComputeEnvironment(), jobTemplate.getComputeEnvironment()); - assertEquals(hardware, jobTemplate.getHardware()); - assertEquals(Collections.singletonList(constraint), jobTemplate.getConstraints()); - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/services/impl/HibernateComputeEnvironmentConfigEntityServiceTest.java b/src/test/java/org/nrg/xnat/compute/services/impl/HibernateComputeEnvironmentConfigEntityServiceTest.java deleted file mode 100644 index ddd97b6..0000000 --- a/src/test/java/org/nrg/xnat/compute/services/impl/HibernateComputeEnvironmentConfigEntityServiceTest.java +++ /dev/null @@ -1,505 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.nrg.xnat.compute.models.*; -import org.nrg.framework.constants.Scope; -import org.nrg.xnat.compute.config.HibernateComputeEnvironmentConfigEntityServiceTestConfig; -import org.nrg.xnat.compute.entities.ComputeEnvironmentConfigEntity; -import org.nrg.xnat.compute.entities.HardwareConfigEntity; -import org.nrg.xnat.compute.repositories.ComputeEnvironmentConfigDao; -import org.nrg.xnat.compute.repositories.HardwareConfigDao; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import javax.transaction.Transactional; -import java.util.*; - -import static org.hamcrest.Matchers.is; -import static org.junit.Assert.*; -import static org.nrg.framework.constants.Scope.*; -import static org.nrg.xnat.compute.models.ComputeEnvironmentConfig.ConfigType.CONTAINER_SERVICE; -import static org.nrg.xnat.compute.models.ComputeEnvironmentConfig.ConfigType.JUPYTERHUB; -import static org.nrg.xnat.compute.utils.TestingUtils.commitTransaction; - -@RunWith(SpringJUnit4ClassRunner.class) -@Transactional -@ContextConfiguration(classes = HibernateComputeEnvironmentConfigEntityServiceTestConfig.class) -public class HibernateComputeEnvironmentConfigEntityServiceTest { - - @Autowired private HibernateComputeEnvironmentConfigEntityService hibernateComputeEnvironmentConfigEntityService; - @Autowired @Qualifier("hardwareConfigDaoImpl") private HardwareConfigDao hardwareConfigDaoImpl; - @Autowired @Qualifier("computeEnvironmentConfigDaoImpl") private ComputeEnvironmentConfigDao computeEnvironmentConfigDaoImpl; - - private ComputeEnvironmentConfig computeEnvironmentConfig1; - private ComputeEnvironmentConfig computeEnvironmentConfig2; - private ComputeEnvironmentConfig computeEnvironmentConfig3; - - private HardwareConfig hardwareConfig1; - private HardwareConfig hardwareConfig2; - - @Before - public void before() { - hibernateComputeEnvironmentConfigEntityService.setDao(computeEnvironmentConfigDaoImpl); - createDummyConfigsAndEntities(); - } - - @After - public void after() { - Mockito.reset(); - } - - @Test - public void test() { - assertNotNull(hibernateComputeEnvironmentConfigEntityService); - assertNotNull(hardwareConfigDaoImpl); - assertNotNull(computeEnvironmentConfigDaoImpl); - } - - @Test - @DirtiesContext - public void testCreate() { - // Setup - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity1 = ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig1); - - // Execute - ComputeEnvironmentConfigEntity created = hibernateComputeEnvironmentConfigEntityService.create(computeEnvironmentConfigEntity1); - commitTransaction(); - ComputeEnvironmentConfigEntity retrieved = hibernateComputeEnvironmentConfigEntityService.retrieve(created.getId()); - - // Verify - assertNotNull(retrieved); - assertThat(retrieved.toPojo(), is(created.toPojo())); - } - - @Test - @DirtiesContext - public void testAddHardwareConfigEntity() { - // Setup - HardwareConfigEntity hardwareConfigEntity1 = HardwareConfigEntity.fromPojo(hardwareConfig1); - HardwareConfigEntity hardwareConfigEntity2 = HardwareConfigEntity.fromPojo(hardwareConfig2); - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity1 = ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig1); - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity2 = ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig2); - - // Commit hardware configs - Long hardwareConfigEntity1_id = (Long) hardwareConfigDaoImpl.create(hardwareConfigEntity1); - Long hardwareConfigEntity2_Id = (Long) hardwareConfigDaoImpl.create(hardwareConfigEntity2); - - ComputeEnvironmentConfigEntity createdComputeEnvironmentConfigEntity1 = hibernateComputeEnvironmentConfigEntityService.create(computeEnvironmentConfigEntity1); - ComputeEnvironmentConfigEntity createdComputeEnvironmentConfigEntity2 = hibernateComputeEnvironmentConfigEntityService.create(computeEnvironmentConfigEntity2); - - commitTransaction(); - - // Verify - assertNotNull(hardwareConfigEntity1_id); - assertNotNull(hardwareConfigEntity2_Id); - assertNotNull(createdComputeEnvironmentConfigEntity1); - assertNotNull(createdComputeEnvironmentConfigEntity2); - - // Execute - // Add hardware configs to compute environment configs - hibernateComputeEnvironmentConfigEntityService.addHardwareConfigEntity(createdComputeEnvironmentConfigEntity1.getId(), hardwareConfigEntity1_id); - hibernateComputeEnvironmentConfigEntityService.addHardwareConfigEntity(createdComputeEnvironmentConfigEntity1.getId(), hardwareConfigEntity2_Id); - hibernateComputeEnvironmentConfigEntityService.addHardwareConfigEntity(createdComputeEnvironmentConfigEntity2.getId(), hardwareConfigEntity1_id); - - commitTransaction(); - - // Verify - ComputeEnvironmentConfigEntity retrievedComputeEnvironmentConfigEntity1 = hibernateComputeEnvironmentConfigEntityService.retrieve(createdComputeEnvironmentConfigEntity1.getId()); - ComputeEnvironmentConfigEntity retrievedComputeEnvironmentConfigEntity2 = hibernateComputeEnvironmentConfigEntityService.retrieve(createdComputeEnvironmentConfigEntity2.getId()); - - assertNotNull(retrievedComputeEnvironmentConfigEntity1); - assertNotNull(retrievedComputeEnvironmentConfigEntity2); - assertEquals(2, retrievedComputeEnvironmentConfigEntity1.getHardwareOptions().getHardwareConfigs().size()); - assertEquals(1, retrievedComputeEnvironmentConfigEntity2.getHardwareOptions().getHardwareConfigs().size()); - assertTrue(retrievedComputeEnvironmentConfigEntity1.getHardwareOptions().getHardwareConfigs().stream().map(HardwareConfigEntity::getId).anyMatch(id -> id.equals(hardwareConfigEntity1_id))); - assertTrue(retrievedComputeEnvironmentConfigEntity1.getHardwareOptions().getHardwareConfigs().stream().map(HardwareConfigEntity::getId).anyMatch(id -> id.equals(hardwareConfigEntity2_Id))); - assertTrue(retrievedComputeEnvironmentConfigEntity2.getHardwareOptions().getHardwareConfigs().stream().map(HardwareConfigEntity::getId).anyMatch(id -> id.equals(hardwareConfigEntity1_id))); - } - - @Test - @DirtiesContext - public void testRemoveHardwareConfigEntity() { - // Setup - HardwareConfigEntity hardwareConfigEntity1 = HardwareConfigEntity.fromPojo(hardwareConfig1); - HardwareConfigEntity hardwareConfigEntity2 = HardwareConfigEntity.fromPojo(hardwareConfig2); - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity1 = ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig1); - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity2 = ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig2); - - // Commit hardware configs - Long hardwareConfigEntity1_id = (Long) hardwareConfigDaoImpl.create(hardwareConfigEntity1); - Long hardwareConfigEntity2_Id = (Long) hardwareConfigDaoImpl.create(hardwareConfigEntity2); - - ComputeEnvironmentConfigEntity createdComputeEnvironmentConfigEntity1 = hibernateComputeEnvironmentConfigEntityService.create(computeEnvironmentConfigEntity1); - ComputeEnvironmentConfigEntity createdComputeEnvironmentConfigEntity2 = hibernateComputeEnvironmentConfigEntityService.create(computeEnvironmentConfigEntity2); - - commitTransaction(); - - // Verify - assertNotNull(hardwareConfigEntity1_id); - assertNotNull(hardwareConfigEntity2_Id); - assertNotNull(createdComputeEnvironmentConfigEntity1); - assertNotNull(createdComputeEnvironmentConfigEntity2); - - // Execute - // Add hardware configs to compute environment configs - hibernateComputeEnvironmentConfigEntityService.addHardwareConfigEntity(createdComputeEnvironmentConfigEntity1.getId(), hardwareConfigEntity1_id); - hibernateComputeEnvironmentConfigEntityService.addHardwareConfigEntity(createdComputeEnvironmentConfigEntity1.getId(), hardwareConfigEntity2_Id); - hibernateComputeEnvironmentConfigEntityService.addHardwareConfigEntity(createdComputeEnvironmentConfigEntity2.getId(), hardwareConfigEntity1_id); - - commitTransaction(); - - // Verify - ComputeEnvironmentConfigEntity retrievedComputeEnvironmentConfigEntity1 = hibernateComputeEnvironmentConfigEntityService.retrieve(createdComputeEnvironmentConfigEntity1.getId()); - ComputeEnvironmentConfigEntity retrievedComputeEnvironmentConfigEntity2 = hibernateComputeEnvironmentConfigEntityService.retrieve(createdComputeEnvironmentConfigEntity2.getId()); - - assertNotNull(retrievedComputeEnvironmentConfigEntity1); - assertNotNull(retrievedComputeEnvironmentConfigEntity2); - assertEquals(2, retrievedComputeEnvironmentConfigEntity1.getHardwareOptions().getHardwareConfigs().size()); - assertEquals(1, retrievedComputeEnvironmentConfigEntity2.getHardwareOptions().getHardwareConfigs().size()); - assertTrue(retrievedComputeEnvironmentConfigEntity1.getHardwareOptions().getHardwareConfigs().stream().map(HardwareConfigEntity::getId).anyMatch(id -> id.equals(hardwareConfigEntity1_id))); - assertTrue(retrievedComputeEnvironmentConfigEntity1.getHardwareOptions().getHardwareConfigs().stream().map(HardwareConfigEntity::getId).anyMatch(id -> id.equals(hardwareConfigEntity2_Id))); - assertTrue(retrievedComputeEnvironmentConfigEntity2.getHardwareOptions().getHardwareConfigs().stream().map(HardwareConfigEntity::getId).anyMatch(id -> id.equals(hardwareConfigEntity1_id))); - - // Remove hardware configs from compute environment configs - hibernateComputeEnvironmentConfigEntityService.removeHardwareConfigEntity(createdComputeEnvironmentConfigEntity1.getId(), hardwareConfigEntity1_id); - hibernateComputeEnvironmentConfigEntityService.removeHardwareConfigEntity(createdComputeEnvironmentConfigEntity1.getId(), hardwareConfigEntity2_Id); - - commitTransaction(); - - hibernateComputeEnvironmentConfigEntityService.removeHardwareConfigEntity(createdComputeEnvironmentConfigEntity2.getId(), hardwareConfigEntity1_id); - - commitTransaction(); - - // Verify - retrievedComputeEnvironmentConfigEntity1 = hibernateComputeEnvironmentConfigEntityService.retrieve(createdComputeEnvironmentConfigEntity1.getId()); - retrievedComputeEnvironmentConfigEntity2 = hibernateComputeEnvironmentConfigEntityService.retrieve(createdComputeEnvironmentConfigEntity2.getId()); - - assertNotNull(retrievedComputeEnvironmentConfigEntity1); - assertNotNull(retrievedComputeEnvironmentConfigEntity2); - assertEquals(0, retrievedComputeEnvironmentConfigEntity1.getHardwareOptions().getHardwareConfigs().size()); - assertEquals(0, retrievedComputeEnvironmentConfigEntity2.getHardwareOptions().getHardwareConfigs().size()); - } - - @Test - @DirtiesContext - public void testFindByType() { - // Setup - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity1 = ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig1); - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity2 = ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig2); - ComputeEnvironmentConfigEntity computeEnvironmentConfigEntity3 = ComputeEnvironmentConfigEntity.fromPojo(computeEnvironmentConfig3); - - // Commit compute environment configs - ComputeEnvironmentConfigEntity createdComputeEnvironmentConfigEntity1 = hibernateComputeEnvironmentConfigEntityService.create(computeEnvironmentConfigEntity1); - ComputeEnvironmentConfigEntity createdComputeEnvironmentConfigEntity2 = hibernateComputeEnvironmentConfigEntityService.create(computeEnvironmentConfigEntity2); - ComputeEnvironmentConfigEntity createdComputeEnvironmentConfigEntity3 = hibernateComputeEnvironmentConfigEntityService.create(computeEnvironmentConfigEntity3); - - commitTransaction(); - - // Verify - assertNotNull(createdComputeEnvironmentConfigEntity1); - assertNotNull(createdComputeEnvironmentConfigEntity2); - assertNotNull(createdComputeEnvironmentConfigEntity3); - - // Execute - List retrievedComputeEnvironmentConfigEntities = hibernateComputeEnvironmentConfigEntityService.findByType(JUPYTERHUB); - - // Verify - assertNotNull(retrievedComputeEnvironmentConfigEntities); - assertEquals(2, retrievedComputeEnvironmentConfigEntities.size()); - assertEquals(createdComputeEnvironmentConfigEntity1.getId(), retrievedComputeEnvironmentConfigEntities.get(0).getId()); - assertEquals(createdComputeEnvironmentConfigEntity3.getId(), retrievedComputeEnvironmentConfigEntities.get(1).getId()); - - // Execute - retrievedComputeEnvironmentConfigEntities = hibernateComputeEnvironmentConfigEntityService.findByType(CONTAINER_SERVICE); - - // Verify - assertNotNull(retrievedComputeEnvironmentConfigEntities); - assertEquals(2, retrievedComputeEnvironmentConfigEntities.size()); - assertEquals(createdComputeEnvironmentConfigEntity2.getId(), retrievedComputeEnvironmentConfigEntities.get(0).getId()); - assertEquals(createdComputeEnvironmentConfigEntity3.getId(), retrievedComputeEnvironmentConfigEntities.get(1).getId()); - } - - public void createDummyConfigsAndEntities() { - // Setup hardware - Hardware hardware1 = Hardware.builder() - .name("Small") - .cpuReservation(2.0) - .cpuLimit(4.0) - .memoryReservation("4G") - .memoryLimit("8G") - .build(); - - // Setup hardware constraints - Constraint hardwareConstraint1 = Constraint.builder() - .key("node.role") - .operator(Constraint.Operator.IN) - .values(new HashSet<>(Collections.singletonList("worker"))) - .build(); - - Constraint hardwareConstraint2 = Constraint.builder() - .key("node.instance.type") - .operator(Constraint.Operator.NOT_IN) - .values(new HashSet<>(Arrays.asList("spot", "demand"))) - .build(); - - hardware1.setConstraints(Arrays.asList(hardwareConstraint1, hardwareConstraint2)); - - // Setup hardware environment variables - EnvironmentVariable hardwareEnvironmentVariable1 = new EnvironmentVariable("MATLAB_LICENSE_FILE", "12345@myserver"); - EnvironmentVariable hardwareEnvironmentVariable2 = new EnvironmentVariable("NVIDIA_VISIBLE_DEVICES", "all"); - - hardware1.setEnvironmentVariables(Arrays.asList(hardwareEnvironmentVariable1, hardwareEnvironmentVariable2)); - - // Setup hardware generic resources - GenericResource hardwareGenericResource1 = new GenericResource("nvidia.com/gpu", "2"); - GenericResource hardwareGenericResource2 = new GenericResource("fpga.com/fpga", "1"); - - hardware1.setGenericResources(Arrays.asList(hardwareGenericResource1, hardwareGenericResource2)); - - // Setup hardware scopes - HardwareScope hardwareSiteScope1 = HardwareScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope hardwareProjectScope1 = HardwareScope.builder() - .scope(Project) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope userHardwareScope1 = HardwareScope.builder() - .scope(User) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - Map hardwareScopes1 = new HashMap<>(); - hardwareScopes1.put(Site, hardwareSiteScope1); - hardwareScopes1.put(Project, hardwareProjectScope1); - hardwareScopes1.put(User, userHardwareScope1); - - // Setup a hardware config entity - hardwareConfig1 = HardwareConfig.builder() - .hardware(hardware1) - .scopes(hardwareScopes1) - .build(); - - // Setup second hardware config - Hardware hardware2 = Hardware.builder() - .name("Medium") - .cpuReservation(4.0) - .cpuLimit(4.0) - .memoryReservation("8G") - .memoryLimit("8G") - .build(); - - // Setup hardware constraints - Constraint hardwareConstraint3 = Constraint.builder() - .key("node.role") - .operator(Constraint.Operator.IN) - .values(new HashSet<>(Collections.singletonList("worker"))) - .build(); - - Constraint hardwareConstraint4 = Constraint.builder() - .key("node.instance.type") - .operator(Constraint.Operator.NOT_IN) - .values(new HashSet<>(Arrays.asList("spot", "demand"))) - .build(); - - hardware2.setConstraints(Arrays.asList(hardwareConstraint3, hardwareConstraint4)); - - // Setup hardware environment variables - EnvironmentVariable hardwareEnvironmentVariable3 = new EnvironmentVariable("MATLAB_LICENSE_FILE", "12345@myserver"); - EnvironmentVariable hardwareEnvironmentVariable4 = new EnvironmentVariable("NVIDIA_VISIBLE_DEVICES", "all"); - - hardware2.setEnvironmentVariables(Arrays.asList(hardwareEnvironmentVariable3, hardwareEnvironmentVariable4)); - - // Setup hardware generic resources - GenericResource hardwareGenericResource3 = new GenericResource("nvidia.com/gpu", "2"); - GenericResource hardwareGenericResource4 = new GenericResource("fpga.com/fpga", "1"); - - hardware2.setGenericResources(Arrays.asList(hardwareGenericResource3, hardwareGenericResource4)); - - // Setup hardware scopes - HardwareScope hardwareSiteScope2 = HardwareScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope hardwareProjectScope2 = HardwareScope.builder() - .scope(Project) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - HardwareScope userHardwareScope2 = HardwareScope.builder() - .scope(User) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - Map hardwareScopes2 = new HashMap<>(); - hardwareScopes2.put(Site, hardwareSiteScope2); - hardwareScopes2.put(Project, hardwareProjectScope2); - hardwareScopes2.put(User, userHardwareScope2); - - // Setup second hardware config entity - hardwareConfig2 = HardwareConfig.builder() - .hardware(hardware2) - .scopes(hardwareScopes2) - .build(); - - // Setup first compute environment - // Create mount first - Mount mount1 = Mount.builder() - .localPath("/home/jovyan/work") - .containerPath("/home/jovyan/work") - .readOnly(false) - .build(); - - Mount mount2 = Mount.builder() - .localPath("/tools/MATLAB/R2019b") - .containerPath("/tools/MATLAB/R2019b") - .readOnly(true) - .build(); - - ComputeEnvironment computeEnvironment1 = ComputeEnvironment.builder() - .name("Jupyter Datascience Notebook") - .image("jupyter/datascience-notebook:hub-3.0.0") - .environmentVariables(Collections.singletonList(new EnvironmentVariable("JUPYTER_ENABLE_LAB", "yes"))) - .mounts(Arrays.asList(mount1, mount2)) - .build(); - - ComputeEnvironmentScope computeEnvironmentSiteScope1 = ComputeEnvironmentScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentProjectScope1 = ComputeEnvironmentScope.builder() - .scope(Project) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentUserScope1 = ComputeEnvironmentScope.builder() - .scope(User) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - Map computeEnvironmentScopes1 = new HashMap<>(); - computeEnvironmentScopes1.put(Site, computeEnvironmentSiteScope1); - computeEnvironmentScopes1.put(Project, computeEnvironmentProjectScope1); - computeEnvironmentScopes1.put(User, computeEnvironmentUserScope1); - - ComputeEnvironmentHardwareOptions computeEnvironmentHardwareOptions1 = ComputeEnvironmentHardwareOptions.builder() - .allowAllHardware(true) - .hardwareConfigs(new HashSet<>()) - .build(); - - computeEnvironmentConfig1 = ComputeEnvironmentConfig.builder() - .configTypes(new HashSet<>(Collections.singletonList(JUPYTERHUB))) - .computeEnvironment(computeEnvironment1) - .scopes(computeEnvironmentScopes1) - .hardwareOptions(computeEnvironmentHardwareOptions1) - .build(); - - // Setup second compute environment - ComputeEnvironment computeEnvironment2 = ComputeEnvironment.builder() - .name("XNAT Datascience Notebook") - .image("xnat/datascience-notebook:latest") - .environmentVariables(new ArrayList<>()) - .mounts(new ArrayList<>()) - .build(); - - ComputeEnvironmentScope computeEnvironmentSiteScope2 = ComputeEnvironmentScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentProjectScope2 = ComputeEnvironmentScope.builder() - .scope(Project) - .enabled(false) - .ids(new HashSet<>(Collections.singletonList("Project1"))) - .build(); - - ComputeEnvironmentScope computeEnvironmentUserScope2 = ComputeEnvironmentScope.builder() - .scope(User) - .enabled(false) - .ids(new HashSet<>(Collections.singletonList("User1"))) - .build(); - - Map computeEnvironmentScopes2 = new HashMap<>(); - computeEnvironmentScopes2.put(Site, computeEnvironmentSiteScope2); - computeEnvironmentScopes2.put(Project, computeEnvironmentProjectScope2); - computeEnvironmentScopes2.put(User, computeEnvironmentUserScope2); - - ComputeEnvironmentHardwareOptions computeEnvironmentHardwareOptions2 = ComputeEnvironmentHardwareOptions.builder() - .allowAllHardware(false) - .hardwareConfigs(new HashSet<>()) - .build(); - - computeEnvironmentConfig2 = ComputeEnvironmentConfig.builder() - .configTypes(new HashSet<>(Collections.singletonList(CONTAINER_SERVICE))) - .computeEnvironment(computeEnvironment2) - .scopes(computeEnvironmentScopes2) - .hardwareOptions(computeEnvironmentHardwareOptions2) - .build(); - - // Setup third compute environment - ComputeEnvironment computeEnvironment3 = ComputeEnvironment.builder() - .name("MATLAB Datascience Notebook") - .image("matlab/datascience-notebook:latest") - .environmentVariables(new ArrayList<>()) - .mounts(new ArrayList<>()) - .build(); - - ComputeEnvironmentScope computeEnvironmentSiteScope3 = ComputeEnvironmentScope.builder() - .scope(Site) - .enabled(true) - .ids(new HashSet<>(Collections.emptyList())) - .build(); - - ComputeEnvironmentScope computeEnvironmentProjectScope3 = ComputeEnvironmentScope.builder() - .scope(Project) - .enabled(false) - .ids(new HashSet<>(Collections.singletonList("Project1"))) - .build(); - - ComputeEnvironmentScope computeEnvironmentUserScope3 = ComputeEnvironmentScope.builder() - .scope(User) - .enabled(false) - .ids(new HashSet<>(Collections.singletonList("User1"))) - .build(); - - Map computeEnvironmentScopes3 = new HashMap<>(); - computeEnvironmentScopes2.put(Site, computeEnvironmentSiteScope3); - computeEnvironmentScopes2.put(Project, computeEnvironmentProjectScope3); - computeEnvironmentScopes2.put(User, computeEnvironmentUserScope3); - - ComputeEnvironmentHardwareOptions computeEnvironmentHardwareOptions3 = ComputeEnvironmentHardwareOptions.builder() - .allowAllHardware(false) - .hardwareConfigs(new HashSet<>()) - .build(); - - computeEnvironmentConfig3 = ComputeEnvironmentConfig.builder() - .configTypes(new HashSet<>(Arrays.asList(CONTAINER_SERVICE, JUPYTERHUB))) - .computeEnvironment(computeEnvironment3) - .scopes(computeEnvironmentScopes3) - .hardwareOptions(computeEnvironmentHardwareOptions3) - .build(); - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/services/impl/HibernateConstraintConfigEntityServiceTest.java b/src/test/java/org/nrg/xnat/compute/services/impl/HibernateConstraintConfigEntityServiceTest.java deleted file mode 100644 index 6c6e872..0000000 --- a/src/test/java/org/nrg/xnat/compute/services/impl/HibernateConstraintConfigEntityServiceTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.nrg.framework.constants.Scope; -import org.nrg.xnat.compute.config.HibernateConstraintConfigEntityServiceTestConfig; -import org.nrg.xnat.compute.entities.ConstraintConfigEntity; -import org.nrg.xnat.compute.models.Constraint; -import org.nrg.xnat.compute.models.ConstraintConfig; -import org.nrg.xnat.compute.models.ConstraintScope; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.transaction.annotation.Transactional; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.nrg.xnat.compute.utils.TestingUtils.commitTransaction; - -@RunWith(SpringJUnit4ClassRunner.class) -@Transactional -@ContextConfiguration(classes = HibernateConstraintConfigEntityServiceTestConfig.class) -public class HibernateConstraintConfigEntityServiceTest { - - @Autowired private HibernateConstraintConfigEntityService hibernateConstraintConfigEntityService; - - @Test - public void test() { - assertNotNull(hibernateConstraintConfigEntityService); - } - - @Test - @DirtiesContext - public void testCreateConstraintConfig() { - assertNotNull(hibernateConstraintConfigEntityService); - - // Create a constraint config - Constraint constraint1 = Constraint.builder() - .key("node.role") - .operator(Constraint.Operator.IN) - .values(new HashSet<>(Arrays.asList("worker"))) - .build(); - - ConstraintScope constraintScopeSite1 = ConstraintScope.builder() - .scope(Scope.Site) - .enabled(true) - .ids(new HashSet<>()) - .build(); - - ConstraintScope constraintScopeProject1 = ConstraintScope.builder() - .scope(Scope.Project) - .enabled(true) - .ids(new HashSet<>()) - .build(); - - ConstraintScope constraintScopeUser1 = ConstraintScope.builder() - .scope(Scope.User) - .enabled(true) - .ids(new HashSet<>()) - .build(); - - Map scopes1 = new HashMap<>(); - scopes1.put(Scope.Site, constraintScopeSite1); - scopes1.put(Scope.Project, constraintScopeProject1); - scopes1.put(Scope.User, constraintScopeUser1); - - ConstraintConfig constraintConfig = ConstraintConfig.builder() - .constraint(constraint1) - .scopes(scopes1) - .build(); - - // Save the constraint config - ConstraintConfigEntity created = hibernateConstraintConfigEntityService.create(ConstraintConfigEntity.fromPojo(constraintConfig)); - - commitTransaction(); - - // Retrieve the constraint config - ConstraintConfigEntity retrieved = hibernateConstraintConfigEntityService.retrieve(created.getId()); - - // Check that the retrieved constraint config matches the original - assertEquals(created, retrieved); - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/services/impl/HibernateHardwareConfigEntityServiceTest.java b/src/test/java/org/nrg/xnat/compute/services/impl/HibernateHardwareConfigEntityServiceTest.java deleted file mode 100644 index 8902fd2..0000000 --- a/src/test/java/org/nrg/xnat/compute/services/impl/HibernateHardwareConfigEntityServiceTest.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.nrg.xnat.compute.services.impl; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.nrg.xnat.compute.config.HibernateHardwareConfigEntityServiceTestConfig; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.junit.Assert.*; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(classes = HibernateHardwareConfigEntityServiceTestConfig.class) -public class HibernateHardwareConfigEntityServiceTest { - - @Autowired private HibernateHardwareConfigEntityService hibernateHardwareConfigEntityService; - - @Test - public void test() { - assertNotNull(hibernateHardwareConfigEntityService); - } - -} \ No newline at end of file diff --git a/src/test/java/org/nrg/xnat/compute/utils/TestingUtils.java b/src/test/java/org/nrg/xnat/compute/utils/TestingUtils.java deleted file mode 100644 index 76a2129..0000000 --- a/src/test/java/org/nrg/xnat/compute/utils/TestingUtils.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.nrg.xnat.compute.utils; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.test.context.transaction.TestTransaction; - -@Slf4j -public class TestingUtils { - - public static void commitTransaction() { - TestTransaction.flagForCommit(); - TestTransaction.end(); - TestTransaction.start(); - } - -}