Commit 973a393b authored by Spiros Koulouzis's avatar Spiros Koulouzis

cleanup old code

parent 97f29837
<?xml version="1.0" encoding="UTF-8"?>
<enunciate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://enunciate.webcohesion.com/schemas/enunciate-1.30.xsd">
<facets>
<exclude name="internal_api" />
</facets>
<api-classes>
<include pattern="nl.uva.sne.drip.api.v1.rest.*" />
</api-classes>
<api-import pattern="nl.uva.sne.drip.drip.commons.data.v1.external.*"/>
<api-import pattern="nl.uva.sne.drip.drip.commons.data.v1.external.ansible.*"/>
<modules>
<swagger disabled="true" />
</modules>
</enunciate>
<?xml version="1.0" encoding="UTF-8"?>
<project-shared-configuration>
<!--
This file contains additional configuration written by modules in the NetBeans IDE.
The configuration is intended to be shared among all the users of project and
therefore it is assumed to be part of version control checkout.
Without this configuration present, some functionality in the IDE may be limited or fail altogether.
-->
<properties xmlns="http://www.netbeans.org/ns/maven-properties-data/1">
<!--
Properties that influence various parts of the IDE, especially code formatting and the like.
You can copy and paste the single properties, into the pom.xml file and the IDE will pick them up.
That way multiple projects can share the same settings (useful for formatting rules for example).
Any value defined here will override the pom.xml file value but is only applicable to the current project.
-->
<org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_j2eeVersion>1.6-web</org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_j2eeVersion>
<netbeans.hint.licensePath>${project.basedir}/../licenseheader.txt</netbeans.hint.licensePath>
<org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_deploy_2e_server>Tomcat</org-netbeans-modules-maven-j2ee.netbeans_2e_hint_2e_deploy_2e_server>
</properties>
</project-shared-configuration>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>drip</artifactId>
<groupId>nl.uva.sne.drip</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<groupId>nl.uva.sne.drip</groupId>
<artifactId>drip-api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>drip-api</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<skipTests>true</skipTests>
</properties>
<dependencies>
<dependency>
<groupId>nl.uva.sne.drip</groupId>
<artifactId>drip-commons</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.3.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.5.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.rabbitmq</groupId>
<artifactId>amqp-client</artifactId>
<version>4.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.8.0.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-rest-core</artifactId>
<version>2.5.6.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.6</version>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.2</version>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>com.webcohesion.enunciate</groupId>
<artifactId>enunciate-core-annotations</artifactId>
<version>2.9.1</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>nl.uva.sne.drip</groupId>
<artifactId>drip-planner2provisioner</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>4.3.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.jvnet.ws.wadl</groupId>
<artifactId>wadl-core</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>org.jvnet.ws.wadl</groupId>
<artifactId>wadl-client-plugin</artifactId>
<version>1.1.6</version>
</dependency>
<!-- <dependency>
<groupId>net.bull.javamelody</groupId>
<artifactId>javamelody-core</artifactId>
<version>1.71.0</version>
</dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>9</source>
<target>9</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>6.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<!-- <plugin>
<groupId>com.webcohesion.enunciate</groupId>
<artifactId>enunciate-maven-plugin</artifactId>
<version>2.9.1</version>
<executions>
<execution>
<id>assemble</id>
<goals>
<goal>assemble</goal>
<goal>docs</goal>
</goals>
<configuration>
<docsDir>${project.basedir}/../docs/apidocs</docsDir>
<configFile>enunciate.xml</configFile>
<sourcepath-includes>
<include>
configure Enunciate to look for the source jars for all dependencies groupId.
<groupId>nl.uva.sne.drip</groupId>
<artifactId>drip-commons</artifactId>
</include>
</sourcepath-includes>
</configuration>
</execution>
</executions>
</plugin>-->
<!-- <plugin>
<groupId>com.webcohesion.enunciate</groupId>
<artifactId>enunciate-maven-plugin</artifactId>
<version>2.8.1</version>
<executions>
<execution>
<goals>
<goal>docs</goal>
</goals>
<configuration>
<docsDir>${project.basedir}/../docs</docsDir>
<configFile>enunciate.xml</configFile>
</configuration>
</execution>
</executions>
</plugin>-->
</plugins>
</build>
</project>
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.auth;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.web.filter.GenericFilterBean;
/**
*
* @author S. Koulouzis
*/
public class AuthFilter extends GenericFilterBean {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.auth;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
import org.springframework.stereotype.Component;
/**
*
* @author S. Koulouzis
*/
@Component
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
throws IOException, ServletException {
// super.commence(request, response, authEx);
response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
PrintWriter writer = response.getWriter();
writer.println("HTTP Status 401 - " + authEx.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("DRIP");
super.afterPropertiesSet();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.auth;
import java.io.Serializable;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
/**
*
* @author S. Koulouzis
*/
public class PermissionEvaluatorImp implements PermissionEvaluator {
@Override
public boolean hasPermission(Authentication a, Object o, Object o1) {
if (!a.isAuthenticated()) {
return false;
}
if (!(a.getPrincipal() instanceof User)) {
return false;
} else {
User user = (User) a.getPrincipal();
return true;
}
// return false;
}
@Override
public boolean hasPermission(Authentication a, Serializable srlzbl, String string, Object o) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package nl.uva.sne.drip.api.conf;
import java.util.concurrent.Executor;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
/**
*
* @author S. Koulouzis
*/
@Configuration
@EnableScheduling
@EnableAsync
@ComponentScan("nl.uva.sne.drip")
public class AsyncConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(5);
scheduler.initialize();
return scheduler;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.conf;
import nl.uva.sne.drip.api.auth.PermissionEvaluatorImp;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration;
/**
*
* @author S. Koulouzis
*/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
DefaultMethodSecurityExpressionHandler expressionHandler
= new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(new PermissionEvaluatorImp());
return expressionHandler;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.conf;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
/**
*
* @author S. Koulouzis
*/
@Configuration
@EnableMongoRepositories(basePackages = "nl.uva.sne.drip.api")
@PropertySources({
@PropertySource(value = "classpath:drip.properties", ignoreResourceNotFound = true),
@PropertySource(value = "file:etc/drip.properties", ignoreResourceNotFound = true)
})
@ComponentScan("nl.uva.sne.drip")
public class MongoConfig extends AbstractMongoConfiguration {
@Value("${db.name}")
private String dbName;
@Value("${db.host}")
private String dbHost;
@Value("${db.username}")
private String dbUsername;
@Value("${db.password}")
private String dbPass;
// @Autowired
// private MongoDbFactory mongoFactory;
// @Autowired
// private MongoMappingContext mongoMappingContext;
@Override
protected String getDatabaseName() {
return dbName;
}
@Override
public Mongo mongo() throws Exception {
return new MongoClient(dbHost, 27017);
}
@Override
protected String getMappingBasePackage() {
return "nl.uva.sne.drip";
}
}
/*
* Copyright 2016 S. Koulouzis
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package nl.uva.sne.drip.api.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan("nl.uva.sne.drip")
//@PropertySource("classpath:drip.properties")
@PropertySources({
@PropertySource(value = "classpath:drip.properties", ignoreResourceNotFound = true),
@PropertySource(value = "file:etc/drip.properties", ignoreResourceNotFound = true)
})
@EnableWebMvc
public class MultipartConfig {
@Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
// resolver.setMaxInMemorySize(0);
//resolver.setMaxUploadSize(0);
//resolver.setMaxUploadSizePerFile(0);
return resolver;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.conf;
import nl.uva.sne.drip.api.auth.MyBasicAuthenticationEntryPoint;
import nl.uva.sne.drip.api.auth.AuthFilter;
import nl.uva.sne.drip.api.service.UserService;
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.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
/**
*
* @author S. Koulouzis
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true, prePostEnabled = true)
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
UserService userService;
@Autowired
private MyBasicAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/user/*").hasRole("USER")
.and()
.authorizeRequests()
.antMatchers("/manager/*").hasRole("ADMIN")
.and()
.authorizeRequests()
.antMatchers("/monitoring/*").hasRole("ADMIN")
.and()
.formLogin()
.and()
.httpBasic()
.authenticationEntryPoint(authenticationEntryPoint);
http.addFilterAfter(new AuthFilter(), BasicAuthenticationFilter.class);
}
@Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.conf;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
/*
* Copyright 2016 S. Koulouzis
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package nl.uva.sne.drip.api.conf;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MultipartConfig.class);
ctx.register(MongoConfig.class);
ctx.register(SecurityConfig.class);
ctx.register(AsyncConfig.class);
// ctx.register(MethodSecurityConfig.class);
ctx.setServletContext(servletContext);
DispatcherServlet dispatcher = new DispatcherServlet(ctx);
Dynamic dynamic = servletContext.addServlet("dispatcher", dispatcher);
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
dynamic.setAsyncSupported(true);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.ansible.AnsibleOutput;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface AnsibleOutputDao extends MongoRepository<AnsibleOutput, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.CloudCredentials;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface CloudCredentialsDao extends MongoRepository<CloudCredentials, String> {
// @Override
// CloudCredentials findOne(String id);
//
// @PreAuthorize(ALLOWED_FOR_ADMINISTRATOR)
// @Override
// void delete(String id);
//
// @PreAuthorize(ALLOWED_FOR_OWNER + " or " + ALLOWED_FOR_ADMINISTRATOR)
// @Override
// List<CloudCredentials> findAll();
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.ConfigurationRepresentation;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface ConfigurationDao extends MongoRepository<ConfigurationRepresentation, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.DeployResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.KeyValueHolder;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
/**
*
* @author S. Koulouzis
*/
public interface DeployDao extends MongoRepository<DeployResponse, String> {
@Query(value = "{'statusHistories':{$elemMatch:{'status':{$in:['PROCESSABLE']}}},'created' : { '$gt' : { '$date' : ':?0' } , '$lt' : { '$date' : ':?1'}}}", count = true)
public Iterable<KeyValueHolder> findByCommand(String cmd);
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.KeyPair;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface KeyPairDao extends MongoRepository<KeyPair, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.MonitorringMessage;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface MonitorringMessageDao extends MongoRepository<MonitorringMessage, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.PlanResponse;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface PlanDao extends MongoRepository<PlanResponse, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.ProvisionResponse;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface ProvisionResponseDao extends MongoRepository<ProvisionResponse, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.ToscaRepresentation;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface ToscaDao extends MongoRepository<ToscaRepresentation, String> {
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.dao;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
*
* @author S. Koulouzis
*/
public interface UserDao extends MongoRepository<User, String> {
public User findByUsername(String username);
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String massage) {
super(massage);
}
public BadRequestException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Cloud credentials not found")
public class CloudCredentialsNotFoundException extends RuntimeException {
public CloudCredentialsNotFoundException(String string) {
super(string);
}
public CloudCredentialsNotFoundException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
/**
*
* @author S. Koulouzis
*/
public class ExceptionHandler {
public static RuntimeException generateException(String name, String value) {
if (value == null) {
return new InternalServerErrorException();
}
if (value.contains("The maximum number of VPCs has been reached")) {
return new VMLimitException(name + "." + value);
} else {
return new InternalServerErrorException();
}
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public class InternalServerErrorException extends RuntimeException {
public InternalServerErrorException(String massage) {
super(massage);
}
public InternalServerErrorException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
/**
*
* @author S. Koulouzis
*/
public class KeyException extends Exception{
public KeyException(String message) {
super(message);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
public NotFoundException(String string) {
super(string);
}
public NotFoundException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Cloud provider name can't be null")
public class NullCloudProviderException extends RuntimeException {
public NullCloudProviderException(String string) {
super(string);
}
public NullCloudProviderException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Key can't be null")
public class NullKeyException extends RuntimeException {
public NullKeyException(String string) {
super(string);
}
public NullKeyException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "KeyId can't be null")
public class NullKeyIDException extends RuntimeException {
public NullKeyIDException(String string) {
super(string);
}
public NullKeyIDException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "User already exists")
public class PasswordNullException extends RuntimeException {
public PasswordNullException() {
super();
}
public PasswordNullException(String string) {
super(string);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Plan not found")
public class PlanNotFoundException extends RuntimeException {
public PlanNotFoundException(String string) {
super(string);
}
public PlanNotFoundException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class UnauthorizedExeption extends RuntimeException {
public UnauthorizedExeption(String string) {
super(string);
}
public UnauthorizedExeption() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "User already exists")
public class UserExistsException extends RuntimeException {
public UserExistsException() {
super();
}
public UserExistsException(String string) {
super(string);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "User not found")
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String string) {
super(string);
}
public UserNotFoundException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "User name can't be null")
public class UserNullException extends RuntimeException {
public UserNullException(String massage) {
super(massage);
}
public UserNullException() {
super();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.exception;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*
* @author S. Koulouzis
*/
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "The maximum number of VMs has been reached")
public class VMLimitException extends RuntimeException {
public VMLimitException(String string) {
super(string);
}
public VMLimitException() {
super();
}
}
package nl.uva.sne.drip.api.rpc;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.uva.sne.drip.drip.commons.data.internal.Message;
import nl.uva.sne.drip.commons.utils.Converter;
import org.json.JSONException;
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
*
* @author S. Koulouzis
*/
public abstract class DRIPCaller implements AutoCloseable {
private final Connection connection;
private final Channel channel;
private final String replyQueueName;
private final String requestQeueName;
private final ObjectMapper mapper;
public DRIPCaller(String messageBrokerHost, String requestQeueName) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(messageBrokerHost);
factory.setPort(AMQP.PROTOCOL.PORT);
//factory.setUsername("guest");
//factory.setPassword("pass");
connection = factory.newConnection();
channel = connection.createChannel();
// create a single callback queue per client not per requests.
replyQueueName = channel.queueDeclare().getQueue();
this.requestQeueName = requestQeueName;
this.mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
}
/**
* @return the connection
*/
public Connection getConnection() {
return connection;
}
/**
* @return the channel
*/
public Channel getChannel() {
return channel;
}
/**
* @return the replyQueueName
*/
public String getReplyQueueName() {
return replyQueueName;
}
@Override
public void close() throws IOException, TimeoutException {
if (channel != null && channel.isOpen()) {
channel.close();
}
if (connection != null && connection.isOpen()) {
connection.close();
}
}
public Message call(Message r) throws IOException, TimeoutException, InterruptedException, JSONException {
String jsonInString = mapper.writeValueAsString(r);
//Build a correlation ID to distinguish responds
final String corrId = UUID.randomUUID().toString();
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder()
.correlationId(corrId)
.replyTo(getReplyQueueName())
.build();
Logger.getLogger(DRIPCaller.class.getName()).log(Level.INFO, "Sending: {0} to queue: {1}", new Object[]{jsonInString, requestQeueName});
getChannel().basicPublish("", requestQeueName, props, jsonInString.getBytes("UTF-8"));
final BlockingQueue<String> response = new ArrayBlockingQueue(1);
getChannel().basicConsume(getReplyQueueName(), true, new DefaultConsumer(getChannel()) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
if (properties.getCorrelationId().equals(corrId)) {
response.offer(new String(body, "UTF-8"));
}
}
});
String resp = response.take();
String clean = resp;
if (resp.contains("'null'")) {
clean = resp.replaceAll("'null'", "null").replaceAll("\'", "\"").replaceAll(" ", "");
}
if (clean.contains("\"value\":{\"")) {
return Converter.string2Message(clean);
}
if (clean.contains("\"null\"")) {
clean = clean.replaceAll("\"null\"", "null");
}
Logger.getLogger(DRIPCaller.class.getName()).log(Level.INFO, "Got: {0}", clean);
return mapper.readValue(clean, Message.class);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.rpc;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* @author S. Koulouzis
*/
public class DeployerCaller extends DRIPCaller {
private static final String REQUEST_QUEUE_NAME = "deployer_queue";
public DeployerCaller(String messageBrokerHost) throws IOException, TimeoutException {
super(messageBrokerHost, REQUEST_QUEUE_NAME);
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.rpc;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* @author S. Koulouzis.
*/
public class PlannerCaller extends DRIPCaller {
private static final String REQUEST_QUEUE_NAME = "planner";
public PlannerCaller(String messageBrokerHost) throws IOException, TimeoutException {
super(messageBrokerHost, REQUEST_QUEUE_NAME);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.rpc;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* @author S. Koulouzis
*/
public class ProvisionerCaller0 extends DRIPCaller {
private static final String REQUEST_QUEUE_NAME = "provisioner_queue_v0";
public ProvisionerCaller0(String messageBrokerHost) throws IOException, TimeoutException {
super(messageBrokerHost, REQUEST_QUEUE_NAME);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.rpc;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* @author S. Koulouzis
*/
public class ProvisionerCaller1 extends DRIPCaller {
private static final String REQUEST_QUEUE_NAME = "provisioner_queue_v1";
public ProvisionerCaller1(String messageBrokerHost) throws IOException, TimeoutException {
super(messageBrokerHost, REQUEST_QUEUE_NAME);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.rpc;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
/**
*
* @author S. Koulouzis
*/
public class TransformerCaller extends DRIPCaller {
private static final String REQUEST_QUEUE_NAME = "tosca_2_docker_compose_queue";
public TransformerCaller(String messageBrokerHost) throws IOException, TimeoutException {
super(messageBrokerHost, REQUEST_QUEUE_NAME);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import nl.uva.sne.drip.api.dao.AnsibleOutputDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.drip.commons.data.v1.external.KeyValueHolder;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import nl.uva.sne.drip.drip.commons.data.v1.external.ansible.AnsibleOutput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class AnsibleOutputService {
@Autowired
private AnsibleOutputDao ansibleOutputDao;
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public AnsibleOutput findOne(String id) {
AnsibleOutput ansibleOut = ansibleOutputDao.findOne(id);
if (ansibleOut == null) {
throw new NotFoundException();
}
return ansibleOut;
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<AnsibleOutput> findAll() {
return ansibleOutputDao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public AnsibleOutput delete(String id) {
AnsibleOutput ansibleOut = ansibleOutputDao.findOne(id);
if (ansibleOut == null) {
throw new NotFoundException();
}
ansibleOutputDao.delete(ansibleOut);
return ansibleOut;
}
public AnsibleOutput save(AnsibleOutput ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return ansibleOutputDao.save(ownedObject);
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
ansibleOutputDao.deleteAll();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.util.List;
import nl.uva.sne.drip.api.dao.CloudCredentialsDao;
import nl.uva.sne.drip.api.exception.CloudCredentialsNotFoundException;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.drip.commons.data.v1.external.CloudCredentials;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class CloudCredentialsService {
@Autowired
private CloudCredentialsDao dao;
public CloudCredentials save(CloudCredentials ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return dao.save(ownedObject);
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public CloudCredentials findOne(String id) {
CloudCredentials creds = dao.findOne(id);
if (creds == null) {
throw new CloudCredentialsNotFoundException();
}
return creds;
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public CloudCredentials delete(String id) {
CloudCredentials creds = dao.findOne(id);
if (creds == null) {
throw new NotFoundException();
}
dao.delete(creds);
return creds;
}
// @PreAuthorize(" (hasRole('ROLE_ADMIN')) or (hasRole('ROLE_USER'))")
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
// @PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')")
public List<CloudCredentials> findAll() {
return dao.findAll();
}
@PostFilter("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
dao.deleteAll();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.drip.commons.data.v1.external.ConfigurationRepresentation;
import nl.uva.sne.drip.commons.utils.Converter;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import nl.uva.sne.drip.api.dao.ConfigurationDao;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class ConfigurationService {
@Autowired
private ConfigurationDao dao;
public String get(String id, String fromat) throws JSONException, NotFoundException {
ConfigurationRepresentation configuration = findOne(id);
if (configuration == null) {
throw new NotFoundException();
}
Map<String, Object> map = configuration.getKeyValue();
if (fromat != null && fromat.toLowerCase().equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = cleanup(ymlStr);
return ymlStr;
}
if (fromat != null && fromat.toLowerCase().equals("json")) {
String jsonStr = Converter.map2JsonString(map);
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
ymlStr = cleanup(ymlStr);
return ymlStr;
}
public String saveFile(MultipartFile file) throws IOException {
String originalFileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
String str = new String(bytes, "UTF-8");
return saveStringContents(str);
}
public String saveYamlString(String yamlString, String name) throws IOException {
yamlString = yamlString.replaceAll("\\.", "\uff0E");
Map<String, Object> map = Converter.ymlString2Map(yamlString);
ConfigurationRepresentation t = new ConfigurationRepresentation();
t.setKvMap(map);
save(t);
return t.getId();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public ConfigurationRepresentation delete(String id) {
ConfigurationRepresentation tr = dao.findOne(id);
if (tr == null) {
throw new NotFoundException();
}
dao.delete(tr);
return tr;
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<ConfigurationRepresentation> findAll() {
return dao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public ConfigurationRepresentation findOne(String id) {
return dao.findOne(id);
}
private ConfigurationRepresentation save(ConfigurationRepresentation ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return dao.save(ownedObject);
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
dao.deleteAll();
}
public String saveStringContents(String yamlContents) throws IOException {
Map<String, Object> map = Converter.cleanStringContents(yamlContents, false);
ConfigurationRepresentation t = new ConfigurationRepresentation();
t.setKvMap(map);
save(t);
return t.getId();
}
private String cleanup(String ymlStr) {
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
ymlStr = ymlStr.replaceAll("\'---':", "---");
Pattern p = Pattern.compile("version:.*");
Matcher match = p.matcher(ymlStr);
while (match.find()) {
String line = match.group();
if (!line.contains("\"") && !line.contains("'")) {
String number = line.split(": ")[1];
ymlStr = ymlStr.replaceAll("version: " + number, "version: " + "\'" + number + "\'");
}
}
p = Pattern.compile("cpus:.*,");
match = p.matcher(ymlStr);
while (match.find()) {
String line = match.group();
if (!line.contains("\"") || line.contains("'")) {
String cpusNum = line.split(":")[1];
cpusNum = cpusNum.replaceAll(",", "").trim();
ymlStr = ymlStr.replaceAll("cpus: " + cpusNum, "cpus: " + '\'' + cpusNum + '\'');
}
}
p = Pattern.compile("memory:.*");
match = p.matcher(ymlStr);
while (match.find()) {
String line = match.group();
if (!line.contains("\"") && !line.contains("'")) {
String memory = line.split(":")[1];
memory = memory.replaceAll("}", "").trim();
ymlStr = ymlStr.replaceAll("memory: " + memory, "memory: " + '\'' + memory + '\'');
}
}
return ymlStr.replaceAll("'''", "'");
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.GetResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
import nl.uva.sne.drip.drip.commons.data.v1.external.DRIPLogRecord;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class DRIPLogService {
@Value("${message.broker.host}")
private String messageBrokerHost;
private final String qeueName = "log_qeue";
private ObjectMapper mapper;
private ConnectionFactory factory;
public List<DRIPLogRecord> get() throws IOException, TimeoutException {
Channel channel = null;
if (factory == null) {
this.factory = new ConnectionFactory();
factory.setHost(messageBrokerHost);
factory.setPort(AMQP.PROTOCOL.PORT);
}
if (this.mapper == null) {
this.mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
}
try (Connection connection = factory.newConnection()) {
channel = connection.createChannel();
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
String qeueNameUser = qeueName + "_" + owner;
channel.queueDeclare(qeueNameUser, true, false, false, null);
GetResponse response = channel.basicGet(qeueNameUser, true);
List<DRIPLogRecord> logs = new ArrayList<>();
while (response != null) {
String message = new String(response.getBody(), "UTF-8");
response = channel.basicGet(qeueNameUser, true);
logs.add(mapper.readValue(message, DRIPLogRecord.class));
}
return logs;
}
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.uva.sne.drip.api.dao.DeployDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.rpc.DRIPCaller;
import nl.uva.sne.drip.api.rpc.DeployerCaller;
import nl.uva.sne.drip.api.v1.rest.DeployController;
import nl.uva.sne.drip.drip.commons.data.v1.external.DeployRequest;
import nl.uva.sne.drip.drip.commons.data.v1.external.DeployResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.Key;
import nl.uva.sne.drip.drip.commons.data.internal.Message;
import nl.uva.sne.drip.drip.commons.data.internal.MessageParameter;
import nl.uva.sne.drip.drip.commons.data.v1.external.ProvisionResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import nl.uva.sne.drip.api.dao.KeyPairDao;
import nl.uva.sne.drip.api.exception.KeyException;
import nl.uva.sne.drip.commons.utils.Converter;
import nl.uva.sne.drip.commons.utils.DRIPLogHandler;
import nl.uva.sne.drip.commons.utils.TOSCAUtils;
import nl.uva.sne.drip.drip.commons.data.v1.external.KeyPair;
import nl.uva.sne.drip.drip.commons.data.v1.external.ScaleRequest;
import nl.uva.sne.drip.drip.commons.data.v1.external.ansible.AnsibleOutput;
import nl.uva.sne.drip.drip.commons.data.v1.external.ansible.BenchmarkResult;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class DeployService {
@Autowired
private DeployDao deployDao;
@Autowired
private AnsibleOutputService ansibleOutputService;
@Autowired
KeyPairDao keyDao;
@Value("${message.broker.host}")
private String messageBrokerHost;
@Autowired
private ProvisionService provisionService;
private static final String[] CLOUD_SITE_NAMES = new String[]{"domain", "VMResourceID"};
private static final String[] PUBLIC_ADRESS_NAMES = new String[]{"public_address", "publicAddress"};
private final Logger logger;
@Autowired
public DeployService(@Value("${message.broker.host}") String messageBrokerHost) throws IOException, TimeoutException {
logger = Logger.getLogger(DeployService.class.getName());
logger.addHandler(new DRIPLogHandler(messageBrokerHost));
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public DeployResponse findOne(String id) throws JSONException, IOException, TimeoutException, InterruptedException {
DeployResponse deployDescription = deployDao.findOne(id);
if (deployDescription == null) {
throw new NotFoundException();
}
return deployDescription;
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<DeployResponse> findAll() {
return deployDao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public DeployResponse delete(String id) {
DeployResponse creds = deployDao.findOne(id);
if (creds == null) {
throw new NotFoundException();
}
deployDao.delete(creds);
return creds;
}
public DeployResponse save(DeployResponse ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return deployDao.save(ownedObject);
}
public DeployResponse deploySoftware(DeployRequest deployInfo) throws Exception {
try (DRIPCaller deployer = new DeployerCaller(messageBrokerHost);) {
Message deployerInvokationMessage = buildDeployerMessages(
deployInfo,
null,
null).get(0);
;
deployerInvokationMessage.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
logger.info("Calling deployer");
Message response = (deployer.call(deployerInvokationMessage));
logger.info("Got response from deployer");
List<MessageParameter> params = response.getParameters();
DeployResponse deploy = handleResponse(params, deployInfo);
deploy.setProvisionID(deployInfo.getProvisionID());
// deploy.setConfigurationID(deployInfo.getConfigurationID());
// deploy.setManagerType(deployInfo.getManagerType().toLowerCase());
logger.info("Deployment saved");
save(deploy);
return deploy;
} catch (IOException | TimeoutException | JSONException | InterruptedException ex) {
Logger.getLogger(DeployController.class.getName()).log(Level.SEVERE, null, ex);
} catch (KeyException ex) {
Logger.getLogger(DeployService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public Map<String, Object> getSwarmInfo(DeployResponse deployResp) throws JSONException, IOException, TimeoutException, InterruptedException {
// deployResp.setManagerType("swarm_info");
// Message deployerInvokationMessage = buildDeployerMessages(
// deployResp,
// null,
// null).get(0);
// Map<String, Object> info;
// deployerInvokationMessage.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
// try (DRIPCaller deployer = new DeployerCaller(messageBrokerHost);) {
// logger.info("Calling deployer");
// Message response = (deployer.call(deployerInvokationMessage));
// logger.info("Got response from deployer");
// List<MessageParameter> params = response.getParameters();
// info = buildSwarmInfo(params);
// }
return null;
}
private List<Message> buildDeployerMessages(
DeployRequest deployInfo,
String serviceName,
Integer numOfContainers) throws JSONException {
String provisionID = deployInfo.getProvisionID();
ProvisionResponse pro = provisionService.findOne(provisionID);
if (pro == null) {
throw new NotFoundException();
}
List<Message> messages = new ArrayList<>();
List<MessageParameter> parameters = new ArrayList<>();
Map<String, Object> toscaProvisonMap = pro.getKeyValue();
List<String> vmNames = TOSCAUtils.getVMsNodeNamesFromTopology(toscaProvisonMap);
for (String name : vmNames) {
Map<String, String> outputs = TOSCAUtils.getOutputsForNode(toscaProvisonMap, name);
MessageParameter messageParameter = createCredentialPartameter(outputs);
parameters.add(messageParameter);
}
MessageParameter managerTypeParameter = createManagerTypeParameter("kubernetes");
parameters.add(managerTypeParameter);
List<Map<String, Object>> k8sFiles = TOSCAUtils.tosca2KubernetesDeployment(toscaProvisonMap);
int count = 0;
for (Map<String, Object> map : k8sFiles) {
String deploymentEncoded = new String(Base64.getEncoder().encode(Converter.map2YmlString(map).getBytes()));
MessageParameter confParam = createConfigurationParameter(deploymentEncoded, "k8s_deploymet" + count);
parameters.add(confParam);
count++;
}
k8sFiles = TOSCAUtils.tosca2KubernetesService(toscaProvisonMap);
count = 0;
for (Map<String, Object> map : k8sFiles) {
String deploymentEncoded = new String(Base64.getEncoder().encode(Converter.map2YmlString(map).getBytes()));
MessageParameter confParam = createConfigurationParameter(deploymentEncoded, "k8s_service" + count);
parameters.add(confParam);
count++;
}
Message deployInvokationMessage = new Message();
deployInvokationMessage.setParameters(parameters);
deployInvokationMessage.setCreationDate(System.currentTimeMillis());
messages.add(deployInvokationMessage);
return messages;
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
deployDao.deleteAll();
}
private MessageParameter createCredentialPartameter(Map<String, String> outputs) {
MessageParameter messageParameter = new MessageParameter();
messageParameter.setName("credential");
messageParameter.setEncoding("UTF-8");
// This key is configured on all vms fo the 'user_name'
messageParameter.setValue(outputs.get("private_user_key"));
Map<String, String> attributes = new HashMap<>();
attributes.put("IP", outputs.get("ip"));
attributes.put("role", outputs.get("role"));
attributes.put("user", outputs.get("user_name"));
messageParameter.setAttributes(attributes);
return messageParameter;
}
private MessageParameter createManagerTypeParameter(String managerType) {
MessageParameter managerTypeParameter = new MessageParameter();
managerTypeParameter.setName("cluster");
managerTypeParameter.setEncoding("UTF-8");
managerTypeParameter.setValue(managerType);
return managerTypeParameter;
}
private MessageParameter createAnsibleParameter(String configurationID) throws JSONException {
return createConfigurationParameter(configurationID, "ansible");
}
private MessageParameter createComposerParameter(String configurationID, Map<String, String> dockerLogin) throws JSONException {
MessageParameter configurationParameter = createConfigurationParameter(configurationID, "composer");
Map<String, String> attributes = new HashMap<>();
attributes.put("name", configurationID);
if (dockerLogin != null) {
attributes.put("docker_login_username", dockerLogin.get("username"));
attributes.put("docker_login_password", dockerLogin.get("password"));
attributes.put("docker_login_registry", dockerLogin.get("registry"));
}
configurationParameter.setAttributes(attributes);
return configurationParameter;
}
private MessageParameter createConfigurationParameter(String configuration, String confType) throws JSONException {
MessageParameter configurationParameter = new MessageParameter();
if (confType.equals("ansible")) {
configurationParameter.setName("playbook");
} else if (confType.equals("kubernetes")) {
configurationParameter.setName("deployment");
} else {
configurationParameter.setName(confType);
}
configurationParameter.setEncoding("UTF-8");
configurationParameter.setValue(configuration);
return configurationParameter;
}
private MessageParameter createScaleParameter(String configurationID, String serviceName, int numOfContainers) throws JSONException {
MessageParameter scaleParameter = new MessageParameter();
scaleParameter.setName("scale");
scaleParameter.setEncoding("UTF-8");
scaleParameter.setValue(configurationID);
Map<String, String> attributes = new HashMap<>();
attributes.put("service", serviceName);
attributes.put("number_of_containers", String.valueOf(numOfContainers));
scaleParameter.setAttributes(attributes);
return scaleParameter;
}
private MessageParameter createSwarmInforparameter(String configurationID, String serviceName) {
MessageParameter swarmInfoParameter = new MessageParameter();
swarmInfoParameter.setName("swarm_info");
swarmInfoParameter.setEncoding("UTF-8");
Map<String, String> attributes = new HashMap<>();
attributes.put("service", serviceName);
attributes.put("name", configurationID);
swarmInfoParameter.setAttributes(attributes);
return swarmInfoParameter;
}
public DeployResponse scale(ScaleRequest scaleReq) throws IOException, TimeoutException, InterruptedException, JSONException, Exception {
// //Deployer needs configurationID -> name_of_deployment
// String deployId = scaleReq.getScaleTargetID();
// DeployResponse deployment = this.findOne(deployId);
// String confID = deployment.getConfigurationID();
// ConfigurationRepresentation configuration = configurationService.findOne(confID);
// Map<String, Object> map = configuration.getKeyValue();
// Map<String, Object> services = (Map<String, Object>) map.get("services");
// if (!services.containsKey(scaleReq.getScaleTargetName())) {
// throw new BadRequestException("Service name does not exist in this deployment");
// }
//
// deployment.setManagerType("scale");
// Message message = buildDeployerMessages(deployment,
// scaleReq.getScaleTargetName(),
// scaleReq.getNumOfInstances()).get(0);
//
// message.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
// try (DRIPCaller deployer = new DeployerCaller(messageBrokerHost);) {
// logger.info("Calling deployer");
// Message response = (deployer.call(message));
// logger.info("Got response from deployer");
// List<MessageParameter> params = response.getParameters();
// handleResponse(params, null);
// }
// deployment.setScale(scaleReq);
// deployment.setManagerType("swarm");
// save(deployment);
return null;
}
private DeployResponse handleResponse(List<MessageParameter> params, DeployRequest deployInfo) throws KeyException, IOException, Exception {
DeployResponse deployResponse = new DeployResponse();
deployResponse.setProvisionID(deployInfo.getProvisionID());
deployResponse.setKvMap(provisionService.findOne(deployInfo.getProvisionID()).getKeyValue());
for (MessageParameter p : params) {
String name = p.getName();
if (name.equals("credential")) {
String value = p.getValue();
Key k = new Key();
k.setKey(value);
k.setType(Key.KeyType.PRIVATE);
KeyPair pair = new KeyPair();
pair.setPrivateKey(k);
// deployResponse.setKey(pair);
save(deployResponse);
return deployResponse;
}
if (name.equals("ansible_output")) {
setAnsibleOutput(p, deployInfo);
}
if (name.equals("kubectl_get")) {
String decoded = new String(Base64.getDecoder().decode(p.getValue().getBytes()));
Map<String, Object> kubectlGetOutput = Converter.jsonString2Map(decoded);
Map<String, Object> outputs = new HashMap<>();
List<Map<String, Object>> items = (List<Map<String, Object>>) kubectlGetOutput.get("items");
for (Map<String, Object> entry : items) {
String serviceName = (String) ((Map<String, Object>) entry.get("metadata")).get("name");
List<Map<String, Object>> ports = (List<Map<String, Object>>) ((Map<String, Object>) entry.get("spec")).get("ports");
for (Map<String, Object> port : ports) {
Set<String> keys = port.keySet();
for (String key : keys) {
if (port.get(key) instanceof Integer) {
outputs = TOSCAUtils.buildTOSCAOutput(outputs, serviceName, String.valueOf((Integer) port.get(key)), key, false);
} else {
outputs = TOSCAUtils.buildTOSCAOutput(outputs, serviceName, (String) port.get(key), key, false);
}
}
}
}
Map<String, Object> tosca = provisionService.findOne(deployInfo.getProvisionID()).getKeyValue();
Map<String, Object> topologyTemplate = (Map<String, Object>) ((Map<String, Object>) tosca.get("topology_template"));
topologyTemplate.put("outputs", outputs);
deployResponse.setKvMap(tosca);
}
}
return deployResponse;
}
private BenchmarkResult parseSaveBenchmarkResult(AnsibleOutput ansOut) {
return null;
}
private String parseValue(String value) throws JSONException {
JSONArray ja = new JSONArray(value);
JSONArray newJa = new JSONArray();
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = ja.getJSONObject(i);
JSONObject result = ((JSONObject) jo.get("result"));
if (result.has("msg")) {
String msg;
try {
msg = (String) result.get("msg");
} catch (java.lang.ClassCastException ex) {
JSONObject message = (JSONObject) result.get("msg");
msg = Converter.jsonObject2String(message.toString());
result.put("msg", msg);
jo.put("result", result);
}
}
if (result.has("invocation")) {
JSONObject invocation = ((JSONObject) (result).get("invocation"));
if (invocation.has("module_args")) {
JSONObject module_args = (JSONObject) invocation.get("module_args");
if (module_args.has("msg")) {
String msg;
try {
msg = (String) module_args.get("msg");
} catch (java.lang.ClassCastException ex) {
JSONObject message = (JSONObject) module_args.get("msg");
msg = Converter.jsonObject2String(message.toString());
module_args.put("msg", msg);
invocation.put("module_args", module_args);
}
}
}
if (invocation.has("msg")) {
String msg;
try {
msg = (String) invocation.get("msg");
} catch (java.lang.ClassCastException ex) {
JSONObject message = (JSONObject) invocation.get("msg");
msg = Converter.jsonObject2String(message.toString());
invocation.put("msg", msg);
result.put("invocation", invocation);
}
}
}
newJa.put(jo);
}
return newJa.toString();
}
private Map<String, Object> buildSwarmInfo(List<MessageParameter> params) throws JSONException, IOException {
Map<String, Object> info = new HashMap();
for (MessageParameter param : params) {
String jsonResp = param.getValue().replaceAll("^\"|\"$", "");
Map<String, Object> kv = Converter.jsonString2Map(jsonResp);
info.putAll(kv);
}
return info;
}
public List<String> getServiceNames(String id) throws JSONException, IOException, TimeoutException, InterruptedException {
DeployResponse resp = findOne(id);
// if (resp.getManagerType().equals("swarm")) {
// Map<String, Object> swarmInfo = getSwarmInfo(resp);
//
// List< Map<String, Object>> stackInfo = (List) swarmInfo.get("stack_info");
// List<String> serviceNames = new ArrayList<>();
// for (Map<String, Object> map : stackInfo) {
// if (map.containsKey("name")) {
// serviceNames.add(((String) map.get("name")));
// }
// }
// return serviceNames;
// }
return null;
}
public DeployResponse getContainersStatus(String id, String serviceName) throws JSONException, IOException, TimeoutException, InterruptedException {
DeployResponse resp = findOne(id);
Map<String, Object> result = new HashMap<>();
// if (resp.getManagerType().equals("swarm")) {
// Map<String, Object> swarmInfo = getSwarmInfo(resp);
//
// List< Map<String, Object>> servicesInfo = (List) swarmInfo.get("services_info");
// List<String> taskIDs = new ArrayList<>();
// for (Map<String, Object> map : servicesInfo) {
// if (map.containsKey("name") && ((String) map.get("name")).startsWith(serviceName)) {
// taskIDs.add(((String) map.get("ID")));
// }
// }
// List< Map<String, Object>> inspecInfo = (List) swarmInfo.get("inspect_info");
// List< Map<String, Object>> inspecInfoResult = new ArrayList<>();
// for (String taskID : taskIDs) {
// for (Map<String, Object> map : inspecInfo) {
// if (map.containsKey("ID") && ((String) map.get("ID")).startsWith(taskID)) {
// inspecInfoResult.add((Map<String, Object>) map.get("Status"));
// }
// }
// }
// result.put("inspect_info", inspecInfoResult);
// resp.setManagerInfo(result);
// resp.setKey(null);
// resp.setScale(null);
// }
return resp;
}
// private Map<String, String> getDockerLogin(ProvisionResponse pro) {
// String planID = pro.getPlanID();
// PlanResponse plan = plannerService.findOne(planID);
// String toscaID = plan.getToscaID();
// if (toscaID != null) {
// ToscaRepresentation tosca = toscaService.findOne(plan.getToscaID());
// Map<String, Object> map = tosca.getKeyValue();
// map.get("repositories");
// HashMap dockerLogin = new HashMap();
// return dockerLogin;
// }
// return null;
// }
public String get(String id, String format) throws JSONException, IOException, TimeoutException, InterruptedException {
DeployResponse deploy = findOne(id);
Map<String, Object> map = deploy.getKeyValue();
if (format != null && format.equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
if (format != null && format.equals("json")) {
String jsonStr = Converter.map2JsonString(map);
jsonStr = jsonStr.replaceAll("\\uff0E", ".");
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
private void setAnsibleOutput(MessageParameter p, DeployRequest deployInfo) throws JSONException, IOException {
String value = p.getValue();
value = p.getValue();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
value = parseValue(value);
List<AnsibleOutput> outputList = mapper.readValue(value, new TypeReference<List<AnsibleOutput>>() {
});
List<String> outputListIds = new ArrayList<>();
Map<String, String> nodeTypeCache = new HashMap<>();
Map<String, String> domainCache = new HashMap<>();
Map<String, String> osTypeCache = new HashMap<>();
for (AnsibleOutput ansOut : outputList) {
Map<String, Object> map = provisionService.findOne(deployInfo.getProvisionID()).getKeyValue();
String nodeType = nodeTypeCache.get(ansOut.getHost());
String domain = domainCache.get(ansOut.getHost());
String os = osTypeCache.get(ansOut.getHost());
if (nodeType == null) {
List<Map<String, Object>> components = null;
List<Map<String, Object>> topologies = null;
if (map.containsKey("components")) {
components = (List<Map<String, Object>>) map.get("components");
// topologies = (List<Map<String, Object>>) map.get("topologies");
} else {
for (String key : map.keySet()) {
Map<String, Object> subMap = (Map<String, Object>) map.get(key);
if (subMap.containsKey("components") && components == null) {
components = (List<Map<String, Object>>) subMap.get("components");
}
if (subMap.containsKey("topologies") && topologies == null) {
topologies = (List<Map<String, Object>>) subMap.get("topologies");
}
if (components != null && topologies != null) {
break;
}
}
}
for (Map<String, Object> component : components) {
String publicAddress = null;
for (String addressName : PUBLIC_ADRESS_NAMES) {
if (component.containsKey(addressName)) {
publicAddress = (String) component.get(addressName);
break;
}
}
if (publicAddress != null && publicAddress.equals(ansOut.getHost())) {
nodeType = (String) component.get("nodeType");
for (String siteName : CLOUD_SITE_NAMES) {
if (component.containsKey(siteName)) {
domain = (String) component.get(siteName);
break;
}
}
os = (String) component.get("OStype");
nodeTypeCache.put(ansOut.getHost(), nodeType);
domainCache.put(ansOut.getHost(), domain);
osTypeCache.put(ansOut.getHost(), os);
break;
}
}
}
ansOut.setVmType(nodeType);
ansOut.setCloudDeploymentDomain(domain);
ansOut.setProvisionID(deployInfo.getProvisionID());
// ansOut.setCloudProvider(provider);
ansOut = ansibleOutputService.save(ansOut);
BenchmarkResult benchmarkResult = parseSaveBenchmarkResult(ansOut);
outputListIds.add(ansOut.getId());
}
// deployResponse.setAnsibleOutputList(outputListIds);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.util.List;
import nl.uva.sne.drip.api.dao.MonitorringMessageDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.drip.commons.data.v1.external.MonitorringMessage;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class MonitorringMessageService {
@Autowired
private MonitorringMessageDao dao;
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public MonitorringMessage delete(String id) {
MonitorringMessage tr = dao.findOne(id);
if (tr == null) {
throw new NotFoundException();
}
dao.delete(tr);
return tr;
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<MonitorringMessage> findAll() {
return dao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public MonitorringMessage findOne(String id) {
return dao.findOne(id);
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
dao.deleteAll();
}
public MonitorringMessage save(MonitorringMessage ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return dao.save(ownedObject);
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import nl.uva.sne.drip.commons.utils.DRIPLogHandler;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.uva.sne.drip.api.dao.PlanDao;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.rpc.DRIPCaller;
import nl.uva.sne.drip.api.rpc.PlannerCaller;
import nl.uva.sne.drip.drip.commons.data.internal.Message;
import nl.uva.sne.drip.drip.commons.data.internal.MessageParameter;
import nl.uva.sne.drip.drip.commons.data.v1.external.PlanResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.ToscaRepresentation;
import nl.uva.sne.drip.commons.utils.Converter;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.util.Base64;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class PlannerService {
@Autowired
private ToscaService toscaService;
@Autowired
private PlanDao planDao;
@Value("${message.broker.host}")
private String messageBrokerHost;
private final Logger logger;
@Autowired
public PlannerService(@Value("${message.broker.host}") String messageBrokerHost) throws IOException, TimeoutException {
logger = Logger.getLogger(PlannerService.class.getName());
logger.addHandler(new DRIPLogHandler(messageBrokerHost));
}
public PlanResponse getPlan(String toscaId, String cloudProvider, Integer maxVM) throws JSONException, UnsupportedEncodingException, IOException, TimeoutException, InterruptedException {
try (DRIPCaller planner = new PlannerCaller(messageBrokerHost)) {
Message plannerInvokationMessage = buildPlannerMessage(toscaId, maxVM);
logger.log(Level.INFO, "Calling planner");
plannerInvokationMessage.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
Message plannerReturnedMessage = (planner.call(plannerInvokationMessage));
logger.log(Level.INFO, "Got response from planner");
ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
List<MessageParameter> messageParams = plannerReturnedMessage.getParameters();
String toscaPlan = null;
for (MessageParameter mp : messageParams) {
String value = mp.getValue();
toscaPlan = new String(Base64.getDecoder().decode(value));
logger.log(Level.INFO, "TOSCA Plann: {0}", toscaPlan);
}
Map<String, Object> toscaPlanMap = Converter.ymlString2Map(toscaPlan);
// SimplePlanContainer simplePlan = P2PConverter.transfer(toscaPlanMap, null, null, null);
PlanResponse planResponse = new PlanResponse();
planResponse.setToscaID(toscaId);
planResponse.setKvMap(toscaPlanMap);
save(planResponse);
logger.log(Level.INFO, "Plan saved");
return planResponse;
}
}
private Message buildPlannerMessage(String toscaId, Integer maxVM) throws JSONException, UnsupportedEncodingException {
ToscaRepresentation toscaRepresentation = toscaService.findOne(toscaId);
if (toscaRepresentation == null) {
throw new BadRequestException();
}
logger.log(Level.INFO, "Building invokation message for planner");
Map<String, Object> map = toscaRepresentation.getKeyValue();
String json = Converter.map2JsonString(map);
json = json.replaceAll("\\uff0E", ".");
byte[] bytes = json.getBytes();
Message invokationMessage = new Message();
List parameters = new ArrayList();
MessageParameter jsonArgument = new MessageParameter();
String charset = "UTF-8";
jsonArgument.setValue(new String(bytes, charset));
jsonArgument.setEncoding(charset);
jsonArgument.setName("tosca_input");
parameters.add(jsonArgument);
if (maxVM != null) {
MessageParameter maxVMsArgument = new MessageParameter();
maxVMsArgument.setValue(String.valueOf(maxVM));
maxVMsArgument.setEncoding(charset);
maxVMsArgument.setName("max_vm");
parameters.add(maxVMsArgument);
}
invokationMessage.setParameters(parameters);
invokationMessage.setCreationDate((System.currentTimeMillis()));
return invokationMessage;
}
public String get(String id, String fromat) throws JSONException {
PlanResponse plan = findOne(id);
if (plan == null) {
throw new NotFoundException();
}
Map<String, Object> map = plan.getKeyValue();
if (fromat != null && fromat.equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
if (fromat != null && fromat.equals("json")) {
String jsonStr = Converter.map2JsonString(map);
jsonStr = jsonStr.replaceAll("\\uff0E", ".");
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
public String getToscaID(String id) {
return findOne(id).getToscaID();
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<PlanResponse> findAll() {
List<PlanResponse> all = planDao.findAll();
return all;
}
public PlanResponse save(PlanResponse ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return planDao.save(ownedObject);
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public PlanResponse findOne(String id) {
PlanResponse plan = planDao.findOne(id);
if (plan == null) {
throw new NotFoundException();
}
return plan;
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public PlanResponse delete(String id) {
PlanResponse plan = planDao.findOne(id);
if (plan == null) {
throw new NotFoundException();
}
planDao.delete(plan);
return plan;
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
planDao.deleteAll();
}
public String saveStringContents(String ymlContents, Integer level, String name) {
Map<String, Object> map = Converter.cleanStringContents(ymlContents, true);
PlanResponse pr = new PlanResponse();
pr.setKvMap(map);
save(pr);
return pr.getId();
}
public boolean verify(String ymlContents) {
Map<String, Object> map = Converter.cleanStringContents(ymlContents, true);
ArrayList<Map> topologies = topologies = (ArrayList) map.get("topologies");
ArrayList<String> topologyNames = new ArrayList();
for (Map<String, Object> m : topologies) {
String topology = (String) m.get("topology");
topologyNames.add(topology);
}
for (String name : topologyNames) {
Map<String, Object> topology = (Map<String, Object>) map.get(name);
ArrayList<Map> components = (ArrayList<Map>) topology.get("components");
for (Map<String, Object> component : components) {
String nodeType = (String) component.get("nodeType");
String OStype = (String) component.get("OStype");
if (nodeType != null && OStype != null) {
return true;
}
}
}
return false;
}
// private String getBestCloudProvider() {
// List<CloudCredentials> creds = credentialService.findAll();
// return creds.get(0).getCloudProviderName().toUpperCase();
// }
// private String getBestDomain(String cloudProvider) {
// switch (cloudProvider.trim().toLowerCase()) {
// case "ec2":
// return "Frankfurt";
// case "egi":
// return "CESNET";
// case "exogeni":
// return "RENCI (Chapel Hill, NC USA) XO Rack";
// }
// return null;
// }
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.exception.CloudCredentialsNotFoundException;
import nl.uva.sne.drip.api.exception.ExceptionHandler;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.exception.PlanNotFoundException;
import nl.uva.sne.drip.api.rpc.DRIPCaller;
import nl.uva.sne.drip.api.v1.rest.ProvisionController;
import nl.uva.sne.drip.commons.utils.Converter;
import nl.uva.sne.drip.drip.commons.data.v1.external.CloudCredentials;
import nl.uva.sne.drip.drip.commons.data.internal.Message;
import nl.uva.sne.drip.drip.commons.data.internal.MessageParameter;
import nl.uva.sne.drip.drip.commons.data.v1.external.PlanResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.ProvisionRequest;
import nl.uva.sne.drip.drip.commons.data.v1.external.ProvisionResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import nl.uva.sne.drip.api.dao.ProvisionResponseDao;
import nl.uva.sne.drip.api.rpc.ProvisionerCaller1;
import nl.uva.sne.drip.commons.utils.DRIPLogHandler;
import nl.uva.sne.drip.commons.utils.TOSCAUtils;
import static nl.uva.sne.drip.commons.utils.TOSCAUtils.getVMsFromTopology;
import static nl.uva.sne.drip.commons.utils.TOSCAUtils.getVMsNodeNamesFromTopology;
import nl.uva.sne.drip.drip.commons.data.v1.external.ScaleRequest;
import org.apache.commons.codec.binary.Base64;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class ProvisionService {
@Autowired
private ProvisionResponseDao provisionDao;
@Autowired
private CloudCredentialsService cloudCredentialsService;
@Autowired
private SimplePlannerService simplePlanService;
@Value("${message.broker.host}")
private String messageBrokerHost;
private final Logger logger;
@Autowired
public ProvisionService(@Value("${message.broker.host}") String messageBrokerHost) throws IOException, TimeoutException {
logger = Logger.getLogger(ProvisionService.class.getName());
logger.addHandler(new DRIPLogHandler(messageBrokerHost));
}
public ProvisionResponse save(ProvisionResponse ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return provisionDao.save(ownedObject);
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public ProvisionResponse findOne(String id) {
ProvisionResponse provisionInfo = provisionDao.findOne(id);
if (provisionInfo == null) {
throw new NotFoundException();
}
return provisionInfo;
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public ProvisionResponse delete(String id) {
ProvisionResponse provisionInfo = provisionDao.findOne(id);
if (provisionInfo != null) {
provisionDao.delete(provisionInfo);
return provisionInfo;
} else {
throw new NotFoundException();
}
}
// @PreAuthorize(" (hasRole('ROLE_ADMIN')) or (hasRole('ROLE_USER'))")
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
// @PostFilter("hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')")
public List<ProvisionResponse> findAll() {
return provisionDao.findAll();
}
public ProvisionResponse provisionResources(ProvisionRequest provisionRequest, int provisionerVersion) throws IOException, TimeoutException, JSONException, InterruptedException, Exception {
return callProvisioner1(provisionRequest);
}
private List<MessageParameter> buildTopologyParams(PlanResponse plan) throws JSONException, FileNotFoundException {
if (plan == null) {
throw new PlanNotFoundException();
}
List<MessageParameter> parameters = new ArrayList();
MessageParameter topology = new MessageParameter();
topology.setName("topology");
String val = Converter.map2YmlString(plan.getKeyValue());
val = val.replaceAll("\\uff0E", ".");
String encodedValue = new String(Base64.encodeBase64(val.getBytes()));
topology.setValue(encodedValue);
Map<String, String> attributes = new HashMap<>();
topology.setAttributes(attributes);
parameters.add(topology);
return parameters;
}
private List<MessageParameter> buildProvisionedTopologyParams(ProvisionResponse provisionInfo) throws JSONException {
List<MessageParameter> parameters = new ArrayList();
Map<String, Object> map = provisionInfo.getKeyValue();
for (String topoName : map.keySet()) {
Map<String, Object> topo = (Map<String, Object>) map.get(topoName);
MessageParameter topology = new MessageParameter();
topology.setName("topology");
topology.setValue(Converter.map2YmlString(topo));
HashMap<String, String> attributes = new HashMap<>();
if (topoName.equals("topology_main")) {
attributes.put("level", String.valueOf(0));
} else {
attributes.put("level", String.valueOf(1));
}
attributes.put("filename", topoName);
topology.setAttributes(attributes);
parameters.add(topology);
}
return parameters;
}
private List<MessageParameter> buildClusterKeyParams(ProvisionResponse provisionInfo) {
List<MessageParameter> parameters = new ArrayList();
// List<String> ids = provisionInfo.getDeployerKeyPairIDs();
// for (String id : ids) {
// KeyPair pair = keyPairService.findOne(id);
//
// MessageParameter param = new MessageParameter();
// param.setName("private_deployer_key");
// param.setValue(pair.getPrivateKey().getKey());
// HashMap<String, String> attributes = new HashMap<>();
// if (pair.getPrivateKey() != null && pair.getPrivateKey().getAttributes() != null) {
// attributes.putAll(pair.getPrivateKey().getAttributes());
// }
// attributes.put("name", pair.getPrivateKey().getName());
// param.setAttributes(attributes);
// parameters.add(param);
//
// param = new MessageParameter();
// param.setName("public_deployer_key");
// param.setValue(pair.getPublicKey().getKey());
// attributes = new HashMap<>();
// if (pair.getPublicKey() != null && pair.getPublicKey().getAttributes() != null) {
// attributes.putAll(pair.getPublicKey().getAttributes());
// }
// param.setAttributes(attributes);
// attributes.put("name", pair.getPublicKey().getName());
// parameters.add(param);
// }
return parameters;
}
private List<MessageParameter> buildUserKeyParams(ProvisionResponse provisionInfo) {
List<MessageParameter> parameters = new ArrayList();
// List<String> ids = provisionInfo.getUserKeyPairIDs();
// for (String id : ids) {
// KeyPair pair = keyPairService.findOne(id);
//
// MessageParameter param = new MessageParameter();
// param.setName("private_user_key");
// param.setValue(pair.getPrivateKey().getKey());
// HashMap<String, String> attributes = new HashMap<>();
// if (pair.getPrivateKey().getAttributes() != null) {
// attributes.putAll(pair.getPrivateKey().getAttributes());
// }
// attributes.put("name", pair.getPrivateKey().getName());
// param.setAttributes(attributes);
// parameters.add(param);
//
// param = new MessageParameter();
// param.setName("public_user_key");
// param.setValue(pair.getPublicKey().getKey());
// if (pair.getPublicKey().getAttributes() != null) {
// attributes.putAll(pair.getPublicKey().getAttributes());
// }
// attributes.put("name", pair.getPublicKey().getName());
// param.setAttributes(attributes);
// parameters.add(param);
// }
return parameters;
}
@PostFilter("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
provisionDao.deleteAll();
}
private ProvisionResponse callProvisioner1(ProvisionRequest provisionRequest) throws IOException, TimeoutException, JSONException, InterruptedException, Exception {
try (DRIPCaller provisioner = new ProvisionerCaller1(messageBrokerHost);) {
Message provisionerInvokationMessage = buildProvisioner1Message(provisionRequest);
provisionerInvokationMessage.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
logger.info("Calling provisioner");
Message response = (provisioner.call(provisionerInvokationMessage));
logger.info("Got provisioner response");
return parseCreateResourcesResponse(response.getParameters(), provisionRequest, null, true, true);
}
}
public void deleteProvisionedResources(ProvisionResponse provisionInfo) throws IOException, TimeoutException, InterruptedException, JSONException {
try (DRIPCaller provisioner = new ProvisionerCaller1(messageBrokerHost);) {
Message deleteInvokationMessage = buildTopoplogyModificationMessage(provisionInfo, "kill_topology", null);
deleteInvokationMessage.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
logger.info("Calling provisioner");
Message response = (provisioner.call(deleteInvokationMessage));
logger.info("Got provisioner response");
parseDeleteResourcesResponse(response.getParameters(), provisionInfo);
}
}
public ProvisionResponse scale(ScaleRequest scaleRequest) throws IOException, TimeoutException, JSONException, InterruptedException, Exception {
String provisionID = scaleRequest.getScaleTargetID();
String scaleName = scaleRequest.getScaleTargetName();
if (scaleName == null || scaleName.length() < 1) {
throw new BadRequestException("Must specify wich topology to scale. \'scaleName\' was empty ");
}
ProvisionResponse provisionInfo = findOne(provisionID);
boolean scaleNameExists = false;
int currentNumOfInstances = 1;
Map<String, Object> plan = provisionInfo.getKeyValue();
String cloudProvider = null;
String domain = null;
for (String key : plan.keySet()) {
Map<String, Object> subMap = (Map<String, Object>) plan.get(key);
if (subMap.containsKey("topologies")) {
List< Map<String, Object>> topologies = (List< Map<String, Object>>) subMap.get("topologies");
for (Map<String, Object> topology : topologies) {
if (topology.get("tag").equals("scaling") && topology.get("topology").equals(scaleName) && !scaleNameExists) {
cloudProvider = (String) topology.get("cloudProvider");
domain = (String) topology.get("domain");
scaleNameExists = true;
} else if (topology.get("tag").equals("scaled")
&& topology.get("status").equals("running")
&& topology.get("copyOf").equals(scaleName)) {
currentNumOfInstances++;
}
}
}
}
if (!scaleNameExists) {
throw new BadRequestException("Name of topology dosen't exist");
}
int numOfInstances = Math.abs(currentNumOfInstances - scaleRequest.getNumOfInstances());
if (currentNumOfInstances > scaleRequest.getNumOfInstances() && currentNumOfInstances != 0) {
try (DRIPCaller provisioner = new ProvisionerCaller1(messageBrokerHost);) {
Map<String, String> extra = new HashMap<>();
extra.put("scale_topology_name", scaleName);
extra.put("number_of_instances", String.valueOf(numOfInstances));
extra.put("cloud_provider", cloudProvider);
extra.put("domain", domain);
Message scaleMessage = buildTopoplogyModificationMessage(provisionInfo, "scale_topology_down", extra);
scaleMessage.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
logger.info("Calling provisioner");
Message response = provisioner.call(scaleMessage);
logger.info("Got response from provisioner");
parseCreateResourcesResponse(response.getParameters(), null, provisionInfo, false, false);
}
} else if (currentNumOfInstances < scaleRequest.getNumOfInstances() || currentNumOfInstances == 0) {
try (DRIPCaller provisioner = new ProvisionerCaller1(messageBrokerHost);) {
Map<String, String> extra = new HashMap<>();
extra.put("scale_topology_name", scaleName);
extra.put("number_of_instances", String.valueOf(numOfInstances));
extra.put("cloud_provider", cloudProvider);
extra.put("domain", domain);
Message scaleMessage = buildTopoplogyModificationMessage(provisionInfo, "scale_topology_up", extra);
scaleMessage.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
logger.info("Calling provisioner");
Message response = provisioner.call(scaleMessage);
logger.info("Got response from provisioner");
parseCreateResourcesResponse(response.getParameters(), null, provisionInfo, false, false);
}
}
return provisionInfo;
}
private Message buildProvisioner1Message(ProvisionRequest provisionRequest) throws JSONException, FileNotFoundException, IOException {
Message invokationMessage = new Message();
List<MessageParameter> parameters = new ArrayList();
MessageParameter action = new MessageParameter();
action.setName("action");
action.setValue("start_topology");
parameters.add(action);
PlanResponse plan = addCloudCredentialsOnTOSCAPlan(provisionRequest);
List<MessageParameter> topologies = buildTopologyParams(plan);
parameters.addAll(topologies);
invokationMessage.setParameters(parameters);
invokationMessage.setCreationDate((System.currentTimeMillis()));
return invokationMessage;
}
private Message buildTopoplogyModificationMessage(ProvisionResponse provisionInfo, String actionName, Map<String, String> extraAttributes) throws JSONException, IOException {
// Message invokationMessage = new Message();
// List<MessageParameter> parameters = new ArrayList();
//
// MessageParameter action = new MessageParameter();
// action.setName("action");
// action.setValue(actionName);
// parameters.add(action);
//
// List<MessageParameter> topologies = buildProvisionedTopologyParams(provisionInfo);
// parameters.addAll(topologies);
//
// List<MessageParameter> clusterKeys = buildClusterKeyParams(provisionInfo);
// parameters.addAll(clusterKeys);
//
// List<MessageParameter> userKeys = buildUserKeyParams(provisionInfo);
// parameters.addAll(userKeys);
//
// List<MessageParameter> cloudKeys = buildCloudKeyParams(provisionInfo);
// parameters.addAll(cloudKeys);
//
//
// for (String id : provisionInfo.getCloudCredentialsIDs()) {
// CloudCredentials cred = cloudCredentialsService.findOne(id);
// if (cred == null) {
// throw new CloudCredentialsNotFoundException();
// }
//// List<MessageParameter> cloudCredentialParams = buildCloudCredentialParam(cred, 1);
//// parameters.addAll(cloudCredentialParams);
// }
// if (extraAttributes != null && extraAttributes.containsKey("scale_topology_name")) {
// MessageParameter scale = new MessageParameter();
// scale.setName("scale_topology_name");
// scale.setValue(extraAttributes.get("scale_topology_name"));
// Map<String, String> attributes = new HashMap<>();
// attributes.put("number_of_instances", extraAttributes.get("number_of_instances"));
// attributes.put("cloud_provider", extraAttributes.get("cloud_provider"));
// attributes.put("domain", extraAttributes.get("domain"));
// scale.setAttributes(attributes);
// parameters.add(scale);
// }
// invokationMessage.setParameters(parameters);
// invokationMessage.setCreationDate(System.currentTimeMillis());
return null;
}
private ProvisionResponse parseCreateResourcesResponse(List<MessageParameter> parameters,
ProvisionRequest provisionRequest, ProvisionResponse provisionResponse, boolean saveUserKeys, boolean saveDeployerKeyI) throws Exception {
if (provisionResponse == null) {
provisionResponse = new ProvisionResponse();
}
PlanResponse plan = addCloudCredentialsOnTOSCAPlan(provisionRequest);
Map<String, Object> toscaPlan = plan.getKeyValue();
Map<String, Object> topologyTemplate = (Map<String, Object>) ((Map<String, Object>) toscaPlan.get("topology_template"));
List<Map<String, Object>> vmList = getVMsFromTopology(toscaPlan);
List<String> nodeNames = getVMsNodeNamesFromTopology(toscaPlan);
Map<String, Object> outputs = new HashMap<>();
for (MessageParameter p : parameters) {
String name = p.getName();
if (name.toLowerCase().contains("exception")) {
RuntimeException ex = ExceptionHandler.generateException(name, p.getValue());
Logger.getLogger(ProvisionController.class.getName()).log(Level.SEVERE, null, ex);
throw ex;
}
if (name.equals("deploy_parameters")) {
String value = p.getValue();
String[] lines = value.split("\n");
if (value.length() < 2) {
throw new Exception("Provision failed");
// this.deleteProvisionedResources(provisionResponse);
}
for (int i = 0; i < lines.length; i++) {
String[] parts = lines[i].split(" ");
String deployIP = parts[0];
String deployUser = parts[1];
String deployRole = parts[2];
String nodeName = nodeNames.get(i);
Map<String, Object> properties = (Map<String, Object>) vmList.get(i).get("properties");
properties.put("user_name", deployUser);
outputs = TOSCAUtils.buildTOSCAOutput(outputs, nodeName, deployIP, "ip", false);
outputs = TOSCAUtils.buildTOSCAOutput(outputs, nodeName, deployUser, "user_name", false);
outputs = TOSCAUtils.buildTOSCAOutput(outputs, nodeName, deployRole, "role", false);
}
}
if (name.contains("_key")) {
for (String nodeName : nodeNames) {
outputs = TOSCAUtils.buildTOSCAOutput(outputs, nodeName, p.getValue(), name, true);
}
}
}
topologyTemplate.put("outputs", outputs);
provisionResponse.setKvMap(toscaPlan);
provisionResponse = save(provisionResponse);
return provisionResponse;
}
private void parseDeleteResourcesResponse(List<MessageParameter> parameters, ProvisionResponse provisionInfo) {
}
private PlanResponse addCloudCredentialsOnTOSCAPlan(ProvisionRequest provisionRequest) {
List<Map<String, Object>> credentials = new ArrayList<>();
for (String id : provisionRequest.getCloudCredentialsIDs()) {
CloudCredentials cred = cloudCredentialsService.findOne(id);
if (cred == null) {
throw new CloudCredentialsNotFoundException();
}
Map<String, Object> toscaCredential = new HashMap<>();
Map<String, Object> toscaCredentialProperties = new HashMap<>();
toscaCredentialProperties.put("token_type", "secretKey");
toscaCredentialProperties.put("token", cred.getSecretKey());
toscaCredentialProperties.put("accessKeyId", cred.getAccessKeyId());
toscaCredentialProperties.put("cloud_provider_name", cred.getCloudProviderName());
toscaCredentialProperties.put("attributes", cred.getAttributes());
toscaCredential.put("properties", toscaCredentialProperties);
credentials.add(toscaCredential);
}
PlanResponse plan = simplePlanService.getDao().findOne(provisionRequest.getPlanID());
Map<String, Object> toscaPlan = plan.getKeyValue();
Map<String, Object> nodeTemplates = (Map<String, Object>) ((Map<String, Object>) toscaPlan.get("topology_template")).get("node_templates");
Iterator it = nodeTemplates.entrySet().iterator();
while (it.hasNext()) {
Map.Entry node = (Map.Entry) it.next();
Map<String, Object> value = (Map<String, Object>) node.getValue();
String type = (String) value.get("type");
if (type.equals("tosca.nodes.ARTICONF.VM.topology")) {
Map<String, Object> properties = (Map<String, Object>) value.get("properties");
properties.put("credentials", credentials);
}
}
return plan;
}
public String get(String id, String format) throws JSONException {
ProvisionResponse pro = findOne(id);
Map<String, Object> map = pro.getKeyValue();
if (format != null && format.equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
if (format != null && format.equals("json")) {
String jsonStr = Converter.map2JsonString(map);
jsonStr = jsonStr.replaceAll("\\uff0E", ".");
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import nl.uva.sne.drip.api.dao.PlanDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.rpc.PlannerCaller;
import nl.uva.sne.drip.drip.commons.data.internal.Message;
import nl.uva.sne.drip.drip.commons.data.internal.MessageParameter;
import nl.uva.sne.drip.drip.commons.data.v1.external.PlanResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.ToscaRepresentation;
import nl.uva.sne.drip.commons.utils.Converter;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
public class SimplePlannerService {
@Value("${message.broker.host}")
private String messageBrokerHost;
@Autowired
private ToscaService toscaService;
@Autowired
private PlanDao planDao;
public PlanResponse getPlan(String toscaId) throws JSONException, IOException, TimeoutException, InterruptedException {
ToscaRepresentation tosca = toscaService.findOne(toscaId);
Message plannerInvokationMessage = buildSimplePlannerMessage(tosca);
PlanResponse topLevel;
try (PlannerCaller planner = new PlannerCaller(messageBrokerHost)) {
Message plannerReturnedMessage = (planner.call(plannerInvokationMessage));
List<MessageParameter> planFiles = plannerReturnedMessage.getParameters();
topLevel = new PlanResponse();
// Set<String> ids = topLevel.getLoweLevelPlanIDs();
// if (ids == null) {
// ids = new HashSet<>();
// }
PlanResponse lowerLevelPlan = null;
for (MessageParameter p : planFiles) {
//Should have levels in attributes
Map<String, String> attributess = p.getAttributes();
if (attributess != null) {
attributess.get("level");
}
String originalFileName = p.getName();
String name = System.currentTimeMillis() + "_" + originalFileName;
if (originalFileName.equals("planner_output_all.yml")) {
// topLevel.setName(name);
// topLevel.setLevel(0);
topLevel.setKvMap(Converter.ymlString2Map(p.getValue()));
} else {
lowerLevelPlan = new PlanResponse();
// lowerLevelPlan.setName(name);
lowerLevelPlan.setKvMap(Converter.ymlString2Map(p.getValue()));
// lowerLevelPlan.setLevel(1);
planDao.save(lowerLevelPlan);
// ids.add(lowerLevelPlan.getId());
}
}
// topLevel.setLoweLevelPlansIDs(ids);
}
topLevel.setToscaID(toscaId);
planDao.save(topLevel);
return topLevel;
}
private Message buildSimplePlannerMessage(ToscaRepresentation t2) throws JSONException, UnsupportedEncodingException, IOException {
if (t2 == null) {
throw new NotFoundException();
}
Map<String, Object> map = t2.getKeyValue();
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
byte[] bytes = ymlStr.getBytes();
Message invokationMessage = new Message();
List parameters = new ArrayList();
MessageParameter fileArgument = new MessageParameter();
String charset = "UTF-8";
fileArgument.setValue(new String(bytes, charset));
fileArgument.setEncoding(charset);
fileArgument.setName("input");
parameters.add(fileArgument);
fileArgument = new MessageParameter();
bytes = Files.readAllBytes(Paths.get(System.getProperty("user.home") + File.separator + "Downloads/DRIP/example_a.yml"));
fileArgument.setValue(new String(bytes, charset));
fileArgument.setEncoding(charset);
fileArgument.setName("example");
parameters.add(fileArgument);
invokationMessage.setParameters(parameters);
invokationMessage.setCreationDate((System.currentTimeMillis()));
return invokationMessage;
}
public String get(String id, String fromat) throws JSONException {
PlanResponse plan = planDao.findOne(id);
if (plan == null) {
throw new NotFoundException();
}
Map<String, Object> map = plan.getKeyValue();
// Set<String> ids = plan.getLoweLevelPlanIDs();
// for (String lowID : ids) {
// Map<String, Object> lowLevelMap = planDao.findOne(lowID).getKeyValue();
// map.putAll(lowLevelMap);
// }
if (fromat != null && fromat.equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
if (fromat != null && fromat.equals("json")) {
String jsonStr = Converter.map2JsonString(map);
jsonStr = jsonStr.replaceAll("\\uff0E", ".");
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
public PlanDao getDao() {
return planDao;
}
public String getToscaID(String id) {
return planDao.findOne(id).getToscaID();
}
public List<PlanResponse> findAll() {
List<PlanResponse> all = planDao.findAll();
// List<PlanResponse> topLevel = new ArrayList<>();
// for (PlanResponse p : all) {
// if (p.getLevel() == 0) {
// topLevel.add(p);
// }
// }
return all;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import nl.uva.sne.drip.api.dao.ToscaDao;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.rpc.DRIPCaller;
import nl.uva.sne.drip.api.rpc.TransformerCaller;
import nl.uva.sne.drip.drip.commons.data.v1.external.ToscaRepresentation;
import nl.uva.sne.drip.commons.utils.Converter;
import nl.uva.sne.drip.drip.commons.data.internal.Message;
import nl.uva.sne.drip.drip.commons.data.internal.MessageParameter;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
/**
*
* @author S. Koulouzis
*/
@Service
@PreAuthorize("isAuthenticated()")
public class ToscaService {
@Autowired
private ToscaDao dao;
@Value("${message.broker.host}")
private String messageBrokerHost;
public String get(Map<String, Object> map, String fromat) throws JSONException {
if (fromat != null && fromat.equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
if (fromat != null && fromat.equals("json")) {
String jsonStr = Converter.map2JsonString(map);
jsonStr = jsonStr.replaceAll("\\uff0E", ".");
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
public String get(String id, String fromat) throws JSONException {
ToscaRepresentation tosca = findOne(id);
if (tosca == null) {
throw new NotFoundException();
}
Map<String, Object> map = tosca.getKeyValue();
if (fromat != null && fromat.equals("yml")) {
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
if (fromat != null && fromat.equals("json")) {
String jsonStr = Converter.map2JsonString(map);
jsonStr = jsonStr.replaceAll("\\uff0E", ".");
return jsonStr;
}
String ymlStr = Converter.map2YmlString(map);
ymlStr = ymlStr.replaceAll("\\uff0E", ".");
return ymlStr;
}
public String saveFile(MultipartFile file) throws IOException {
String originalFileName = file.getOriginalFilename();
String name = System.currentTimeMillis() + "_" + originalFileName;
byte[] bytes = file.getBytes();
String str = new String(bytes, "UTF-8");
return saveStringContents(str, name);
}
public String saveYamlString(String yamlString, String name) throws IOException {
if (name == null) {
name = System.currentTimeMillis() + "_" + "tosca.yaml";
}
yamlString = yamlString.replaceAll("\\.", "\uff0E");
Map<String, Object> map = Converter.ymlString2Map(yamlString);
ToscaRepresentation t = new ToscaRepresentation();
t.setName(name);
t.setKvMap(map);
save(t);
return t.getId();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public ToscaRepresentation delete(String id) {
ToscaRepresentation tr = dao.findOne(id);
dao.delete(tr);
return tr;
}
@PostFilter("(filterObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public List<ToscaRepresentation> findAll() {
return dao.findAll();
}
@PostAuthorize("(returnObject.owner == authentication.name) or (hasRole('ROLE_ADMIN'))")
public ToscaRepresentation findOne(String id) {
ToscaRepresentation tr = dao.findOne(id);
return tr;
}
private ToscaRepresentation save(ToscaRepresentation ownedObject) {
User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String owner = user.getUsername();
ownedObject.setOwner(owner);
return dao.save(ownedObject);
}
@PostAuthorize("(hasRole('ROLE_ADMIN'))")
public void deleteAll() {
dao.deleteAll();
}
public String saveStringContents(String toscaContents, String name) throws IOException {
Map<String, Object> map = Converter.cleanStringContents(toscaContents, true);
ToscaRepresentation t = new ToscaRepresentation();
t.setName(name);
t.setKvMap(map);
save(t);
return t.getId();
}
public String transform(String id, String target) throws JSONException, IOException, TimeoutException, InterruptedException {
ToscaRepresentation toscaRep = findOne(id);
switch (target) {
case "docker_compose":
return getDockerCompose(toscaRep);
}
return null;
}
private String getDockerCompose(ToscaRepresentation toscaRep) throws IOException, TimeoutException, JSONException, InterruptedException {
String dockerCompose;
try (DRIPCaller transformer = new TransformerCaller(messageBrokerHost);) {
Message transformerInvokationMessage = buildDockerComposeMessage(toscaRep);
transformerInvokationMessage.setOwner(((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsername());
Message response = (transformer.call(transformerInvokationMessage));
dockerCompose = response.getParameters().get(0).getValue();
}
return dockerCompose;
}
private Message buildDockerComposeMessage(ToscaRepresentation toscaRep) throws JSONException {
Message deployInvokationMessage = new Message();
List<MessageParameter> parameters = new ArrayList<>();
MessageParameter messageParam = new MessageParameter();
messageParam.setName(toscaRep.getName());
messageParam.setValue(get(toscaRep.getKeyValue(), "yml"));
parameters.add(messageParam);
deployInvokationMessage.setParameters(parameters);
deployInvokationMessage.setCreationDate(System.currentTimeMillis());
return deployInvokationMessage;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.service;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import nl.uva.sne.drip.api.dao.UserDao;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
/**
*
* @author S. Koulouzis
*/
@Service
public class UserService implements UserDetailsService {
public static final String ADMIN = "ADMIN";
public static final String USER = "USER";
@Autowired
private UserDao dao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
User user = dao.findByUsername(username);
return user;
} catch (Exception ex) {
Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public User save(User user) {
return dao.save(user);
}
public User findOne(String id) {
return dao.findOne(id);
}
public void delete(User user) {
dao.delete(user);
}
public List<User> findAll() {
return dao.findAll();
}
public void deleteAll() {
dao.deleteAll();
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.service.AnsibleOutputService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.ansible.AnsibleOutput;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
/**
* This controller is responsible for showing the output from ansible executions
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/deployer/ansible")
@Controller
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class AnsibleOutputController {
@Autowired
private AnsibleOutputService ansibleOutputService;
/**
* Returns an AnsibleOutput.
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "AnsibleOutput not found"),
@ResponseCode(code = 200, condition = "AnsibleOutput exists")
})
public @ResponseBody
AnsibleOutput get(@PathVariable("id") String id) {
AnsibleOutput resp = ansibleOutputService.findOne(id);
if (resp == null) {
throw new NotFoundException();
}
return resp;
}
/**
* Returns the ids of stored objects. Empty list if non stored
*
* @return
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful query")
})
public @ResponseBody
List<String> getIds() {
List<AnsibleOutput> all = ansibleOutputService.findAll();
List<String> ids = new ArrayList<>(all.size());
for (AnsibleOutput pi : all) {
ids.add(pi.getId());
}
return ids;
}
/**
* Deletes object
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete"),
@ResponseCode(code = 404, condition = "Non existing id")
})
public @ResponseBody
String delete(@PathVariable("id") String id) {
AnsibleOutput Key = ansibleOutputService.findOne(id);
if (Key != null) {
ansibleOutputService.delete(id);
return "Deleted : " + id;
}
throw new NotFoundException();
}
/**
* Deletes all entries. Use with caution !
*
* @return
*/
@RequestMapping(value = "/all", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete")
})
public @ResponseBody
String deleteAll() {
ansibleOutputService.deleteAll();
return "Done";
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.core.MediaType;
import nl.uva.sne.drip.drip.commons.data.v1.external.CloudCredentials;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.exception.KeyException;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.exception.NullCloudProviderException;
import nl.uva.sne.drip.api.exception.NullKeyException;
import nl.uva.sne.drip.api.service.CloudCredentialsService;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.Key;
import nl.uva.sne.drip.drip.commons.data.v1.external.KeyPair;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
/**
*
* This controller is responsible for handling CloudCredentials.
* CloudCredentials are a representation of the credentials that are used by the
* provisoner to request for resources (VMs)
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/credentials/cloud")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class CloudCredentialsController {
@Autowired
private CloudCredentialsService cloudCredentialsService;
/**
* Post the cloud credentials.
*
* @param cloudCredentials
* @return the CloudCredentials id
*/
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "Key can't be empty")
,
@ResponseCode(code = 404, condition = "Cloud provider's name can't be empty")
,
@ResponseCode(code = 200, condition = "At least one key ID is posted")
})
public @ResponseBody
String postCredentials(@RequestBody CloudCredentials cloudCredentials) {
if (cloudCredentials.getSecretKey() == null || cloudCredentials.getSecretKey().length() < 1) {
throw new NullKeyException();
}
if (cloudCredentials.getCloudProviderName() == null || cloudCredentials.getCloudProviderName().length() < 1) {
throw new NullCloudProviderException();
}
cloudCredentials = cloudCredentialsService.save(cloudCredentials);
return cloudCredentials.getId();
}
/**
* Upload the login keys for a cloud provider. The cloud credentials have to
* be created
*
* @param file
* @param id
* @return the CloudCredentials id
* @throws java.lang.Exception
*/
@RequestMapping(value = "/upload/{id}", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "Credential not found")
,
@ResponseCode(code = 400, condition = "Did not upload file")
,
@ResponseCode(code = 200, condition = "Key added to credential")
})
public @ResponseBody
String addLogineKey(@RequestParam("file") MultipartFile file, @PathVariable("id") String id) throws Exception {
try {
CloudCredentials cloudCredentials = cloudCredentialsService.findOne(id);
if (cloudCredentials == null) {
throw new NotFoundException();
}
if (file.isEmpty()) {
throw new BadRequestException("Must uplaod a file");
}
String originalFileName = file.getOriginalFilename();
byte[] bytes = file.getBytes();
// List<String> loginKeyIDs = cloudCredentials.getkeyPairIDs();
// if (loginKeyIDs == null) {
// loginKeyIDs = new ArrayList<>();
// }
Key key = new Key();
key.setKey(new String(bytes, "UTF-8"));
if (cloudCredentials.getCloudProviderName().toLowerCase().equals("ec2")) {
Map<String, String> attributes = new HashMap<>();
attributes.put("domain_name", FilenameUtils.removeExtension(originalFileName));
key.setAttributes(attributes);
KeyPair pair = new KeyPair();
pair.setPrivateKey(key);
}
if (cloudCredentials.getCloudProviderName().toLowerCase().equals("egi")) {
cloudCredentials.setSecretKey(new String(bytes, "UTF-8"));
}
cloudCredentials = cloudCredentialsService.save(cloudCredentials);
return cloudCredentials.getId();
} catch (IOException | KeyException ex) {
Logger.getLogger(CloudCredentialsController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Get the cloud credentials
*
* @param id the id of the cloud credentials
* @return the cloud credentials
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "Credential not found")
,
@ResponseCode(code = 200, condition = "Credential exists")
})
public @ResponseBody
CloudCredentials get(@PathVariable("id") String id) {
CloudCredentials cc = cloudCredentialsService.findOne(id);
if (cc == null) {
throw new NotFoundException();
}
return cc;
}
/**
* Delete the cloud credentials
*
* @param id the id of the cloud credentials
* @return the id of the cloud credentials
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Credential exists")
})
public @ResponseBody
String delete(@PathVariable("id") String id) {
cloudCredentialsService.delete(id);
return "Deleted :" + id;
}
/**
* Deletes all credentials. Use with caution !
*
* @return
*/
@RequestMapping(value = "/all", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Credentiasl exist")
})
public @ResponseBody
String deleteAll() {
cloudCredentialsService.deleteAll();
return "Done";
}
/**
* Gets all the IDs of the stored cloud credentials
*
* @return a list of stored IDs
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Credentials exist")
})
public @ResponseBody
List<String> getIds() {
List<CloudCredentials> all = cloudCredentialsService.findAll();
List<String> ids = new ArrayList<>();
for (CloudCredentials tr : all) {
ids.add(tr.getId());
}
return ids;
}
@RequestMapping(value = "/sample", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
CloudCredentials getSample() {
CloudCredentials cloudCredentials = new CloudCredentials();
cloudCredentials.setAccessKeyId("AKIAITWERHZUQ6M7YBSQ");
cloudCredentials.setCloudProviderName("egi");
cloudCredentials.setSecretKey("6J7uo99ifrff45sa6Gsy5vgb3b3ewdsdtwY6hBxtYt9y");
List<String> keyIDs = new ArrayList<>();
keyIDs.add("58da4c91f7b43a3282cacdbb");
keyIDs.add("58da4d2af7b43a3282cacdbd");
Map<String, Object> attributes = new HashMap<>();
attributes.put("myProxyEndpoint", "myproxy.egee.host.com");
attributes.put("trustedCertificatesURL", "https://dist.eugridpma.info/distribution/igtf/current/accredited/igtf-preinstalled-bundle-classic.tar.gz");
cloudCredentials.setAttributes(attributes);
return cloudCredentials;
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import nl.uva.sne.drip.drip.commons.data.v1.external.ConfigurationRepresentation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.PathVariable;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.service.ConfigurationService;
import nl.uva.sne.drip.api.service.UserService;
import org.springframework.web.bind.annotation.RequestBody;
/**
* This controller is responsible for managing deployment configurations used
* by the deployer. Currently docker-compose.yml and ansible playbooks are supported.
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/deployer/configuration")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class ConfigurationController {
@Autowired
private ConfigurationService configurationService;
/**
* Post a deployment configuration.
*
* @param yamlContents
* @return
*/
@RequestMapping(value = "/post", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful post"),
@ResponseCode(code = 400, condition = "contents are not valid (e.g. not a yaml format)")
})
public @ResponseBody
String post(@RequestBody String yamlContents) {
try {
return configurationService.saveStringContents(yamlContents);
} catch (IOException ex) {
throw new BadRequestException("Not valid contents");
}
}
/**
* Uploads and stores a configuration file
*
* @param file. The configuration description file
* @return the ID of the configuration description
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful upload"),
@ResponseCode(code = 400, condition = "Didn't upload (multipart) file or "
+ "contents are not valid (e.g. not a yaml format)")
})
public @ResponseBody
String configurationUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
throw new BadRequestException("Must uplaod a file");
}
try {
return configurationService.saveFile(file);
} catch (IOException | IllegalStateException ex) {
throw new BadRequestException("Not valid contents");
}
}
/**
* Gets the configuration contents.
*
* @param id the ID configuration contents.
* @param format. the format to display the configuration description.
* @return the configuration contents.
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, params = {"format"})
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Object found"),
@ResponseCode(code = 400, condition = "contents are not valid (e.g. not a yaml format)"),
@ResponseCode(code = 404, condition = "Object not found")
})
public @ResponseBody
String get(@PathVariable("id") String id, @RequestParam(value = "format") String format) {
try {
return configurationService.get(id, format);
} catch (JSONException | NotFoundException ex) {
throw new BadRequestException("Not valid contents");
}
}
/**
* Deletes the configuration
*
* @param id. The ID of configuration
* @return The ID of the deleted configuration
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete"),
@ResponseCode(code = 404, condition = "Object not found")
})
public @ResponseBody
String delete(@PathVariable("id") String id) {
try {
configurationService.delete(id);
} catch (NotFoundException ex) {
throw ex;
}
return "Deleted : " + id;
}
/**
* Gets the IDs of all the stored configuration
*
* @return a list of all the IDs
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful query")
})
public @ResponseBody
List<String> getIds() {
List<ConfigurationRepresentation> all = configurationService.findAll();
List<String> ids = new ArrayList<>();
for (ConfigurationRepresentation tr : all) {
ids.add(tr.getId());
}
return ids;
}
/**
* Deletes all entries. Use with caution !
*
* @return
*/
@RequestMapping(value = "/all", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete")
})
public @ResponseBody
String deleteAll() {
configurationService.deleteAll();
return "Done";
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.exception.InternalServerErrorException;
import nl.uva.sne.drip.api.exception.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.service.DeployService;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.DeployRequest;
import nl.uva.sne.drip.drip.commons.data.v1.external.DeployResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.ScaleRequest;
import org.json.JSONException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
/**
* This controller is responsible for deploying a cluster on provisioned
* resources.
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/deployer")
@Controller
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class DeployController {
@Autowired
private DeployService deployService;
/**
* Deploys software (inc. swarm ,kubernetes) to provisioned VMs.
*
* @param deployRequest
* @return
*/
@RequestMapping(value = "/deploy", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 400, condition = "Empty provision ID")
,
@ResponseCode(code = 500, condition = "Deploymet failed")
,
@ResponseCode(code = 200, condition = "Successful deploymet")
})
public @ResponseBody
String deploy(@RequestBody DeployRequest deployRequest) {
try {
if (deployRequest.getProvisionID() == null) {
throw new BadRequestException("Must provide provision ID");
}
DeployResponse deploy = deployService.deploySoftware(deployRequest);
return deploy.getId();
} catch (Exception ex) {
throw new InternalServerErrorException(ex.getMessage());
}
}
/**
* Scales deployment
*
* @param scaleRequest
* @return
*/
@RequestMapping(value = "/scale", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String scaleDeployment(@RequestBody ScaleRequest scaleRequest) {
try {
return deployService.scale(scaleRequest).getId();
} catch (TimeoutException ex) {
Logger.getLogger(DeployController.class.getName()).log(Level.SEVERE, null, ex);
} catch (InterruptedException ex) {
Logger.getLogger(DeployController.class.getName()).log(Level.SEVERE, null, ex);
} catch (JSONException ex) {
Logger.getLogger(DeployController.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(DeployController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Returns a deployment description
*
* @param id
* @param format
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, params = {"format"})
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "Object not found")
,
@ResponseCode(code = 200, condition = "Object found")
})
public @ResponseBody
String get(@PathVariable("id") String id, @RequestParam(value = "format") String format) {
try {
DeployResponse resp = null;
return deployService.get(id, format);
} catch (JSONException | IOException | TimeoutException | InterruptedException ex) {
Logger.getLogger(DeployController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* For a given service name returns the container status on all nodes
*
* @param id
* @param serviceName
* @return
*/
@RequestMapping(value = "/{id}/container_status", method = RequestMethod.GET, params = {"service_name"})
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "Object not found")
,
@ResponseCode(code = 200, condition = "Object found")
})
public @ResponseBody
DeployResponse getContainerStatus(@PathVariable("id") String id,
@RequestParam(value = "service_name", required = true) String serviceName) {
DeployResponse resp = null;
try {
resp = deployService.getContainersStatus(id, serviceName);
} catch (JSONException | IOException | TimeoutException | InterruptedException ex) {
Logger.getLogger(DeployController.class.getName()).log(Level.SEVERE, null, ex);
}
if (resp == null) {
throw new NotFoundException();
}
return resp;
}
/**
* Returns the service names running on the cluster
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}/service_names", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "Object not found")
,
@ResponseCode(code = 200, condition = "Object found")
})
public @ResponseBody
List<String> getContainerStatus(@PathVariable("id") String id) {
List<String> names = null;
try {
names = deployService.getServiceNames(id);
} catch (JSONException | IOException | TimeoutException | InterruptedException ex) {
Logger.getLogger(DeployController.class.getName()).log(Level.SEVERE, null, ex);
}
if (names == null) {
throw new NotFoundException();
}
return names;
}
/**
* Gets the IDs of all the stored deployment descriptions.
*
* @return a list of all the IDs
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful query")
})
public @ResponseBody
List<String> getIds() {
List<DeployResponse> all = deployService.findAll();
List<String> ids = new ArrayList<>(all.size());
for (DeployResponse pi : all) {
ids.add(pi.getId());
}
return ids;
}
/**
* Deletes entry
*
* @param id
* @return
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete")
,
@ResponseCode(code = 404, condition = "Object not found")
})
public @ResponseBody
String delete(@PathVariable("id") String id) {
DeployResponse Key = null;
try {
Key = deployService.findOne(id);
} catch (JSONException | IOException | TimeoutException | InterruptedException ex) {
Logger.getLogger(DeployController.class.getName()).log(Level.SEVERE, null, ex);
}
if (Key != null) {
deployService.delete(id);
return "Deleted : " + id;
}
throw new NotFoundException();
}
/**
* Deletes all entries. Use with caution !
*
* @return
*/
@RequestMapping(value = "/all", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete")
})
public @ResponseBody
String deleteAll() {
deployService.deleteAll();
return "Done";
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.service.DRIPLogService;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.DRIPLogRecord;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
/**
* This controller is responsible for storing TOSCA descriptions that can be
* used by the planner.
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/logs")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class LogController {
@Autowired
private DRIPLogService logService;
@RequestMapping(method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
List<DRIPLogRecord> get() {
try {
return logService.get();
} catch (IOException | TimeoutException ex) {
Logger.getLogger(LogController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
// @RequestMapping(method = RequestMethod.GET, value = "/ll")
// @RolesAllowed({UserService.USER, UserService.ADMIN})
// public @ResponseBody
// ResponseBodyEmitter streamLogs() {
//
// final ResponseBodyEmitter emitter = new ResponseBodyEmitter();
// ExecutorService service = Executors.newSingleThreadExecutor();
// service.execute(new Runnable() {
// @Override
// public void run() {
// int i = 0;
// while (true) {
// try {
// i++;
// emitter.send(i + " - ", MediaType.TEXT_PLAIN);
// Thread.sleep(10);
// } catch (InterruptedException | IOException ex) {
// Logger.getLogger(LogController.class.getName()).log(Level.SEVERE, null, ex);
// emitter.completeWithError(ex);
// }
//
// }
//// emitter.complete();
// }
// });
//
// return emitter;
// }
@RequestMapping(method = RequestMethod.GET, value = "/ll")
@RolesAllowed({UserService.USER, UserService.ADMIN})
public StreamingResponseBody streamLogs() {
return new StreamingResponseBody() {
@Override
public void writeTo(OutputStream out) throws IOException {
ObjectMapper mapper = new ObjectMapper();
while (true) {
try {
List<DRIPLogRecord> logs = logService.get();
for (DRIPLogRecord log : logs) {
out.write(mapper.writeValueAsBytes(log));
out.write("\n".getBytes());
Thread.sleep(10);
}
Thread.sleep(2000);
} catch (InterruptedException | TimeoutException ex) {
Logger.getLogger(LogController.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.flush();
}
}
}
};
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import nl.uva.sne.drip.drip.commons.data.v1.external.GrafanaMonitorringMessage;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.core.MediaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import nl.uva.sne.drip.api.service.MonitorringMessageService;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.MonitorringMessage;
import org.springframework.web.bind.annotation.RequestBody;
/**
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/monitoring_message")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class MonitorringMessageController {
@Autowired
private MonitorringMessageService monitorringMessageService;
@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String post(@RequestBody MonitorringMessage message) {
return monitorringMessageService.save(message).getId();
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
MonitorringMessage get(@PathVariable("id") String id) {
return monitorringMessageService.findOne(id);
}
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
List<String> getIds() {
List<MonitorringMessage> all = monitorringMessageService.findAll();
List<String> ids = new ArrayList<>();
for (MonitorringMessage tr : all) {
ids.add(tr.getId());
}
return ids;
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import nl.uva.sne.drip.api.exception.NotFoundException;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.service.PlannerService;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.PlanResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
/**
* This controller is responsible for planning the type of resources to be
* provisioned based on a TOSCA description.
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/planner")
@Controller
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
//@MonitoredWithSpring
public class PlannerController {
@Autowired
private PlannerService plannerService;
// @Autowired
// private ToscaService toscaService;
/**
* verifies plan. Checks if this is a concrete plan
*
* @param toscaContents
* @return the id of the created plan
*/
@RequestMapping(value = "/vereify_plan", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
Boolean verifyPlan(@RequestBody String toscaContents) {
return plannerService.verify(toscaContents);
}
/**
* Plans resources (number, size of VMs etc).
*
* @param toscaId. The id of the TOSCA description
* @param preferredProvider
* @param maxVm
* @return the id of the created plan
*/
@RequestMapping(value = "/plan/{tosca_id}", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String plan(@PathVariable("tosca_id") String toscaId,
@RequestParam(value = "preferred_provider", required = false) String preferredProvider,
@RequestParam(value = "max_vm", required = false) Integer maxVm) {
try {
PlanResponse plan = plannerService.getPlan(toscaId, preferredProvider, maxVm);
if (plan == null) {
throw new NotFoundException("Could not make plan");
}
return plan.getId();
} catch (JSONException | IOException | TimeoutException | InterruptedException ex) {
Logger.getLogger(PlannerController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Gets a plan
*
* @param id. The id of the plan
* @param format. The format (yml,json)
* @return the plan
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, params = {"format"})
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String get(@PathVariable("id") String id, @RequestParam(value = "format") String format) {
try {
return plannerService.get(id, format);
} catch (JSONException ex) {
Logger.getLogger(ToscaController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Gets the ID of the TOSCA description that was used to generate the plan.
* The plan is represented by its ID
*
* @param id. The plan id
* @return the TOSCA description ID
*/
@RequestMapping(value = "/tosca/{id}", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String getToscaID(@PathVariable("id") String id) {
return plannerService.getToscaID(id);
}
/**
* Deletes the plan.
*
* @param id . The ID of the plan
* @return The ID of the deleted plan
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String delete(@PathVariable("id") String id) {
plannerService.delete(id);
return "Deleted : " + id;
}
@RequestMapping(value = "/all", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
String deleteAll() {
plannerService.deleteAll();
return "Done";
}
/**
* Gets the IDs of all the stored plans
*
* @return a list of IDs
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
List<String> getIds() {
List<PlanResponse> all = plannerService.findAll();
List<String> ids = new ArrayList<>();
for (PlanResponse tr : all) {
ids.add(tr.getId());
}
return ids;
}
// @RequestMapping(value = "/post/{name}", method = RequestMethod.POST)
// @RolesAllowed({UserService.USER, UserService.ADMIN})
// public @ResponseBody
// String postTop(@RequestBody String toscaContents, @PathVariable("name") String name) {
// return plannerService.saveStringContents(toscaContents, 0, name);
// }
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import nl.uva.sne.drip.drip.commons.data.v1.external.ProvisionRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.exception.CloudCredentialsNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.exception.NotFoundException;
import nl.uva.sne.drip.api.service.ProvisionService;
import nl.uva.sne.drip.api.service.UserService;
import nl.uva.sne.drip.drip.commons.data.v1.external.ProvisionResponse;
import nl.uva.sne.drip.drip.commons.data.v1.external.ScaleRequest;
import org.json.JSONException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
/**
* This controller is responsible for obtaining resources from cloud providers
* based the plan generated by the planner
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/provisioner")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class ProvisionController {
@Autowired
private ProvisionService provisionService;
/**
* Gets the supported providers
*
* @return the supported providers
*/
@RequestMapping(value = "/providers", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "object not found")
,
@ResponseCode(code = 200, condition = "object exists")
})
public @ResponseBody
String[] getSuportedProviders() {
return new String[]{"egi", "ec2", "exogeni"};
}
/**
* Gets the ProvisionRequest
*
* @param id. The id of the ProvisionRequest
* @param format
* @return the requested ProvisionRequest
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, params = {"format"})
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "object not found")
,
@ResponseCode(code = 200, condition = "object exists")
})
public @ResponseBody
String get(@PathVariable("id") String id, @RequestParam(value = "format") String format) {
try {
String pro = provisionService.get(id, format);
if (pro == null) {
throw new NotFoundException();
}
return pro;
} catch (JSONException ex) {
Logger.getLogger(ProvisionController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Deletes the ProvisionRequest
*
* @param id. The ID of the ProvisionRequest to be deleted
* @return the ID of the deleted ProvisionRequest
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 404, condition = "object not found")
,
@ResponseCode(code = 200, condition = "delete successful")
})
public @ResponseBody
String delete(@PathVariable("id") String id) {
ProvisionResponse provPlan = provisionService.findOne(id);
if (provPlan != null) {
try {
provisionService.deleteProvisionedResources(provPlan);
ProvisionResponse provisionInfo = provisionService.delete(id);
return "Deleted : " + id;
} catch (IOException | TimeoutException | InterruptedException | JSONException ex) {
Logger.getLogger(ProvisionController.class.getName()).log(Level.SEVERE, null, ex);
}
}
throw new NotFoundException();
}
/**
* Deletes all entries. Use with caution !
*
* @return
*/
@RequestMapping(value = "/all", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful delete")
})
public @ResponseBody
String deleteAll() {
provisionService.deleteAll();
return "Done";
}
/**
* Gets the IDs of all the stored ProvisionRequest
*
* @return a list of IDs
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 200, condition = "Successful query")
})
public @ResponseBody
List<String> getIds() {
List<ProvisionResponse> all = provisionService.findAll();
List<String> ids = new ArrayList<>(all.size());
for (ProvisionResponse pi : all) {
ids.add(pi.getId());
}
return ids;
}
/**
* Provision the resources specified by a plan.
*
* @param req. The ProvisionRequest. This is a container the plan ID, cloud
* credent ID, etc.
* @return The ID of the provisioned ProvisionRequest
*/
@RequestMapping(value = "/provision", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 400, condition = "Plan not found or credentials not found")
,
@ResponseCode(code = 200, condition = "provision success")
})
public @ResponseBody
String provision(@RequestBody ProvisionRequest req) {
if (req.getCloudCredentialsIDs() == null) {
throw new BadRequestException();
}
if (req.getPlanID() == null || req.getPlanID().length() < 2) {
throw new BadRequestException();
}
try {
ProvisionResponse resp = provisionService.provisionResources(req, 1);
return resp.getId();
} catch (Exception ex) {
if (ex instanceof nl.uva.sne.drip.api.exception.PlanNotFoundException
|| ex instanceof nl.uva.sne.drip.api.exception.NotFoundException
|| ex instanceof CloudCredentialsNotFoundException) {
throw new BadRequestException(ex.getMessage());
}
Logger.getLogger(ProvisionController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Updates or creates a new ProvisionResponse.
*
* @param resp
* @return
*/
@RequestMapping(value = "/post/provision", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
@StatusCodes({
@ResponseCode(code = 400, condition = "Plan not found or credentials not found or something important")
,
@ResponseCode(code = 200, condition = "provision success")
})
public @ResponseBody
String postProvisionResponse(@RequestBody ProvisionResponse resp) {
// if (resp.getCloudCredentialsIDs() == null || resp.getCloudCredentialsIDs().get(0) == null
// || resp.getCloudCredentialsIDs().get(0).length() < 2) {
// throw new BadRequestException();
// }
// if (resp.getPlanID() == null || resp.getPlanID().length() < 2) {
// throw new BadRequestException();
// }
// if (resp.getDeployParameters() == null || resp.getDeployParameters().get(0) == null) {
// throw new BadRequestException();
// }
resp = provisionService.save(resp);
return resp.getId();
}
@RequestMapping(value = "/scale", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String scaleDeployment(@RequestBody ScaleRequest scaleRequest) {
try {
return provisionService.scale(scaleRequest).getId();
} catch (IOException | TimeoutException | JSONException ex) {
Logger.getLogger(ProvisionController.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(ProvisionController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
@RequestMapping(value = "/sample", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
ProvisionRequest sample() {
ProvisionRequest req = new ProvisionRequest();
List<String> cloudCredentialsIDs = new ArrayList<>();
cloudCredentialsIDs.add("58f8d74f2af451b88c779d7a");
cloudCredentialsIDs.add("438dAFDf2ead451we8rf34Af");
req.setCloudCredentialsIDs(cloudCredentialsIDs);
List<String> keyPairIDs = new ArrayList<>();
keyPairIDs.add("58f8da042af45d6621813c4e");
req.setUserKeyPairIDs(keyPairIDs);
req.setPlanID("58da51f7f7b42e7d967752a1");
return req;
}
}
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import nl.uva.sne.drip.drip.commons.data.v1.external.ToscaRepresentation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.PathVariable;
import nl.uva.sne.drip.api.exception.BadRequestException;
import nl.uva.sne.drip.api.service.ConfigurationService;
import nl.uva.sne.drip.api.service.ToscaService;
import nl.uva.sne.drip.api.service.UserService;
import org.springframework.web.bind.annotation.RequestBody;
/**
* This controller is responsible for storing TOSCA descriptions that can be
* used by the planner.
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/user/v1.0/tosca")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class ToscaController {
@Autowired
private ToscaService toscaService;
@RequestMapping(value = "/post", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String post(@RequestBody String toscaContents) {
try {
return toscaService.saveStringContents(toscaContents, String.valueOf(System.currentTimeMillis()));
} catch (IOException ex) {
Logger.getLogger(ToscaController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Uploads and stores a TOSCA description file
*
* @param file. The TOSCA description file
* @return the ID of the TOSCA description
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String toscaUpload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
throw new BadRequestException("Must uplaod a file");
}
try {
return toscaService.saveFile(file);
} catch (IOException | IllegalStateException ex) {
Logger.getLogger(ToscaController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Gets the TOSCA description.
*
* @param id the ID TOSCA description.
* @param format. the format to display the TOSCA description.
* @return the TOSCA description.
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET, params = {"format"})
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String get(@PathVariable("id") String id, @RequestParam(value = "format") String format) {
try {
return toscaService.get(id, format);
} catch (JSONException ex) {
Logger.getLogger(ToscaController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Deletes the TOSCA description.
*
* @param id. The ID of TOSCA description to delete.
* @return The ID of the deleted TOSCA description.
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
String delete(@PathVariable("id") String id) {
toscaService.delete(id);
return "Deleted : " + id;
}
/**
* Gets the IDs of all the stored TOSCA descriptions.
*
* @return a list of all the IDs
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.USER, UserService.ADMIN})
public @ResponseBody
List<String> getIds() {
List<ToscaRepresentation> all = toscaService.findAll();
List<String> ids = new ArrayList<>();
for (ToscaRepresentation tr : all) {
ids.add(tr.getId());
}
return ids;
}
/**
* Gets the IDs of all the stored TOSCA descriptions.
*
* @return a list of all the IDs
*/
@RequestMapping(value = "/all", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
String deleteAll() {
toscaService.deleteAll();
return "Done";
}
}
/*
* Copyright 2017 S. Koulouzis, Wang Junchao, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import com.webcohesion.enunciate.metadata.rs.ResponseCode;
import com.webcohesion.enunciate.metadata.rs.StatusCodes;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.security.RolesAllowed;
import nl.uva.sne.drip.api.exception.PasswordNullException;
import nl.uva.sne.drip.api.exception.UserExistsException;
import nl.uva.sne.drip.api.exception.UserNotFoundException;
import nl.uva.sne.drip.api.exception.UserNullException;
import nl.uva.sne.drip.drip.commons.data.v1.external.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import nl.uva.sne.drip.api.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
/**
* This controller is responsible for handling user accounts
*
* @author S. Koulouzis
*/
@RestController
@RequestMapping("/manager/v1.0/user")
@Component
@StatusCodes({
@ResponseCode(code = 401, condition = "Bad credentials")
})
public class UserController {
@Autowired
private UserService service;
/**
* Register new user. A normal user cannot create accounts, only the user
* with the 'ADMIN' role can do that.
*
* @param user. The user to register
* @return Response on success: The ID of the newly register user. Response
* on fail: If the user name already exists, or the user name is 'null' or
* the password is 'null' there will be a 'BadRequestException'
*
*/
@RequestMapping(value = "/register", method = RequestMethod.POST)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
String register(@RequestBody User user) {
if (user.getUsername() == null) {
throw new UserNullException();
}
if (user.getPassword() == null) {
throw new PasswordNullException();
}
UserDetails registeredUser = service.loadUserByUsername(user.getUsername());
if (registeredUser != null) {
throw new UserExistsException("Username " + user.getUsername() + " is used");
}
user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
user = service.save(user);
return user.getId();
}
@RequestMapping(value = "/modify", method = RequestMethod.POST)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
String modify(@RequestBody User user) {
UserDetails registeredUser = service.loadUserByUsername(user.getUsername());
if (registeredUser == null) {
throw new UserNotFoundException("User " + user.getUsername() + " not found");
}
return this.register(user);
}
/**
* Gets the user.
*
* @param id. The ID of the user to retrive
* @return the requested user.
*/
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
User get(@PathVariable("id") String id) {
try {
User user = service.findOne(id);
if (user == null) {
throw new UserNotFoundException("User " + id + " not found");
}
return user;
} catch (Exception ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Deletes a user
*
* @param id. The ID of the user to delete
* @return The ID of the deleted user
*/
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
String delete(@PathVariable("id") String id) {
try {
User user = service.findOne(id);
if (user == null) {
throw new UserNotFoundException("User " + id + " not found");
}
service.delete(user);
return "Deleted : " + id;
} catch (Exception ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Gets the IDs of all the stored users
*
* @return a list of all the IDs
*/
@RequestMapping(value = "/ids", method = RequestMethod.GET)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
List<String> getIds() {
try {
List<User> all = service.findAll();
List<String> ids = new ArrayList<>();
for (User tr : all) {
ids.add(tr.getId());
}
return ids;
} catch (Exception ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
@RequestMapping(value = "/all", method = RequestMethod.GET)
@RolesAllowed({UserService.ADMIN})
public @ResponseBody
List<User> getAll() {
try {
return service.findAll();
} catch (Exception ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
/*
* Copyright 2019 S. Koulouzis, Huan Zhou, Yang Hu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.manager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
*
* @author S. Koulouzis
*/
@SpringBootApplication
public class Manager {
public static void main(String[] args) {
SpringApplication.run(Manager.class, args);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="classpath:/drip-context-rest.xml" />
<context:component-scan base-package="nl.uva.sne.drip" />
</beans>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
\ No newline at end of file
message.broker.host=127.0.0.1
db.host=127.0.0.1
db.name=drip
db.username=drip-user
db.password=drip-pass
# LOG4J Configuration
# ===================
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=FINE, A1
log4j.logger.httpclient.wire.header=OFF
log4j.logger.httpclient.wire.content=OFF
log4j.logger.org.globus=OFF
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{HH:mm:ss,SSS} (%t) %-5p [%c] - %m%n
\ No newline at end of file
handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler
nl.uva.cs.level = FINE
############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################
org.apache.juli.FileHandler.level = FINE
org.apache.juli.FileHandler.directory = ${catalina.base}/logs
java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/drip-api"/>
/*
* Copyright 2017 S. Koulouzis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package nl.uva.sne.drip.api.v1.rest;
import java.io.File;
import java.io.IOException;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.net.URI;
import java.net.URISyntaxException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.HttpClientBuilder;
import static org.junit.Assert.assertEquals;
/**
*
* @author S. Koulouzis
*/
public class TestCloudCredentialsController {
private static URI url;
private static File toscaFile;
public TestCloudCredentialsController() {
}
@BeforeClass
public static void setUpClass() throws URISyntaxException {
url = new URI("http://localhost:8080/drip-api/user/v1.0/credentials/cloud/");
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testPostCredentials() throws IOException {
}
}
swagger: "2.0"
info:
description: "The Dynamic Real-time infrastructure planner (DRIP) allows application developers to seamlessly plan a customized virtual infrastructure based on application level constraints on QoS and resource budgets, provisioning the virtual infrastructure using standardized interfaces (e.g., TOSCA and OCCI), deploy application components onto the virtual infrastructure, and start execution on demand."
version: "3.0.0"
title: "DRIP manager"
license:
name: "Apache 2.0"
url: "http://www.apache.org/licenses/LICENSE-2.0.html"
host: "localhost:8080"
basePath: "/v3"
schemes:
- "https"
- "http"
paths:
/planner:
post:
description: "Uploads a TOSCA definition"
consumes:
- "multipart/form-data"
produces:
- "application/xml"
- "application/json"
parameters:
- in: formData
name: file
required: true
type: file
description: The TOSCA file
x-mimetype:
- application/x-yaml
- text/yaml
responses:
405:
description: "Invalid TOSCA file"
200:
description: "Upload Successful"
/* Knowledge bus basic (JSON-only) implementation.
* Paul Martin, 2/2/17.
*/
:- use_module(library(http/http_unix_daemon)).
:- use_module(library('http/thread_httpd')).
:- use_module(library('http/http_dispatch')).
:- use_module(library('http/http_json')).
:- use_module(library('http/http_header')).
:- use_module(library('http/http_client')).
:- use_module(library('http/html_write')).
:- initialization http_daemon.
/* Servlet structure:
/ : landing page for the knowledge base.
/profiles : landing page for the information profile collection.
GET : retrieve a JSON catalogue of all information profiles.
POST : upload a JSON information profile; returns the identifier in JSON format.
DELETE : purge the knowledge base.
/profiles/{id} : landing page for a specific information profile.
GET : retrieve the information profile in JSON format.
PUT : replace the information profile with another JSON description.
DELETE : remove the information profile from the knowledge base. */
% The handler predicates for the different facets of the servlet.
:- http_handler(root(.), drip_handler, []).
:- http_handler(root('profiles'), profiles_handler, []).
% info_profile(?Key, ?Type, ?Dict)---describes an information profile as a dictionary.
% ?Key---a unique UUID.
% ?Type---the kind of profile: adaptation, application, cloud, component, control, infrastructure, monitoring.
% ?Dict---a dictionary generated by json_write_dict/2.
dynamic info_profile/3.
% server(+Port)---initialises the HTTP server.
% +Port---the port via which the server can be accessed.
server(Port) :-
http_server(http_dispatch, [port(Port)]).
% drip_handler(+Request)---handles requests to the root of the servlet.
% +Request---a HTTP request.
drip_handler(_) :-
reply_html_page( title('DRIP knowledge base'),
[ h1('DRIP knowledge base'),
p('A simple knowledge base for storing information objects needed by the DRIP system.') ] ).
% profile_list_handler(+Request)---handles requests to the profiles collection facet of the servlet.
% +Request---a HTTP request.
profiles_handler(Request) :-
% If a POST request is received...
memberchk(method(post), Request), !,
( http_read_json_dict(Request, Dict)
;
throw( http_reply(bad_request("No content type info: should be 'application/json'.")) )
),
( info_type(Type, Dict),
uuid(Key),
assert( info_profile(Key, Type, Dict) )
;
throw( http_reply(server_error("Unable to modify knowledge base!")) )
),
( atom_concat('profiles/', Key, Location),
http_handler(root(Location), profile_handler(Key), [])
;
throw( http_reply(server_error("Unable to create resource page for profile.")) )
),
dict_create(Reply, _, [identifier(Key)]),
reply_json_dict(Reply, [status(201)]).
profiles_handler(Request) :-
% If a DELETE request is received...
memberchk(method(delete), Request), !,
retractall(info_profile(_, _, _)),
format('Content-type: text/plain~n~n'),
format('All information profiles deleted.').
profiles_handler(Request) :-
% If a GET request is received...
memberchk(method(get), Request), !,
catch( findall(Key, info_profile(Key, _, _), Keys), _, Keys = [] ),
dict_create(Reply, _, [identifiers(Keys)]),
reply_json_dict(Reply).
profiles_handler(_) :-
% Otherwise report an error.
format('Status: 403~n'),
format('Content-type: text/plain~n~n'),
format('This request is not permitted for the URL given.').
% profile_handler(+Key, +Request)---handles requests regarding individual profiles.
% +Key---a UUID for a profile.
% +Request---a HTTP request.
profile_handler(Key, Request) :-
% If a PUT request is received...
memberchk(method(put), Request), !,
catch( info_profile(Key, Type, Dict), _, throw( http_reply(server_error("The information associated with this UUID appears to be missing.")) ) ),
( http_read_json_dict(Request, NewDict)
;
throw( http_reply(bad_request("No content type info: should be 'application/json'.")) )
),
( retract( info_profile(Key, Type, Dict) ),
assert( info_profile(Key, Type, NewDict) )
;
throw( http_reply(server_error("Unable to modify knowledge base!")) )
),
dict_create(Reply, _, [identifier(Key)]),
reply_json_dict(Reply).
profile_handler(Key, Request) :-
% If a GET request is received...
memberchk(method(get), Request), !,
catch( info_profile(Key, _, Dict), _, throw( http_reply(server_error("The information associated with this UUID appears to be missing.")) ) ),
reply_json_dict(Dict).
profile_handler(Key, Request) :-
% If a DELETE request is received...
memberchk(method(delete), Request), !,
catch( info_profile(Key, Type, Dict), _, throw( http_reply(server_error("The information associated with this UUID appears to be missing.")) ) ),
( retract( info_profile(Key, Type, Dict) )
;
throw( http_reply(not_modified("Unable to modify knowledge base!")) )
),
atom_concat('profiles/', Key, Location),
http_delete_handler(root(Location)),
format('Content-type: text/plain~n~n'),
format('The information profile with UUID ~q has been deleted.', [Key]).
profile_handler(Key, Request) :-
% If a POST request is received...
member(method(post), Request), !,
format('Status: 409~n'),
format('Content-type: text/plain~n~n'),
format('Profile with UUID ~q already exists (use PUT to update an existing profile, or POST to ./profiles to generate a new profile with a new UUID).', [Key]).
profile_handler(_, _) :-
% Otherwise report an error.
format('Status: 403~n'),
format('Content-type: text/plain~n~n'),
format('This request is not permitted for the URL given.').
% info_type(?Type, +Dict)---determines if a given profile is of a given type.
% ?Type---the type of the profile.
% +Dict---the dictionary describing the profile.
info_type(adaptation, Dict) :- _ = Dict.get('adaptation profile').
info_type(application, Dict) :- _ = Dict.get('application profile').
info_type(cloud, Dict) :- _ = Dict.get('cloud profile').
info_type(component, Dict) :- _ = Dict.get('component profile').
info_type(control, Dict) :- _ = Dict.get('control profile').
info_type(infrastructure, Dict) :- _ = Dict.get('infrastructure profile').
info_type(monitoring, Dict) :- _ = Dict.get('monitoring profile').
info_type(misc, _).
%:- server(8080).
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment