Skip to content

Commit

Permalink
[TH2-5132] Refactored
Browse files Browse the repository at this point in the history
  • Loading branch information
Nikita-Smirnov-Exactpro committed Nov 30, 2023
1 parent a083b18 commit c3c3faa
Show file tree
Hide file tree
Showing 29 changed files with 254 additions and 341 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.exactpro.th2.inframgr;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand All @@ -29,19 +30,19 @@
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
@SuppressWarnings("unused")
public class BasicAuthConfig {
public class BasicAuthConfiguration {

private static final String ADMIN_ROLE = "ADMIN";

public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();
@Autowired
private Config config;

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
Expand All @@ -57,9 +58,13 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
}

@Bean
public UserDetailsService userDetailsService() throws IOException {
Config config = Config.getInstance();
List<UserDetails> admins = config.getHttp().getAdminAccounts().entrySet().stream()
public UserDetailsService userDetailsService() {
Map<String, String> adminAccounts = config.getHttp().getAdminAccounts();
if (adminAccounts.isEmpty()) {
throw new IllegalStateException("'http.adminAccounts' mustn't be empty");
}

List<UserDetails> admins = adminAccounts.entrySet().stream()
.map(entry -> User.builder()
.username(entry.getKey())
.password(entry.getValue())
Expand All @@ -71,6 +76,6 @@ public UserDetailsService userDetailsService() throws IOException {

@Bean
public PasswordEncoder passwordEncoder() {
return PASSWORD_ENCODER;
return new BCryptPasswordEncoder();
}
}
19 changes: 6 additions & 13 deletions src/main/java/com/exactpro/th2/inframgr/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -128,17 +128,9 @@ public void setKubernetes(K8sConfig kubernetes) {

private Config() {}

public static Config getInstance() throws IOException {
if (instance == null) {
synchronized (Config.class) {
if (instance == null) {
Path file = CONFIG_DIR.resolve(CONFIG_FILE);
instance = readConfiguration(file);
}
}
}

return instance;
public static Config instance() throws IOException {
Path file = CONFIG_DIR.resolve(CONFIG_FILE);
return readConfiguration(file);
}

private static void parseFile(File file, ObjectMapper mapper, Object object) throws IOException {
Expand Down Expand Up @@ -170,8 +162,9 @@ static Config readConfiguration(Path configFile) throws IOException {
if (config.getHttp() == null) {
throw new IllegalStateException("'http' config can't be null");
}

config.getHttp().validate();
if (config.getHttp().getAdminAccounts() == null) {
throw new IllegalStateException("'http.adminAccounts' config can't be null");
}

return config;
} catch (UnrecognizedPropertyException e) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@
import java.util.List;

@Controller
@SuppressWarnings("unused")
public class DeploymentController {

public static final String UNKNOWN_ERROR = "UNKNOWN_ERROR";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import com.exactpro.th2.infrarepo.ResourceType;
import io.fabric8.kubernetes.client.ResourceNotFoundException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
Expand All @@ -37,7 +38,6 @@
import static com.exactpro.th2.inframgr.statuswatcher.ResourcePath.annotationFor;

@Controller
@SuppressWarnings("unused")
public class DescriptorController {

private static final String PROTOBUF_DESCRIPTOR = "protobuf-description-base64";
Expand All @@ -50,6 +50,9 @@ public class DescriptorController {

private static final String UNKNOWN_ERROR = "UNKNOWN_ERROR";

@Autowired
private Config config;

@GetMapping("/descriptor/{schema}/{kind}/{box}")
@ResponseBody
public Response getDescriptor(@PathVariable(name = "schema") String schemaName,
Expand All @@ -70,7 +73,6 @@ public Response getDescriptor(@PathVariable(name = "schema") String schemaName,

String descriptor;
try {
Config config = Config.getInstance();
Kubernetes kube = new Kubernetes(config.getBehaviour(), config.getKubernetes(), schemaName);
RegistryCredentialLookup secretMapper = new RegistryCredentialLookup(kube);
RegistryConnection registryConnection = new RegistryConnection(secretMapper.getCredentials());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,17 @@

package com.exactpro.th2.inframgr;

import com.exactpro.th2.inframgr.metrics.PrometheusServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.io.IOException;

@SpringBootApplication
@EnableScheduling
@EnableAutoConfiguration(exclude = {CassandraAutoConfiguration.class})
Expand All @@ -33,16 +35,16 @@ public class InfraManagerApplication {
public static void main(String[] args) {

try {
// preload configuration
Config.getInstance();

PrometheusServer.start();
SpringApplication application = new SpringApplication(InfraManagerApplication.class);
application.run(args);

} catch (Exception e) {
Logger logger = LoggerFactory.getLogger(InfraManagerApplication.class);
logger.error("Exiting with exception", e);
}
}

@Bean
public Config config() throws IOException {
return Config.instance();
}
}
9 changes: 6 additions & 3 deletions src/main/java/com/exactpro/th2/inframgr/JobController.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.eclipse.jgit.api.errors.GitAPIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

Expand All @@ -36,7 +37,6 @@
import static com.exactpro.th2.inframgr.statuswatcher.ResourcePath.annotationFor;

@RestController
@SuppressWarnings("unused")
public class JobController {

private static final String UNKNOWN_ERROR = "UNKNOWN_ERROR";
Expand All @@ -49,6 +49,9 @@ public class JobController {

private static final Logger LOGGER = LoggerFactory.getLogger(JobController.class);

@Autowired
private Config config;

@PutMapping("/jobs/{schemaName}/{jobName}")
public void putSecrets(@PathVariable(name = "schemaName") String schemaName,
@PathVariable(name = "jobName") String jobName) {
Expand All @@ -61,11 +64,11 @@ public void putSecrets(@PathVariable(name = "schemaName") String schemaName,
}

try (Kubernetes kube = new Kubernetes(
Config.getInstance().getBehaviour(), Config.getInstance().getKubernetes(), schemaName
config.getBehaviour(), config.getKubernetes(), schemaName
)) {
RepositoryResource resource;
String resourceLabel;
GitterContext ctx = GitterContext.getContext(Config.getInstance().getGit());
GitterContext ctx = GitterContext.getContext(config.getGit());
Gitter gitter = ctx.getGitter(schemaName);
try {
gitter.lock();
Expand Down
37 changes: 5 additions & 32 deletions src/main/java/com/exactpro/th2/inframgr/NamespaceController.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,27 @@
import com.exactpro.th2.inframgr.errors.NotAcceptableException;
import com.exactpro.th2.inframgr.errors.ServiceException;
import com.exactpro.th2.inframgr.k8s.K8sCustomResource;
import com.exactpro.th2.inframgr.statuswatcher.Condition;
import com.exactpro.th2.inframgr.statuswatcher.ResourceCondition;
import com.exactpro.th2.infrarepo.git.Gitter;
import com.exactpro.th2.infrarepo.git.GitterContext;
import com.exactpro.th2.infrarepo.repo.Repository;
import com.exactpro.th2.infrarepo.settings.RepositorySettingsResource;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.fabric8.kubernetes.api.model.Namespace;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
import io.fabric8.kubernetes.client.dsl.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@SuppressWarnings("unused")
public class NamespaceController {

private static final Logger LOGGER = LoggerFactory.getLogger(NamespaceController.class);
Expand All @@ -57,6 +52,9 @@ public class NamespaceController {

public static final String BAD_RESOURCE_NAME = "BAD_RESOURCE_NAME";

@Autowired
private Config config;

@DeleteMapping("/namespace/{schemaName}")
@ResponseBody
public String getResourceDeploymentStatuses(HttpServletRequest request,
Expand All @@ -68,7 +66,6 @@ public String getResourceDeploymentStatuses(HttpServletRequest request,
throw new NotAcceptableException(BAD_RESOURCE_NAME, "Invalid schema name");
}

Config config = Config.getInstance();
String namespace = config.getKubernetes().getNamespacePrefix() + schemaName;
LOGGER.debug("Checking namespace \"{}\"", namespace);
try (KubernetesClient kubeClient = new KubernetesClientBuilder().build()) {
Expand Down Expand Up @@ -108,31 +105,7 @@ public String getResourceDeploymentStatuses(HttpServletRequest request,
throw e;
} catch (Exception e) {
throw new ServiceException(HttpStatus.INTERNAL_SERVER_ERROR, UNKNOWN_ERROR,
"Exception deleting namespace related to schema " + schemaName + " from kuber", e);
}
}

public static class ResponseEntry {

@JsonProperty("kind")
public String kind;

@JsonProperty("name")
public String name;

@JsonProperty("conditions")
public List<Condition> conditions;

@JsonProperty("status")
public String status;

public ResponseEntry(ResourceCondition resource) {
kind = resource.getKind();
name = resource.getName();
status = resource.getStatus().toString();
if (resource.getConditions() != null) {
conditions = new ArrayList<>(resource.getConditions().values());
}
"Exception deleting namespace related to schema " + schemaName + " from kubernetes", e);
}
}
}
5 changes: 3 additions & 2 deletions src/main/java/com/exactpro/th2/inframgr/PodController.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,16 @@
import static com.exactpro.th2.inframgr.statuswatcher.ResourcePath.annotationFor;

@Controller
@SuppressWarnings("unused")
public class PodController {
private static final Logger LOGGER = LoggerFactory.getLogger(PodController.class);

private static final String UNKNOWN_ERROR = "UNKNOWN_ERROR";

private static final String BAD_RESOURCE_NAME = "BAD_RESOURCE_NAME";

@Autowired
private Config config;

@Autowired
private StatusCache statusCache;

Expand All @@ -59,7 +61,6 @@ public ResponseEntity<?> deleteResourcePods(
throw new NotAcceptableException(BAD_RESOURCE_NAME, "Invalid schema name");
}

Config config = Config.getInstance();
try (Kubernetes kubernetes = new Kubernetes(config.getBehaviour(), config.getKubernetes(), schemaName)) {
for (var resource : statusCache.getResourceDependencyStatuses(schemaName, kind, resourceName)) {
if (resource.getKind().equals(Kubernetes.KIND_POD)) {
Expand Down
Loading

0 comments on commit c3c3faa

Please sign in to comment.