Move Ddi client

Signed-off-by: SirWayne <dennis.melzer@bosch-si.com>
This commit is contained in:
SirWayne
2016-05-18 15:39:47 +02:00
parent f02485129e
commit 27721c7cf8
12 changed files with 10 additions and 615 deletions

View File

@@ -38,51 +38,32 @@
<artifactId>hawkbit-example-core-feign-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-ddi-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-ddi-dl-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<groupId>org.eclipse.hawkbit</groupId>
<artifactId>hawkbit-ddi-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-core</artifactId>
<!-- need to overwrite for the interface inheritance feature of feign-core -->
</dependency>
<dependency>
<groupId>com.netflix.feign</groupId>
<artifactId>feign-jackson</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<!-- <scope>provided</scope> -->
</dependency>
<dependency>
<groupId>org.springframework.plugin</groupId>
<artifactId>spring-plugin-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<!-- Move to parent or use different framework -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
</dependencies>
</project>

View File

@@ -1,54 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.client;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map;
import org.springframework.cloud.netflix.feign.support.ResponseEntityDecoder;
import org.springframework.hateoas.hal.Jackson2HalModule;
import org.springframework.http.ResponseEntity;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.Response;
import feign.codec.Decoder;
import feign.jackson.JacksonDecoder;
/**
* Decoder for DDI client.
*
*/
public class DdiDecoder implements Decoder {
private static final String OCTET_STREAM = "[application/octet-stream]";
private final ObjectMapper mapper;
public DdiDecoder() {
mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(new Jackson2HalModule());
}
@Override
public Object decode(final Response response, final Type type) throws IOException {
final Map<String, Collection<String>> header = response.headers();
final String contentType = String.valueOf(header.get("Content-Type"));
if (contentType.equals(OCTET_STREAM)) {
return ResponseEntity.ok(response.body().asInputStream());
}
final ResponseEntityDecoder responseEntityDecoder = new ResponseEntityDecoder(new JacksonDecoder(mapper));
return responseEntityDecoder.decode(response, type);
}
}

View File

@@ -1,94 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.client;
import org.apache.commons.lang.Validate;
import org.eclipse.hawkbit.ddi.client.authenctication.AuthenticationInterceptor;
import org.eclipse.hawkbit.ddi.client.resource.RootControllerResourceClient;
import org.eclipse.hawkbit.ddi.client.resource.RootControllerResourceClientConstants;
import org.eclipse.hawkbit.feign.core.client.ApplicationJsonRequestHeaderInterceptor;
import org.eclipse.hawkbit.feign.core.client.IgnoreMultipleConsumersProducersSpringMvcContract;
import feign.Feign;
import feign.Feign.Builder;
import feign.Logger;
import feign.Logger.Level;
import feign.jackson.JacksonEncoder;
/**
* Default implementation of DDI client.
*/
public class DdiDefaultFeignClient {
private RootControllerResourceClient rootControllerResourceClient;
private final Builder feignBuilder;
private final String baseUrl;
private final String tenant;
/**
* Constructor for default DDI feign client with no authentication.
*
* @param baseUrl
* the base url of the client
* @param tenant
* the tenant
*/
public DdiDefaultFeignClient(final String baseUrl, final String tenant) {
this(baseUrl, tenant, null);
}
/**
* Constructor for default DDI feign client with authentication.
*
* @param baseUrl
* the base url of the client
* @param tenant
* the tenant
* @param authenticationInterceptor
*/
public DdiDefaultFeignClient(final String baseUrl, final String tenant,
final AuthenticationInterceptor authenticationInterceptor) {
feignBuilder = Feign.builder().contract(new IgnoreMultipleConsumersProducersSpringMvcContract())
.requestInterceptor(new ApplicationJsonRequestHeaderInterceptor()).logLevel(Level.FULL)
.logger(new Logger.ErrorLogger()).encoder(new JacksonEncoder()).decoder(new DdiDecoder());
if (authenticationInterceptor != null) {
feignBuilder.requestInterceptor(authenticationInterceptor);
}
Validate.notNull(baseUrl, "A baseUrl has to be set");
Validate.notNull(tenant, "A tenant has to be set");
this.baseUrl = baseUrl;
this.tenant = tenant;
}
/**
* Get the feign builder.
*
* @return the feign builder
*/
public Builder getFeignBuilder() {
return feignBuilder;
}
/**
* Get the rootController resource client.
*
* @return the rootController resource client
*/
public RootControllerResourceClient getRootControllerResourceClient() {
if (rootControllerResourceClient == null) {
String rootControllerResourcePath = this.baseUrl + RootControllerResourceClientConstants.PATH;
rootControllerResourcePath = rootControllerResourcePath.replace("{tenant}", tenant);
rootControllerResourceClient = feignBuilder.target(RootControllerResourceClient.class,
rootControllerResourcePath);
}
return rootControllerResourceClient;
}
}

View File

@@ -1,232 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.client;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoField;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.eclipse.hawkbit.ddi.client.authenctication.AuthenticationInterceptor;
import org.eclipse.hawkbit.ddi.client.resource.RootControllerResourceClient;
import org.eclipse.hawkbit.ddi.client.strategy.ArtifactsPersistenceStrategy;
import org.eclipse.hawkbit.ddi.json.model.DdiActionFeedback;
import org.eclipse.hawkbit.ddi.json.model.DdiArtifact;
import org.eclipse.hawkbit.ddi.json.model.DdiChunk;
import org.eclipse.hawkbit.ddi.json.model.DdiControllerBase;
import org.eclipse.hawkbit.ddi.json.model.DdiDeploymentBase;
import org.eclipse.hawkbit.ddi.json.model.DdiResult;
import org.eclipse.hawkbit.ddi.json.model.DdiResult.FinalResult;
import org.eclipse.hawkbit.ddi.json.model.DdiStatus;
import org.eclipse.hawkbit.ddi.json.model.DdiStatus.ExecutionStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.hateoas.Link;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* DDI example client based on defualt DDI feign client.
*/
public class DdiExampleClient implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(DdiExampleClient.class);
private final String controllerId;
private Long actionIdOfLastInstalltion;
private final RootControllerResourceClient rootControllerResourceClient;
private final ArtifactsPersistenceStrategy persistenceStrategy;
private DdiClientStatus clientStatus;
private FinalResult finalResultOfCurrentUpdate;
/**
* Constructor for the DDI example client.
*
* @param baseUrl
* the base url of the hawkBit server
* @param controllerId
* the controller id that will be simulated
* @param tenant
* the tenant
* @param persistenceStrategy
* the persistence strategy for downloading artifacts
*/
public DdiExampleClient(final String baseUrl, final String controllerId, final String tenant,
final ArtifactsPersistenceStrategy persistenceStrategy) {
this(baseUrl, controllerId, tenant, persistenceStrategy, null);
}
/**
* Constructor for the DDI example client.
*
* @param baseUrl
* the base url of the hawkBit server
* @param controllerId
* the controller id that will be simulated
* @param tenant
* the tenant
* @param persistenceStrategy
* the persistence strategy for downloading artifacts
* @param authenticationInterceptor
* the authentication intercepter to authenticate the DDI client,
* might be {@code null}
*/
public DdiExampleClient(final String baseUrl, final String controllerId, final String tenant,
final ArtifactsPersistenceStrategy persistenceStrategy,
final AuthenticationInterceptor authenticationInterceptor) {
this.controllerId = controllerId;
this.rootControllerResourceClient = new DdiDefaultFeignClient(baseUrl, tenant, authenticationInterceptor)
.getRootControllerResourceClient();
this.actionIdOfLastInstalltion = null;
this.persistenceStrategy = persistenceStrategy;
this.clientStatus = DdiClientStatus.DOWN;
}
@Override
public void run() {
clientStatus = DdiClientStatus.UP;
ResponseEntity<DdiControllerBase> response;
while (clientStatus == DdiClientStatus.UP) {
LOGGER.info(" Controller {} polling from hawkBit server", controllerId);
response = rootControllerResourceClient.getControllerBase(controllerId);
final String pollingTimeFormReponse = response.getBody().getConfig().getPolling().getSleep();
final LocalTime localtime = LocalTime.parse(pollingTimeFormReponse);
final long pollingIntervalInMillis = localtime.getLong(ChronoField.MILLI_OF_DAY);
final Link controllerDeploymentBaseLink = response.getBody().getLink("deploymentBase");
if (controllerDeploymentBaseLink != null) {
final Long actionId = getActionIdOutOfLink(controllerDeploymentBaseLink);
final Integer resource = getResourceOutOfLink(controllerDeploymentBaseLink);
if (actionId != actionIdOfLastInstalltion) {
finalResultOfCurrentUpdate = FinalResult.NONE;
startDownload(actionId, resource);
finishUpdateProcess(actionId);
actionIdOfLastInstalltion = actionId;
}
}
try {
Thread.sleep(pollingIntervalInMillis);
} catch (final InterruptedException e) {
LOGGER.error("Error during sleep");
}
}
}
/**
* Stop the DDI example client
*/
public void stop() {
clientStatus = DdiClientStatus.DOWN;
}
private void startDownload(final Long actionId, final Integer resource) {
final ResponseEntity<DdiDeploymentBase> respone = rootControllerResourceClient
.getControllerBasedeploymentAction(controllerId, actionId, resource);
final DdiDeploymentBase ddiDeploymentBase = respone.getBody();
final List<DdiChunk> chunks = ddiDeploymentBase.getDeployment().getChunks();
for (final DdiChunk chunk : chunks) {
downloadArtifacts(chunk, actionId);
}
}
private void downloadArtifacts(final DdiChunk chunk, final Long actionId) {
final List<DdiArtifact> artifactList = chunk.getArtifacts();
if (artifactList.isEmpty()) {
sendFeedBackMessage(actionId, ExecutionStatus.PROCEEDING, FinalResult.NONE,
"No artifacts to download for softwaremodule " + chunk.getName());
return;
}
for (final DdiArtifact ddiArtifact : artifactList) {
if (finalResultOfCurrentUpdate != FinalResult.FAILURE) {
downloadArtifact(actionId, ddiArtifact);
}
}
}
private void downloadArtifact(final Long actionId, final DdiArtifact ddiArtifact) {
final String artifact = ddiArtifact.getFilename();
final Link downloadLink = ddiArtifact.getLink("download-http");
final String[] downloadLinkSep = downloadLink.getHref().split(Pattern.quote("/"));
final Long softwareModuleId = Long.valueOf(downloadLinkSep[8]);
sendFeedBackMessage(actionId, ExecutionStatus.PROCEEDING, FinalResult.NONE,
"Starting download of artifact " + artifact);
LOGGER.info("Starting download of artifact " + artifact);
final ResponseEntity<InputStream> responseDownloadArtifact = rootControllerResourceClient
.downloadArtifact(controllerId, softwareModuleId, artifact);
final HttpStatus statsuCode = responseDownloadArtifact.getStatusCode();
LOGGER.info("Finished download with stataus {}", statsuCode);
try {
persistenceStrategy.handleInputStream(responseDownloadArtifact.getBody(), artifact);
sendFeedBackMessage(actionId, ExecutionStatus.PROCEEDING, FinalResult.NONE,
"Downloaded artifact " + artifact);
} catch (final IOException e) {
LOGGER.error("Download of artifact failed", e);
sendFeedBackMessage(actionId, ExecutionStatus.PROCEEDING, FinalResult.NONE,
"Download of artifact " + artifact + "failed");
finalResultOfCurrentUpdate = FinalResult.FAILURE;
}
}
private void sendFeedBackMessage(final Long actionId, final ExecutionStatus executionStatus,
final FinalResult finalResult, final String message) {
final DdiResult result = new DdiResult(finalResult, null);
final List<String> details = new ArrayList<>();
details.add(message);
final DdiStatus ddiStatus = new DdiStatus(executionStatus, result, details);
final String time = String.valueOf(LocalDateTime.now());
final DdiActionFeedback feedback = new DdiActionFeedback(actionId, time, ddiStatus);
rootControllerResourceClient.postBasedeploymentActionFeedback(feedback, controllerId, actionId);
LOGGER.info("Sent feedback message to HaktBit");
}
private void finishUpdateProcess(final Long actionId) {
if (finalResultOfCurrentUpdate == FinalResult.FAILURE) {
sendFeedBackMessage(actionId, ExecutionStatus.CLOSED, FinalResult.FAILURE, "Error during update process");
}
if (finalResultOfCurrentUpdate == FinalResult.NONE) {
sendFeedBackMessage(actionId, ExecutionStatus.CLOSED, FinalResult.SUCESS,
"Simulated installation successful");
}
}
private Long getActionIdOutOfLink(final Link controllerDeploymentBaseLink) {
final String[] ending = splitControllerDeploymentBaseLinkInActionIdAndResource(controllerDeploymentBaseLink);
return Long.valueOf(ending[0]);
}
private Integer getResourceOutOfLink(final Link controllerDeploymentBaseLink) {
final String[] ending = splitControllerDeploymentBaseLinkInActionIdAndResource(controllerDeploymentBaseLink);
return Integer.valueOf(ending[1].substring(2));
}
private String[] splitControllerDeploymentBaseLinkInActionIdAndResource(final Link controllerDeploymentBaseLink) {
final String link = controllerDeploymentBaseLink.getHref();
final String[] segments = link.split(Pattern.quote("/"));
return segments[8].split(Pattern.quote("?"));
}
/**
* Enum for DDI running status.
*/
public enum DdiClientStatus {
UP, DOWN;
}
}

View File

@@ -1,19 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.client.authenctication;
import feign.RequestInterceptor;
/**
* An DdiClient authentication intercepter to provide credential information
* e.g. in http-headers.
*/
public interface AuthenticationInterceptor extends RequestInterceptor {
}

View File

@@ -1,34 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.client.authenctication;
/**
* A factory to create {@link AuthenticationInterceptor}s.
*/
public class AuthenticationInterceptorFactory {
private AuthenticationInterceptorFactory() {
// factory class no public constructor
}
/**
* Creates a new {@link AuthenticationInterceptor} to authenticate a
* Ddi-Client via a target-security-token HTTP authorization header.
*
* @param targetSecurityToken
* the target-security-token to be added to the HTTP
* 'TargetToken' authorization header
* @return the authentication interceptor which can be used to authenticate
* an Ddi-Client
*/
public static AuthenticationInterceptor createTargetSecurityAuthenticator(final String targetSecurityToken) {
return new TargetSecurityTokenAuthenticationInterceptor(targetSecurityToken);
}
}

View File

@@ -1,35 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.client.authenctication;
import com.google.common.net.HttpHeaders;
import feign.RequestTemplate;
/**
* Implementation of the {@link AuthenticationInterceptor} to add a given
* target-security-token to the HTTP authorization header.
*/
class TargetSecurityTokenAuthenticationInterceptor implements AuthenticationInterceptor {
private final String targetSecurityToken;
/**
* @param targetSecurityToken
* the security token to add to the authorization header
*/
TargetSecurityTokenAuthenticationInterceptor(final String targetSecurityToken) {
this.targetSecurityToken = targetSecurityToken;
}
@Override
public void apply(final RequestTemplate template) {
template.header(HttpHeaders.AUTHORIZATION, "TargetToken " + targetSecurityToken);
}
}

View File

@@ -8,13 +8,14 @@
*/
package org.eclipse.hawkbit.ddi.client.resource;
import org.eclipse.hawkbit.ddi.rest.api.DdiRestConstants;
import org.eclipse.hawkbit.ddi.rest.api.DdiRootControllerRestApi;
import org.springframework.cloud.netflix.feign.FeignClient;
/**
* Client binding for the Rootcontroller resource of the DDI API.
*/
@FeignClient(url = "${hawkbit.url:localhost:8080}/" + RootControllerResourceClientConstants.PATH)
@FeignClient(url = "${hawkbit.url:localhost:8080}/" + DdiRestConstants.BASE_V1_REQUEST_MAPPING)
public interface RootControllerResourceClient extends DdiRootControllerRestApi {
}

View File

@@ -1,26 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.client.resource;
/**
*
* Constants for RootController resource client.
*/
public class RootControllerResourceClientConstants {
public static final String PATH = "{tenant}/controller/v1";
/**
* Private constructor to prevent instantiation.
*/
private RootControllerResourceClientConstants() {
}
}

View File

@@ -1,31 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.client.strategy;
import java.io.IOException;
import java.io.InputStream;
/**
* Interface of persistence strategy.
*/
@FunctionalInterface
public interface ArtifactsPersistenceStrategy {
/**
* Method handling the artifact download.
*
* @param in
* the input stream
* @param artifactName
* the name of the artifact
* @throws IOException
*/
public void handleInputStream(InputStream in, String artifactName) throws IOException;
}

View File

@@ -1,28 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.client.strategy;
import java.io.IOException;
import java.io.InputStream;
/**
* Implementation of {@link ArtifactsPersistenceStrategy} for not downloading
* any artifacts.
*/
public class DoNotSaveArtifacts implements ArtifactsPersistenceStrategy {
@Override
public void handleInputStream(final InputStream in, final String artifactName) throws IOException {
while (in.read() != -1) {
;
}
}
}

View File

@@ -1,34 +0,0 @@
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.ddi.client.strategy;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;
/**
* Implementation of {@link ArtifactsPersistenceStrategy} for downloading
* artifacts to the temp directory.
*/
public class SaveArtifactsToLocalTempDirectories implements ArtifactsPersistenceStrategy {
@Override
public void handleInputStream(final InputStream in, final String artifactName) throws IOException {
final File tempDir = Files.createTempDir();
final File file = new File(tempDir, artifactName);
final OutputStream out = new FileOutputStream(file);
ByteStreams.copy(in, out);
}
}