diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index cfe013a..0000000 --- a/.dockerignore +++ /dev/null @@ -1,2 +0,0 @@ -**/node_modules/ -**/target diff --git a/Jenkinsfile b/Jenkinsfile deleted file mode 100644 index e5ba5f7..0000000 --- a/Jenkinsfile +++ /dev/null @@ -1,32 +0,0 @@ -pipeline { - - agent any - - environment { - DOCKER_TLS_VERIFY='1' - COMPOSE_TLS_VERSION='TLSv1_2' - DOCKER_CERT_PATH='/home/jenkins/jenkinscerts' - DOCKER_HOST='tcp://:443' - DTR_FQDN_PORT=':4443' - } - - stages { - stage('Build') { - environment { - DTR_ACCESS_KEY = credentials('jenkins-dtr-access-token') - MAJORMINOR = '0.0' - } - steps { - sh 'docker image build -t ${DTR_FQDN_PORT}/engineering/api-build:rc-${MAJORMINOR}.${BUILD_ID} api' - sh 'docker login -u jenkins -p ${DTR_ACCESS_KEY} ${DTR_FQDN_PORT}' - sh 'docker image push ${DTR_FQDN_PORT}/engineering/api-build:rc-${MAJORMINOR}.${BUILD_ID}' - } - } - } - - post { - always{ - sh 'rm -rf ${WORKSPACE}/*' - } - } -} diff --git a/README.md b/README.md new file mode 100644 index 0000000..7509c66 --- /dev/null +++ b/README.md @@ -0,0 +1,9 @@ +``` +docker secret create password db/mypassword +docker image build -t myapi:demo api +docker stack deploy -c docker-compose.yaml demo +``` + + - http://localhost:8080/demo/price?name=widget : our API endpoint. `name` can be `widget` or `sprocket` + - http://localhost:8080/swagger-ui.html : autogenerated API docs + - http://localhost:8081/ : database admin interface diff --git a/api/.classpath b/api/.classpath deleted file mode 100644 index 6d7587a..0000000 --- a/api/.classpath +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/api/.gitignore b/api/.gitignore deleted file mode 100644 index b83d222..0000000 --- a/api/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/target/ diff --git a/api/.project b/api/.project deleted file mode 100644 index d3dffa4..0000000 --- a/api/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - ddev - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.jdt.core.javanature - org.eclipse.m2e.core.maven2Nature - - diff --git a/api/.settings/org.eclipse.core.resources.prefs b/api/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index abdea9a..0000000 --- a/api/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,4 +0,0 @@ -eclipse.preferences.version=1 -encoding//src/main/java=UTF-8 -encoding//src/main/resources=UTF-8 -encoding/=UTF-8 diff --git a/api/.settings/org.eclipse.jdt.core.prefs b/api/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 714351a..0000000 --- a/api/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,5 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 -org.eclipse.jdt.core.compiler.compliance=1.8 -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.8 diff --git a/api/.settings/org.eclipse.m2e.core.prefs b/api/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f..0000000 --- a/api/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/api/Dockerfile b/api/Dockerfile index 210b75a..d006d57 100644 --- a/api/Dockerfile +++ b/api/Dockerfile @@ -1,13 +1,12 @@ -FROM maven:3.6.3-jdk-8 AS appserver -WORKDIR /usr/src/ddev -COPY pom.xml . -RUN mvn -B -f pom.xml -s /usr/share/maven/ref/settings-docker.xml dependency:resolve -COPY . . -RUN mvn -B -s /usr/share/maven/ref/settings-docker.xml package -DskipTests +FROM gradle:jdk10 as build +WORKDIR /home/gradle/project +COPY build.gradle . +COPY src ./src +USER root +RUN gradle build + +FROM openjdk:10-jre-slim +COPY --from=build /home/gradle/project/build/libs/gs-rest-service-0.1.0.jar /gs-rest-service-0.1.0.jar +ENTRYPOINT java -jar /gs-rest-service-0.1.0.jar + -FROM java:8-jdk-alpine -RUN adduser -Dh /home/gordon gordon -WORKDIR /app -COPY --from=appserver /usr/src/ddev/target/ddev-0.0.1-SNAPSHOT.jar . -ENTRYPOINT ["java", "-jar", "/app/ddev-0.0.1-SNAPSHOT.jar"] -CMD ["--spring.profiles.active=postgres"] diff --git a/api/build.gradle b/api/build.gradle new file mode 100644 index 0000000..bda0882 --- /dev/null +++ b/api/build.gradle @@ -0,0 +1,33 @@ +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath("org.springframework.boot:spring-boot-gradle-plugin:2.0.5.RELEASE") + } +} + +apply plugin: 'java' +apply plugin: 'org.springframework.boot' +apply plugin: 'io.spring.dependency-management' + +bootJar { + baseName = 'gs-rest-service' + version = '0.1.0' +} + +repositories { + mavenCentral() +} + +sourceCompatibility = 1.8 +targetCompatibility = 1.8 + +dependencies { + compile("org.springframework.boot:spring-boot-starter-web") + testCompile('org.springframework.boot:spring-boot-starter-test') + implementation 'org.mariadb.jdbc:mariadb-java-client:2.4.0' + compile "io.springfox:springfox-swagger2:2.9.2" + compile "io.springfox:springfox-swagger-ui:2.9.2" + runtime('org.postgresql:postgresql') +} diff --git a/api/pom.xml b/api/pom.xml deleted file mode 100644 index 1984e06..0000000 --- a/api/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - 4.0.0 - - - org.springframework.boot - spring-boot-starter-parent - 1.5.3.RELEASE - - - com.docker.ddev - ddev - 0.0.1-SNAPSHOT - ddev - - - 1.8 - 1.4.187 - - - - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework - spring-core - - - - org.springframework.boot - spring-boot-starter-data-jpa - - - - com.zaxxer - HikariCP - - - - com.h2database - h2 - - - - org.postgresql - postgresql - - - - org.hibernate - hibernate-c3p0 - 5.2.10.Final - - - - org.springframework.boot - spring-boot-starter-jdbc - - - org.springframework - spring-jdbc - - - com.googlecode.json-simple - json-simple - - - org.springframework.boot - spring-boot-starter-security - - - - org.springframework.boot - spring-boot-devtools - - - - org.apache.commons - commons-lang3 - 3.0 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - true - - - - - \ No newline at end of file diff --git a/api/src/main/java/com/docker/ddev/DdevApp.java b/api/src/main/java/com/docker/ddev/DdevApp.java deleted file mode 100644 index 180df0a..0000000 --- a/api/src/main/java/com/docker/ddev/DdevApp.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.docker.ddev; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Import; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; - -import com.docker.ddev.configuration.JpaConfiguration; - - -@Import(JpaConfiguration.class) -@SpringBootApplication(scanBasePackages={"com.docker.ddev"}) -@EntityScan("com.docker.ddev.model") -@EnableJpaRepositories("com.docker.ddev.repository") -public class DdevApp { - public static void main(String[] args) { - SpringApplication.run(DdevApp.class, args); - } -} \ No newline at end of file diff --git a/api/src/main/java/com/docker/ddev/configuration/BeanConfiguration.java b/api/src/main/java/com/docker/ddev/configuration/BeanConfiguration.java deleted file mode 100644 index 7f44c1f..0000000 --- a/api/src/main/java/com/docker/ddev/configuration/BeanConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.docker.ddev.configuration; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; - -import com.docker.ddev.service.ProductService; -import com.docker.ddev.service.ProductServiceImpl; -import com.mchange.v2.c3p0.ComboPooledDataSource; - -public class BeanConfiguration { - - @Bean - public ProductService productService() { - return new ProductServiceImpl(); - } - - // Implement C3P0 connection pooling - @Bean - @ConfigurationProperties("ddev.datasource") - public ComboPooledDataSource dataSource() { - return new ComboPooledDataSource(); - } -} \ No newline at end of file diff --git a/api/src/main/java/com/docker/ddev/configuration/JpaConfiguration.java b/api/src/main/java/com/docker/ddev/configuration/JpaConfiguration.java deleted file mode 100644 index a0257c5..0000000 --- a/api/src/main/java/com/docker/ddev/configuration/JpaConfiguration.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.docker.ddev.configuration; - -import java.util.Properties; -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; - -import javax.naming.NamingException; -import javax.persistence.EntityManagerFactory; -import javax.sql.DataSource; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder; -import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; -import org.springframework.core.env.Environment; -import org.springframework.data.jpa.repository.config.EnableJpaRepositories; -import org.springframework.orm.jpa.JpaTransactionManager; -import org.springframework.orm.jpa.JpaVendorAdapter; -import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; -import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.annotation.EnableTransactionManagement; - -import com.zaxxer.hikari.HikariDataSource; - -@Configuration -@EnableJpaRepositories(basePackages = "com.docker.ddev.repositories", - entityManagerFactoryRef = "entityManagerFactory", - transactionManagerRef = "transactionManager") -@EnableTransactionManagement -public class JpaConfiguration { - - @Autowired - private Environment environment; - - - /* - * Populate SpringBoot DataSourceProperties from application.yml - */ - @Bean - @Primary - @ConfigurationProperties(prefix = "datasource.ddev") - public DataSourceProperties dataSourceProperties() { - DataSourceProperties dataSourceProperties = new DataSourceProperties(); - - // Set password to connect to postgres using Docker secrets. - try(BufferedReader br = new BufferedReader(new FileReader("/run/secrets/postgres_password"))) { - StringBuilder sb = new StringBuilder(); - String line = br.readLine(); - - while (line != null) { - sb.append(line); - sb.append(System.lineSeparator()); - line = br.readLine(); - } - dataSourceProperties.setDataPassword(sb.toString()); - } catch (IOException e) { - System.err.println("Could not successfully load DB password file"); - } - - return dataSourceProperties; - } - - /* - * Configure HikariCP pooled DataSource. - */ - @Bean - public DataSource dataSource() { - DataSourceProperties dataSourceProperties = dataSourceProperties(); - HikariDataSource dataSource = (HikariDataSource) DataSourceBuilder - .create(dataSourceProperties.getClassLoader()) - .driverClassName(dataSourceProperties.getDriverClassName()) - .url(dataSourceProperties.getUrl()) - .username(dataSourceProperties.getUsername()) - .password(dataSourceProperties.getPassword()) - .type(HikariDataSource.class) - .build(); - return dataSource; - } - - /* - * Entity Manager Factory setup. - */ - @Bean - public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException { - LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean(); - factoryBean.setDataSource(dataSource()); - factoryBean.setPackagesToScan(new String[] { "com.docker.ddev.model" }); - factoryBean.setJpaVendorAdapter(jpaVendorAdapter()); - factoryBean.setJpaProperties(jpaProperties()); - return factoryBean; - } - - /* - * Provider specific adapter. - */ - @Bean - public JpaVendorAdapter jpaVendorAdapter() { - HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter(); - return hibernateJpaVendorAdapter; - } - - /* - * Provider specific properties. - */ - private Properties jpaProperties() { - Properties properties = new Properties(); - properties.put("hibernate.dialect", environment.getRequiredProperty("datasource.ddev.hibernate.dialect")); - properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("datasource.ddev.hibernate.hbm2ddl.method")); - properties.put("hibernate.show_sql", environment.getRequiredProperty("datasource.ddev.hibernate.show_sql")); - properties.put("hibernate.format_sql", environment.getRequiredProperty("datasource.ddev.hibernate.format_sql")); - if(StringUtils.isNotEmpty(environment.getRequiredProperty("datasource.ddev.defaultSchema"))){ - properties.put("hibernate.default_schema", environment.getRequiredProperty("datasource.ddev.defaultSchema")); - } - return properties; - } - - @Bean - @Autowired - public PlatformTransactionManager transactionManager(EntityManagerFactory emf) { - JpaTransactionManager txManager = new JpaTransactionManager(); - txManager.setEntityManagerFactory(emf); - return txManager; - } - -} \ No newline at end of file diff --git a/api/src/main/java/com/docker/ddev/controller/ProductController.java b/api/src/main/java/com/docker/ddev/controller/ProductController.java deleted file mode 100644 index 14e2258..0000000 --- a/api/src/main/java/com/docker/ddev/controller/ProductController.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.docker.ddev.controller; - -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -import com.docker.ddev.model.Product; -import com.docker.ddev.service.ProductService; -import com.docker.ddev.util.CustomErrorType; - -@RestController -@RequestMapping("/api") -public class ProductController { - public static final Logger logger = LoggerFactory.getLogger(ProductController.class); - - @Autowired - ProductService productService; - - // -------------------Retrieve All Products--------------------------------------------- - - @RequestMapping(value = "/products/", method = RequestMethod.GET) - public ResponseEntity> listAllProducts() { - List products = productService.findAllProducts(); - if (products.isEmpty()) { - return new ResponseEntity>(HttpStatus.NO_CONTENT); - } - return new ResponseEntity>(products, HttpStatus.OK); - } - - // -------------------Retrieve Single Product By Id------------------------------------------ - - @SuppressWarnings({ "unchecked", "rawtypes" }) - @RequestMapping(value = "/products/{productId}", method = RequestMethod.GET) - public ResponseEntity getProduct(@PathVariable("productId") long productId) { - logger.info("Fetching Product with id {}", productId); - Product product = productService.findById(productId); - if (product == null) { - logger.error("Product with id {} not found.", productId); - return new ResponseEntity(new CustomErrorType("Product with id " + productId - + " not found"), HttpStatus.NOT_FOUND); - } - return new ResponseEntity(product, HttpStatus.OK); - } -} \ No newline at end of file diff --git a/api/src/main/java/com/docker/ddev/model/Product.java b/api/src/main/java/com/docker/ddev/model/Product.java deleted file mode 100644 index aa37877..0000000 --- a/api/src/main/java/com/docker/ddev/model/Product.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.docker.ddev.model; - -import org.hibernate.validator.constraints.NotEmpty; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonInclude.Include; - -import java.io.Serializable; -import javax.persistence.*; - -@Entity -@Table(name="products", uniqueConstraints = { @UniqueConstraint(columnNames = "productid")}) -@JsonInclude(Include.NON_NULL) -public class Product implements Serializable { - - private static final long serialVersionUID = 3222530297013481114L; - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long productId; - - @NotEmpty - @Column(name = "price", nullable = false) - private double price; - - @Column(name = "description", length=10485760, nullable = false) - private String description; - - public Product() { - - } - - public Product(Long productId, String description, double price) { - this.productId = productId; - this.price = price; - this.description = description; - } - - public long getProductId() { - return productId; - } - - public void setProductId(long productId) { - this.productId = productId; - } - - public double getPrice() { - return price; - } - - public void setPrice(double price) { - this.price = price; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - @Override - public String toString() { - return "Product [productId=" + productId + - ", price=" + price + - ", description=" + description + - "]"; - } - -} \ No newline at end of file diff --git a/api/src/main/java/com/docker/ddev/repositories/ProductRepository.java b/api/src/main/java/com/docker/ddev/repositories/ProductRepository.java deleted file mode 100644 index 2e86ee6..0000000 --- a/api/src/main/java/com/docker/ddev/repositories/ProductRepository.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.docker.ddev.repositories; - -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; -import org.springframework.transaction.annotation.Transactional; - -import com.docker.ddev.model.Product; - -@Repository -@Transactional -public interface ProductRepository extends JpaRepository { -} \ No newline at end of file diff --git a/api/src/main/java/com/docker/ddev/security/SecurityConfiguration.java b/api/src/main/java/com/docker/ddev/security/SecurityConfiguration.java deleted file mode 100644 index cab148b..0000000 --- a/api/src/main/java/com/docker/ddev/security/SecurityConfiguration.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.docker.ddev.security; - -import javax.sql.DataSource; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; - -@Configuration -@EnableWebSecurity -public class SecurityConfiguration extends WebSecurityConfigurerAdapter { - // -----Basic Authentication implemented but not used ------- - @Override - protected void configure(HttpSecurity http) throws Exception { - - http.authorizeRequests() - .anyRequest().permitAll() - .and().httpBasic() - .and().csrf().disable(); - } -} \ No newline at end of file diff --git a/api/src/main/java/com/docker/ddev/service/ProductService.java b/api/src/main/java/com/docker/ddev/service/ProductService.java deleted file mode 100644 index 2c6fe60..0000000 --- a/api/src/main/java/com/docker/ddev/service/ProductService.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.docker.ddev.service; - -import java.util.List; -import com.docker.ddev.model.Product; - -public interface ProductService { - List findAllProducts(); - Product findById(Long productId); -} \ No newline at end of file diff --git a/api/src/main/java/com/docker/ddev/service/ProductServiceImpl.java b/api/src/main/java/com/docker/ddev/service/ProductServiceImpl.java deleted file mode 100644 index c99a448..0000000 --- a/api/src/main/java/com/docker/ddev/service/ProductServiceImpl.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.docker.ddev.service; - -import java.util.List; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import com.docker.ddev.model.Product; -import com.docker.ddev.repositories.ProductRepository; - -@Service("productService") -@Transactional -public class ProductServiceImpl implements ProductService { - @Autowired - private ProductRepository productRepository; - - public List findAllProducts() { - return productRepository.findAll(); - } - - public Product findById(Long productId) { - return productRepository.findOne(productId); - } -} \ No newline at end of file diff --git a/api/src/main/java/com/docker/ddev/util/CustomErrorType.java b/api/src/main/java/com/docker/ddev/util/CustomErrorType.java deleted file mode 100644 index 99f053d..0000000 --- a/api/src/main/java/com/docker/ddev/util/CustomErrorType.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.docker.ddev.util; - -public class CustomErrorType { - private String errorMessage; - public CustomErrorType(String errorMessage){ - this.errorMessage = errorMessage; - } - public String getErrorMessage() { - return errorMessage; - } -} \ No newline at end of file diff --git a/api/src/main/java/prices/Application.java b/api/src/main/java/prices/Application.java new file mode 100644 index 0000000..1f28235 --- /dev/null +++ b/api/src/main/java/prices/Application.java @@ -0,0 +1,12 @@ +package prices; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } +} diff --git a/api/src/main/java/prices/Prices.java b/api/src/main/java/prices/Prices.java new file mode 100644 index 0000000..bb62867 --- /dev/null +++ b/api/src/main/java/prices/Prices.java @@ -0,0 +1,39 @@ +package prices; + +import java.sql.*; + +public class Prices { + + private final Double price; + + public Prices(String name) { + + Double p=0.0; + + try { + // query template + String query = "SELECT PRICE from PRODUCTS WHERE NAME=?"; + + // connect and execute + Connection conn = DriverManager.getConnection("jdbc:postgresql://db:5432/mydb", "moby", "12345678"); + PreparedStatement ps = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); + ps.setString(1, name); + ResultSet rs = ps.executeQuery(); + + // extract price + if (rs.isBeforeFirst()) { + rs.first(); + p=Double.parseDouble(rs.getString(1)); + } + + } catch (SQLException e) { + e.printStackTrace(); + } + + this.price = p; + } + + public Double getPrice() { + return price; + } +} \ No newline at end of file diff --git a/api/src/main/java/prices/SpringFoxConfig.java b/api/src/main/java/prices/SpringFoxConfig.java new file mode 100644 index 0000000..e47c891 --- /dev/null +++ b/api/src/main/java/prices/SpringFoxConfig.java @@ -0,0 +1,40 @@ +package prices; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import java.util.Collections; + +@Configuration +@EnableSwagger2 +public class SpringFoxConfig { + @Bean + public Docket apiDocket() { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("prices")) + .paths(PathSelectors.any()) + .build() + .apiInfo(getApiInfo()); + } + + private ApiInfo getApiInfo() { + return new ApiInfo( + "API Demo", + "A springboot API, with auto-generated swagger docs", + "VERSION", + "TERMS OF SERVICE URL", + new Contact("NAME","URL","EMAIL"), + "LICENSE", + "LICENSE URL", + Collections.emptyList() + ); + } +} + diff --git a/api/src/main/java/prices/priceController.java b/api/src/main/java/prices/priceController.java new file mode 100644 index 0000000..f049a46 --- /dev/null +++ b/api/src/main/java/prices/priceController.java @@ -0,0 +1,20 @@ +package prices; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@RestController +@RequestMapping("/demo") +@Api(value="demoapi", description="A demo API block") +public class priceController { + + @ApiOperation(value = "Fetch the price corresponding to a product", response = Iterable.class) + @RequestMapping(value = "/price", method = RequestMethod.GET) + public Prices price(@RequestParam(value="name", defaultValue="widget") String name) { + return new Prices(name); + } +} diff --git a/api/src/main/resources/application.yml b/api/src/main/resources/application.yml deleted file mode 100644 index 0e8cd61..0000000 --- a/api/src/main/resources/application.yml +++ /dev/null @@ -1,51 +0,0 @@ ---- -server: - port: 8080 - contextPath: / ---- -spring: - profiles: local, default -datasource: - ddev: - url: jdbc:h2:~/test - username: SA - password: - driverClassName: org.h2.Driver - defaultSchema: - maxPoolSize: 10 - hibernate: - hbm2ddl.method: create-drop - show_sql: true - format_sql: true - dialect: org.hibernate.dialect.H2Dialect ---- -spring: - profiles: postgres - devtools: - remote: - secret: secretkey - restart: - enabled: true - livereload: - enabled: true -datasource: - ddev: - url: jdbc:postgresql://database:5432/ddev - username: gordonuser - password: gordonpass - driverClassName: org.postgresql.Driver - defaultSchema: - maxConnections: 300 - initialConnections: 20 - maxAge: 30000 - testOnBorrow: true - testWhileIdle: true - timeBetweenEvictionRunsMillis: 60000 - validationQuery: SELECT 1 - minPoolSize: 6 - maxPoolSize: 15 - hibernate: - hbm2ddl.method: update - show_sql: true - format_sql: true - dialect: org.hibernate.dialect.PostgreSQLDialect diff --git a/database/Dockerfile b/database/Dockerfile deleted file mode 100644 index 60914dc..0000000 --- a/database/Dockerfile +++ /dev/null @@ -1,14 +0,0 @@ -FROM postgres:9.6 - -# Copy the database initialize script: -# Contents of /docker-entrypoint-initdb.d are run on startup -RUN mkdir -p /images/ - -COPY pg_hba.conf /usr/share/postgresql/9.6/ -COPY postgresql.conf /usr/share/postgresql/9.6/ -ADD docker-entrypoint-initdb.d/ /docker-entrypoint-initdb.d/ - -# Default values for passwords and database name. Can be overridden on docker run -ENV POSTGRES_USER gordonuser -ENV POSTGRES_PASSWORD password -ENV POSTGRES_DB ddev diff --git a/database/docker-entrypoint-initdb.d/init-db.sql b/database/docker-entrypoint-initdb.d/init-db.sql deleted file mode 100644 index a7819dd..0000000 --- a/database/docker-entrypoint-initdb.d/init-db.sql +++ /dev/null @@ -1,19 +0,0 @@ --- create table for products - -CREATE TABLE products -( - productid serial UNIQUE PRIMARY KEY, - description character varying(10485760) NOT NULL, - price real NOT NULL -); - -ALTER TABLE products - OWNER TO gordonuser; -ALTER ROLE gordonuser CONNECTION LIMIT -1; - --- add image data -INSERT INTO products (description, price) VALUES('resistor', 0.01); -INSERT INTO products (description, price) VALUES('capacitor', 0.02); -INSERT INTO products (description, price) VALUES('diode', 0.03); -INSERT INTO products (description, price) VALUES('transistor', 0.04); -INSERT INTO products (description, price) VALUES('breadboard', 1.00); \ No newline at end of file diff --git a/database/pg_hba.conf b/database/pg_hba.conf deleted file mode 100644 index a92249f..0000000 --- a/database/pg_hba.conf +++ /dev/null @@ -1,91 +0,0 @@ -# PostgreSQL Client Authentication Configuration File -# =================================================== -# -# Refer to the "Client Authentication" section in the PostgreSQL -# documentation for a complete description of this file. A short -# synopsis follows. -# -# This file controls: which hosts are allowed to connect, how clients -# are authenticated, which PostgreSQL user names they can use, which -# databases they can access. Records take one of these forms: -# -# local DATABASE USER METHOD [OPTIONS] -# host DATABASE USER ADDRESS METHOD [OPTIONS] -# hostssl DATABASE USER ADDRESS METHOD [OPTIONS] -# hostnossl DATABASE USER ADDRESS METHOD [OPTIONS] -# -# (The uppercase items must be replaced by actual values.) -# -# The first field is the connection type: "local" is a Unix-domain -# socket, "host" is either a plain or SSL-encrypted TCP/IP socket, -# "hostssl" is an SSL-encrypted TCP/IP socket, and "hostnossl" is a -# plain TCP/IP socket. -# -# DATABASE can be "all", "sameuser", "samerole", "replication", a -# database name, or a comma-separated list thereof. The "all" -# keyword does not match "replication". Access to replication -# must be enabled in a separate record (see example below). -# -# USER can be "all", a user name, a group name prefixed with "+", or a -# comma-separated list thereof. In both the DATABASE and USER fields -# you can also write a file name prefixed with "@" to include names -# from a separate file. -# -# ADDRESS specifies the set of hosts the record matches. It can be a -# host name, or it is made up of an IP address and a CIDR mask that is -# an integer (between 0 and 32 (IPv4) or 128 (IPv6) inclusive) that -# specifies the number of significant bits in the mask. A host name -# that starts with a dot (.) matches a suffix of the actual host name. -# Alternatively, you can write an IP address and netmask in separate -# columns to specify the set of hosts. Instead of a CIDR-address, you -# can write "samehost" to match any of the server's own IP addresses, -# or "samenet" to match any address in any subnet that the server is -# directly connected to. -# -# METHOD can be "trust", "reject", "md5", "password", "gss", "sspi", -# "ident", "peer", "pam", "ldap", "radius" or "cert". Note that -# "password" sends passwords in clear text; "md5" is preferred since -# it sends encrypted passwords. -# -# OPTIONS are a set of options for the authentication in the format -# NAME=VALUE. The available options depend on the different -# authentication methods -- refer to the "Client Authentication" -# section in the documentation for a list of which options are -# available for which authentication methods. -# -# Database and user names containing spaces, commas, quotes and other -# special characters must be quoted. Quoting one of the keywords -# "all", "sameuser", "samerole" or "replication" makes the name lose -# its special character, and just match a database or username with -# that name. -# -# This file is read on server startup and when the postmaster receives -# a SIGHUP signal. If you edit the file on a running system, you have -# to SIGHUP the postmaster for the changes to take effect. You can -# use "pg_ctl reload" to do that. - -# Put your actual configuration here -# ---------------------------------- -# -# If you want to allow non-local connections, you need to add more -# "host" records. In that case you will also need to make PostgreSQL -# listen on a non-local interface via the listen_addresses -# configuration parameter, or via the -i or -h command line switches. - -@authcomment@ - -# TYPE DATABASE USER ADDRESS METHOD - -@remove-line-for-nolocal@ -# "local" is for Unix domain socket connections only -@@remove-line-for-nolocal@local all all @authmethod@ -# IPv4 local connections: -host all all 0.0.0.0/0 trust -# IPv6 local connections: -host all all ::1/128 @authmethodhost@ -# Allow replication connections from localhost, by a user with the -# replication privilege. -@remove-line-for-nolocal@ -#local replication @default_username@ @authmethodlocal@ -#host replication @default_username@ 127.0.0.1/32 @authmethodhost@ -#host replication @default_username@ ::1/128 @authmethodhost@ \ No newline at end of file diff --git a/database/postgresql.conf b/database/postgresql.conf deleted file mode 100644 index d69ce12..0000000 --- a/database/postgresql.conf +++ /dev/null @@ -1,642 +0,0 @@ -# ----------------------------- -# PostgreSQL configuration file -# ----------------------------- -# -# This file consists of lines of the form: -# -# name = value -# -# (The "=" is optional.) Whitespace may be used. Comments are introduced with -# "#" anywhere on a line. The complete list of parameter names and allowed -# values can be found in the PostgreSQL documentation. -# -# The commented-out settings shown in this file represent the default values. -# Re-commenting a setting is NOT sufficient to revert it to the default value; -# you need to reload the server. -# -# This file is read on server startup and when the server receives a SIGHUP -# signal. If you edit the file on a running system, you have to SIGHUP the -# server for the changes to take effect, or use "pg_ctl reload". Some -# parameters, which are marked below, require a server shutdown and restart to -# take effect. -# -# Any parameter can also be given as a command-line option to the server, e.g., -# "postgres -c log_connections=on". Some parameters can be changed at run time -# with the "SET" SQL command. -# -# Memory units: kB = kilobytes Time units: ms = milliseconds -# MB = megabytes s = seconds -# GB = gigabytes min = minutes -# TB = terabytes h = hours -# d = days - - -#------------------------------------------------------------------------------ -# FILE LOCATIONS -#------------------------------------------------------------------------------ - -# The default values of these variables are driven from the -D command-line -# option or PGDATA environment variable, represented here as ConfigDir. - -#data_directory = 'ConfigDir' # use data in another directory - # (change requires restart) -#hba_file = 'ConfigDir/pg_hba.conf' # host-based authentication file - # (change requires restart) -#ident_file = 'ConfigDir/pg_ident.conf' # ident configuration file - # (change requires restart) - -# If external_pid_file is not explicitly set, no extra PID file is written. -#external_pid_file = '' # write an extra PID file - # (change requires restart) - - -#------------------------------------------------------------------------------ -# CONNECTIONS AND AUTHENTICATION -#------------------------------------------------------------------------------ - -# - Connection Settings - - -listen_addresses = '*','localhost','127.0.0.1' -#listen_addresses = '*','127.0.0.1' - # comma-separated list of addresses; - # defaults to 'localhost'; use '*' for all - # (change requires restart) -#port = 5432 # (change requires restart) -max_connections = 100 # (change requires restart) -#superuser_reserved_connections = 3 # (change requires restart) -#unix_socket_directories = '/tmp' # comma-separated list of directories - # (change requires restart) -#unix_socket_group = '' # (change requires restart) -#unix_socket_permissions = 0777 # begin with 0 to use octal notation - # (change requires restart) -#bonjour = off # advertise server via Bonjour - # (change requires restart) -#bonjour_name = '' # defaults to the computer name - # (change requires restart) - -# - Security and Authentication - - -#authentication_timeout = 1min # 1s-600s -#ssl = off # (change requires restart) -#ssl_ciphers = 'HIGH:MEDIUM:+3DES:!aNULL' # allowed SSL ciphers - # (change requires restart) -#ssl_prefer_server_ciphers = on # (change requires restart) -#ssl_ecdh_curve = 'prime256v1' # (change requires restart) -#ssl_cert_file = 'server.crt' # (change requires restart) -#ssl_key_file = 'server.key' # (change requires restart) -#ssl_ca_file = '' # (change requires restart) -#ssl_crl_file = '' # (change requires restart) -#password_encryption = on -#db_user_namespace = off -#row_security = on - -# GSSAPI using Kerberos -#krb_server_keyfile = '' -#krb_caseins_users = off - -# - TCP Keepalives - -# see "man 7 tcp" for details - -#tcp_keepalives_idle = 0 # TCP_KEEPIDLE, in seconds; - # 0 selects the system default -#tcp_keepalives_interval = 0 # TCP_KEEPINTVL, in seconds; - # 0 selects the system default -#tcp_keepalives_count = 0 # TCP_KEEPCNT; - # 0 selects the system default - - -#------------------------------------------------------------------------------ -# RESOURCE USAGE (except WAL) -#------------------------------------------------------------------------------ - -# - Memory - - -#shared_buffers = 32MB # min 128kB - # (change requires restart) -#huge_pages = try # on, off, or try - # (change requires restart) -#temp_buffers = 8MB # min 800kB -#max_prepared_transactions = 0 # zero disables the feature - # (change requires restart) -# Caution: it is not advisable to set max_prepared_transactions nonzero unless -# you actively intend to use prepared transactions. -#work_mem = 4MB # min 64kB -#maintenance_work_mem = 64MB # min 1MB -#replacement_sort_tuples = 150000 # limits use of replacement selection sort -#autovacuum_work_mem = -1 # min 1MB, or -1 to use maintenance_work_mem -#max_stack_depth = 2MB # min 100kB -#dynamic_shared_memory_type = posix # the default is the first option - # supported by the operating system: - # posix - # sysv - # windows - # mmap - # use none to disable dynamic shared memory - -# - Disk - - -#temp_file_limit = -1 # limits per-process temp file space - # in kB, or -1 for no limit - -# - Kernel Resource Usage - - -#max_files_per_process = 1000 # min 25 - # (change requires restart) -#shared_preload_libraries = '' # (change requires restart) - -# - Cost-Based Vacuum Delay - - -#vacuum_cost_delay = 0 # 0-100 milliseconds -#vacuum_cost_page_hit = 1 # 0-10000 credits -#vacuum_cost_page_miss = 10 # 0-10000 credits -#vacuum_cost_page_dirty = 20 # 0-10000 credits -#vacuum_cost_limit = 200 # 1-10000 credits - -# - Background Writer - - -#bgwriter_delay = 200ms # 10-10000ms between rounds -#bgwriter_lru_maxpages = 100 # 0-1000 max buffers written/round -#bgwriter_lru_multiplier = 2.0 # 0-10.0 multiplier on buffers scanned/round -#bgwriter_flush_after = 0 # measured in pages, 0 disables - -# - Asynchronous Behavior - - -#effective_io_concurrency = 1 # 1-1000; 0 disables prefetching -#max_worker_processes = 8 # (change requires restart) -#max_parallel_workers_per_gather = 0 # taken from max_worker_processes -#old_snapshot_threshold = -1 # 1min-60d; -1 disables; 0 is immediate - # (change requires restart) -#backend_flush_after = 0 # measured in pages, 0 disables - - -#------------------------------------------------------------------------------ -# WRITE AHEAD LOG -#------------------------------------------------------------------------------ - -# - Settings - - -#wal_level = minimal # minimal, replica, or logical - # (change requires restart) -#fsync = on # flush data to disk for crash safety - # (turning this off can cause - # unrecoverable data corruption) -#synchronous_commit = on # synchronization level; - # off, local, remote_write, remote_apply, or on -#wal_sync_method = fsync # the default is the first option - # supported by the operating system: - # open_datasync - # fdatasync (default on Linux) - # fsync - # fsync_writethrough - # open_sync -#full_page_writes = on # recover from partial page writes -#wal_compression = off # enable compression of full-page writes -#wal_log_hints = off # also do full page writes of non-critical updates - # (change requires restart) -#wal_buffers = -1 # min 32kB, -1 sets based on shared_buffers - # (change requires restart) -#wal_writer_delay = 200ms # 1-10000 milliseconds -#wal_writer_flush_after = 1MB # measured in pages, 0 disables - -#commit_delay = 0 # range 0-100000, in microseconds -#commit_siblings = 5 # range 1-1000 - -# - Checkpoints - - -#checkpoint_timeout = 5min # range 30s-1d -#max_wal_size = 1GB -#min_wal_size = 80MB -#checkpoint_completion_target = 0.5 # checkpoint target duration, 0.0 - 1.0 -#checkpoint_flush_after = 0 # measured in pages, 0 disables -#checkpoint_warning = 30s # 0 disables - -# - Archiving - - -#archive_mode = off # enables archiving; off, on, or always - # (change requires restart) -#archive_command = '' # command to use to archive a logfile segment - # placeholders: %p = path of file to archive - # %f = file name only - # e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f' -#archive_timeout = 0 # force a logfile segment switch after this - # number of seconds; 0 disables - - -#------------------------------------------------------------------------------ -# REPLICATION -#------------------------------------------------------------------------------ - -# - Sending Server(s) - - -# Set these on the master and on any standby that will send replication data. - -#max_wal_senders = 0 # max number of walsender processes - # (change requires restart) -#wal_keep_segments = 0 # in logfile segments, 16MB each; 0 disables -#wal_sender_timeout = 60s # in milliseconds; 0 disables - -#max_replication_slots = 0 # max number of replication slots - # (change requires restart) -#track_commit_timestamp = off # collect timestamp of transaction commit - # (change requires restart) - -# - Master Server - - -# These settings are ignored on a standby server. - -#synchronous_standby_names = '' # standby servers that provide sync rep - # number of sync standbys and comma-separated list of application_name - # from standby(s); '*' = all -#vacuum_defer_cleanup_age = 0 # number of xacts by which cleanup is delayed - -# - Standby Servers - - -# These settings are ignored on a master server. - -#hot_standby = off # "on" allows queries during recovery - # (change requires restart) -#max_standby_archive_delay = 30s # max delay before canceling queries - # when reading WAL from archive; - # -1 allows indefinite delay -#max_standby_streaming_delay = 30s # max delay before canceling queries - # when reading streaming WAL; - # -1 allows indefinite delay -#wal_receiver_status_interval = 10s # send replies at least this often - # 0 disables -#hot_standby_feedback = off # send info from standby to prevent - # query conflicts -#wal_receiver_timeout = 60s # time that receiver waits for - # communication from master - # in milliseconds; 0 disables -#wal_retrieve_retry_interval = 5s # time to wait before retrying to - # retrieve WAL after a failed attempt - - -#------------------------------------------------------------------------------ -# QUERY TUNING -#------------------------------------------------------------------------------ - -# - Planner Method Configuration - - -#enable_bitmapscan = on -#enable_hashagg = on -#enable_hashjoin = on -#enable_indexscan = on -#enable_indexonlyscan = on -#enable_material = on -#enable_mergejoin = on -#enable_nestloop = on -#enable_seqscan = on -#enable_sort = on -#enable_tidscan = on - -# - Planner Cost Constants - - -#seq_page_cost = 1.0 # measured on an arbitrary scale -#random_page_cost = 4.0 # same scale as above -#cpu_tuple_cost = 0.01 # same scale as above -#cpu_index_tuple_cost = 0.005 # same scale as above -#cpu_operator_cost = 0.0025 # same scale as above -#parallel_tuple_cost = 0.1 # same scale as above -#parallel_setup_cost = 1000.0 # same scale as above -#min_parallel_relation_size = 8MB -#effective_cache_size = 4GB - -# - Genetic Query Optimizer - - -#geqo = on -#geqo_threshold = 12 -#geqo_effort = 5 # range 1-10 -#geqo_pool_size = 0 # selects default based on effort -#geqo_generations = 0 # selects default based on effort -#geqo_selection_bias = 2.0 # range 1.5-2.0 -#geqo_seed = 0.0 # range 0.0-1.0 - -# - Other Planner Options - - -#default_statistics_target = 100 # range 1-10000 -#constraint_exclusion = partition # on, off, or partition -#cursor_tuple_fraction = 0.1 # range 0.0-1.0 -#from_collapse_limit = 8 -#join_collapse_limit = 8 # 1 disables collapsing of explicit - # JOIN clauses -#force_parallel_mode = off - - -#------------------------------------------------------------------------------ -# ERROR REPORTING AND LOGGING -#------------------------------------------------------------------------------ - -# - Where to Log - - -#log_destination = 'stderr' # Valid values are combinations of - # stderr, csvlog, syslog, and eventlog, - # depending on platform. csvlog - # requires logging_collector to be on. - -# This is used when logging to stderr: -logging_collector = on # Enable capturing of stderr and csvlog - # into log files. Required to be on for - # csvlogs. - # (change requires restart) - -# These are only used if logging_collector is on: -log_directory = 'pg_log' # directory where log files are written, - # can be absolute or relative to PGDATA -log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' # log file name pattern, - # can include strftime() escapes -log_file_mode = 0600 # creation mode for log files, - # begin with 0 to use octal notation -log_truncate_on_rotation = off # If on, an existing log file with the - # same name as the new log file will be - # truncated rather than appended to. - # But such truncation only occurs on - # time-driven rotation, not on restarts - # or size-driven rotation. Default is - # off, meaning append to existing files - # in all cases. -#log_rotation_age = 1d # Automatic rotation of logfiles will - # happen after that time. 0 disables. -#log_rotation_size = 10MB # Automatic rotation of logfiles will - # happen after that much log output. - # 0 disables. - -# These are relevant when logging to syslog: -#syslog_facility = 'LOCAL0' -#syslog_ident = 'postgres' -#syslog_sequence_numbers = on -#syslog_split_messages = on - -# This is only relevant when logging to eventlog (win32): -#event_source = 'PostgreSQL' - -# - When to Log - - -#client_min_messages = notice # values in order of decreasing detail: - # debug5 - # debug4 - # debug3 - # debug2 - # debug1 - # log - # notice - # warning - # error - -#log_min_messages = warning # values in order of decreasing detail: - # debug5 - # debug4 - # debug3 - # debug2 - # debug1 - # info - # notice - # warning - # error - # log - # fatal - # panic - -#log_min_error_statement = error # values in order of decreasing detail: - # debug5 - # debug4 - # debug3 - # debug2 - # debug1 - # info - # notice - # warning - # error - # log - # fatal - # panic (effectively off) - -#log_min_duration_statement = -1 # -1 is disabled, 0 logs all statements - # and their durations, > 0 logs only - # statements running at least this number - # of milliseconds - - -# - What to Log - - -#debug_print_parse = off -#debug_print_rewritten = off -#debug_print_plan = off -#debug_pretty_print = on -#log_checkpoints = off -log_connections = off -log_disconnections = off -#log_duration = off -log_error_verbosity = verbose # terse, default, or verbose messages -#log_hostname = off -#log_line_prefix = '' # special values: - # %a = application name - # %u = user name - # %d = database name - # %r = remote host and port - # %h = remote host - # %p = process ID - # %t = timestamp without milliseconds - # %m = timestamp with milliseconds - # %n = timestamp with milliseconds (as a Unix epoch) - # %i = command tag - # %e = SQL state - # %c = session ID - # %l = session line number - # %s = session start timestamp - # %v = virtual transaction ID - # %x = transaction ID (0 if none) - # %q = stop here in non-session - # processes - # %% = '%' - # e.g. '<%u%%%d> ' -#log_lock_waits = off # log lock waits >= deadlock_timeout -#log_statement = 'none' # none, ddl, mod, all -#log_replication_commands = off -#log_temp_files = -1 # log temporary files equal or larger - # than the specified size in kilobytes; - # -1 disables, 0 logs all temp files -#log_timezone = 'GMT' - - -# - Process Title - - -#cluster_name = '' # added to process titles if nonempty - # (change requires restart) -#update_process_title = on - - -#------------------------------------------------------------------------------ -# RUNTIME STATISTICS -#------------------------------------------------------------------------------ - -# - Query/Index Statistics Collector - - -#track_activities = on -#track_counts = on -#track_io_timing = off -#track_functions = none # none, pl, all -#track_activity_query_size = 1024 # (change requires restart) -#stats_temp_directory = 'pg_stat_tmp' - - -# - Statistics Monitoring - - -#log_parser_stats = off -#log_planner_stats = off -#log_executor_stats = off -#log_statement_stats = off - - -#------------------------------------------------------------------------------ -# AUTOVACUUM PARAMETERS -#------------------------------------------------------------------------------ - -#autovacuum = on # Enable autovacuum subprocess? 'on' - # requires track_counts to also be on. -#log_autovacuum_min_duration = -1 # -1 disables, 0 logs all actions and - # their durations, > 0 logs only - # actions running at least this number - # of milliseconds. -#autovacuum_max_workers = 3 # max number of autovacuum subprocesses - # (change requires restart) -#autovacuum_naptime = 1min # time between autovacuum runs -#autovacuum_vacuum_threshold = 50 # min number of row updates before - # vacuum -#autovacuum_analyze_threshold = 50 # min number of row updates before - # analyze -#autovacuum_vacuum_scale_factor = 0.2 # fraction of table size before vacuum -#autovacuum_analyze_scale_factor = 0.1 # fraction of table size before analyze -#autovacuum_freeze_max_age = 200000000 # maximum XID age before forced vacuum - # (change requires restart) -#autovacuum_multixact_freeze_max_age = 400000000 # maximum multixact age - # before forced vacuum - # (change requires restart) -#autovacuum_vacuum_cost_delay = 20ms # default vacuum cost delay for - # autovacuum, in milliseconds; - # -1 means use vacuum_cost_delay -#autovacuum_vacuum_cost_limit = -1 # default vacuum cost limit for - # autovacuum, -1 means use - # vacuum_cost_limit - - -#------------------------------------------------------------------------------ -# CLIENT CONNECTION DEFAULTS -#------------------------------------------------------------------------------ - -# - Statement Behavior - - -#search_path = '"$user", public' # schema names -#default_tablespace = '' # a tablespace name, '' uses the default -#temp_tablespaces = '' # a list of tablespace names, '' uses - # only default tablespace -#check_function_bodies = on -#default_transaction_isolation = 'read committed' -#default_transaction_read_only = off -#default_transaction_deferrable = off -#session_replication_role = 'origin' -#statement_timeout = 0 # in milliseconds, 0 is disabled -#lock_timeout = 0 # in milliseconds, 0 is disabled -#idle_in_transaction_session_timeout = 0 # in milliseconds, 0 is disabled -#vacuum_freeze_min_age = 50000000 -#vacuum_freeze_table_age = 150000000 -#vacuum_multixact_freeze_min_age = 5000000 -#vacuum_multixact_freeze_table_age = 150000000 -#bytea_output = 'hex' # hex, escape -#xmlbinary = 'base64' -#xmloption = 'content' -#gin_fuzzy_search_limit = 0 -#gin_pending_list_limit = 4MB - -# - Locale and Formatting - - -#datestyle = 'iso, mdy' -#intervalstyle = 'postgres' -#timezone = 'GMT' -#timezone_abbreviations = 'Default' # Select the set of available time zone - # abbreviations. Currently, there are - # Default - # Australia (historical usage) - # India - # You can create your own file in - # share/timezonesets/. -#extra_float_digits = 0 # min -15, max 3 -#client_encoding = sql_ascii # actually, defaults to database - # encoding - -# These settings are initialized by initdb, but they can be changed. -#lc_messages = 'C' # locale for system error message - # strings -#lc_monetary = 'C' # locale for monetary formatting -#lc_numeric = 'C' # locale for number formatting -#lc_time = 'C' # locale for time formatting - -# default configuration for text search -#default_text_search_config = 'pg_catalog.simple' - -# - Other Defaults - - -#dynamic_library_path = '$libdir' -#local_preload_libraries = '' -#session_preload_libraries = '' - - -#------------------------------------------------------------------------------ -# LOCK MANAGEMENT -#------------------------------------------------------------------------------ - -#deadlock_timeout = 1s -#max_locks_per_transaction = 64 # min 10 - # (change requires restart) -#max_pred_locks_per_transaction = 64 # min 10 - # (change requires restart) - - -#------------------------------------------------------------------------------ -# VERSION/PLATFORM COMPATIBILITY -#------------------------------------------------------------------------------ - -# - Previous PostgreSQL Versions - - -#array_nulls = on -#backslash_quote = safe_encoding # on, off, or safe_encoding -#default_with_oids = off -#escape_string_warning = on -#lo_compat_privileges = off -#operator_precedence_warning = off -#quote_all_identifiers = off -#sql_inheritance = on -#standard_conforming_strings = on -#synchronize_seqscans = on - -# - Other Platforms and Clients - - -#transform_null_equals = off - - -#------------------------------------------------------------------------------ -# ERROR HANDLING -#------------------------------------------------------------------------------ - -#exit_on_error = off # terminate session on any error? -#restart_after_crash = on # reinitialize after backend crash? - - -#------------------------------------------------------------------------------ -# CONFIG FILE INCLUDES -#------------------------------------------------------------------------------ - -# These options allow settings to be loaded from files other than the -# default postgresql.conf. - -#include_dir = 'conf.d' # include files ending in '.conf' from - # directory 'conf.d' -#include_if_exists = 'exists.conf' # include file only if it exists -#include = 'special.conf' # include file - - -#------------------------------------------------------------------------------ -# CUSTOMIZED OPTIONS -#------------------------------------------------------------------------------ - -# Add settings for extensions here \ No newline at end of file diff --git a/db/db-init.sh b/db/db-init.sh new file mode 100644 index 0000000..8e9459a --- /dev/null +++ b/db/db-init.sh @@ -0,0 +1,8 @@ +#!/bin/bash +set -e + +psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL + CREATE TABLE PRODUCTS(PRICE FLOAT, NAME TEXT); + INSERT INTO PRODUCTS VALUES('18.95', 'widget'); + INSERT INTO PRODUCTS VALUES('1.45', 'sprocket'); +EOSQL \ No newline at end of file diff --git a/db/mypassword b/db/mypassword new file mode 100644 index 0000000..97b5955 --- /dev/null +++ b/db/mypassword @@ -0,0 +1 @@ +12345678 diff --git a/db/myvars.env b/db/myvars.env new file mode 100644 index 0000000..49afdd3 --- /dev/null +++ b/db/myvars.env @@ -0,0 +1,2 @@ +POSTGRES_USER=moby +POSTGRES_DB=mydb \ No newline at end of file diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..20070bc --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,39 @@ +version: "3.7" + +services: + db: + image: postgres:9.6 + networks: + - demonet + env_file: + - db/myvars.env + configs: + - source: initscript + target: /docker-entrypoint-initdb.d/init.sh + secrets: + - password + environment: + - POSTGRES_PASSWORD_FILE=/run/secrets/password + api: + image: myapi:demo + networks: + - demonet + ports: + - 8080:8080 + dbui: + image: adminer + networks: + - demonet + ports: + - 8081:8080 + +configs: + initscript: + file: ./db/db-init.sh + +secrets: + password: + external: true + +networks: + demonet: diff --git a/helm/Chart.yaml b/helm/Chart.yaml deleted file mode 100644 index 3cc7f2f..0000000 --- a/helm/Chart.yaml +++ /dev/null @@ -1,21 +0,0 @@ -apiVersion: v2 -name: demochart -description: A Helm chart for Kubernetes - -# A chart can be either an 'application' or a 'library' chart. -# -# Application charts are a collection of templates that can be packaged into versioned archives -# to be deployed. -# -# Library charts provide useful utilities or functions for the chart developer. They're included as -# a dependency of application charts to inject those utilities and functions into the rendering -# pipeline. Library charts do not define any templates and therefore cannot be deployed. -type: application - -# This is the chart version. This version number should be incremented each time you make changes -# to the chart and its templates, including the app version. -version: 0.1.0 - -# This is the version number of the application being deployed. This version number should be -# incremented each time you make changes to the application. -appVersion: 1.16.0 diff --git a/helm/templates/api.deploy.yaml b/helm/templates/api.deploy.yaml deleted file mode 100644 index dbfea78..0000000 --- a/helm/templates/api.deploy.yaml +++ /dev/null @@ -1,17 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: api -spec: - replicas: 1 - selector: - matchLabels: - app: api - template: - metadata: - labels: - app: api - spec: - containers: - - name: springboot - image: {{ .Values.DTR.FQDN }}:{{ .Values.DTR.port }}/{{ .Values.API.repo }}:{{ .Values.API.tag }} diff --git a/helm/templates/api.service.yaml b/helm/templates/api.service.yaml deleted file mode 100644 index b0309fe..0000000 --- a/helm/templates/api.service.yaml +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: api-ingress -spec: - type: NodePort - selector: - app: api - ports: - - port: 8080 - targetPort: 8080 diff --git a/helm/templates/db.deploy.yaml b/helm/templates/db.deploy.yaml deleted file mode 100644 index d3f9e90..0000000 --- a/helm/templates/db.deploy.yaml +++ /dev/null @@ -1,17 +0,0 @@ -apiVersion: apps/v1 -kind: Deployment -metadata: - name: db -spec: - replicas: 1 - selector: - matchLabels: - app: db - template: - metadata: - labels: - app: db - spec: - containers: - - name: postgres - image: {{ .Values.DTR.FQDN }}:{{ .Values.DTR.port }}/engineering/db:{{ .Values.DB.tag }} diff --git a/helm/templates/db.service.yaml b/helm/templates/db.service.yaml deleted file mode 100644 index 7138c32..0000000 --- a/helm/templates/db.service.yaml +++ /dev/null @@ -1,10 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: database -spec: - selector: - app: db - ports: - - port: 5432 - targetPort: 5432 diff --git a/helm/values.yaml b/helm/values.yaml deleted file mode 100644 index 681ffbe..0000000 --- a/helm/values.yaml +++ /dev/null @@ -1,10 +0,0 @@ -DTR: - FQDN: - port: 4443 - -DB: - tag: '1.0' - -API: - repo: 'engineering/api-build' - tag: 'demo' diff --git a/readme.md b/readme.md deleted file mode 100644 index b5d1312..0000000 --- a/readme.md +++ /dev/null @@ -1,27 +0,0 @@ -## A simple micorservice application - -This app consists of two containerized components: - - - A postgres database - - A springboot-driven API. - -This is meant to serve as a minimal but nontrivial demo app for use in containerization and orchestration education programs. - -### Setup - -1. Log into whatever registry you want to host your images on, and make sure it's happy creating repositories on push. - -2. From the root of this repository (make sure to fill in the first): - - ``` - export REGISTRY= - export OWNER= - docker image build -t ${REGISTRY}/${OWNER}/api:0.1 api - docker image build -t ${REGISTRY}/${OWNER}/db:0.1 database - docker image push ${REGISTRY}/${OWNER}/api:0.1 - docker image push ${REGISTRY}/${OWNER}/db:0.1 - ``` - -3. Edit the `image` entries in `app.yaml` to match your api and db image names you just pushed, and deploy with `kubectl apply -f app.yaml`. - -4. Check the port selected for your `api-ingress` service. Hit your API like `curl localhost:/api/products/1`.