View Javadoc
1   /*
2    * Copyright (c) 2016 ingenieux Labs
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package br.com.ingenieux.mojo.beanstalk.bundle;
18  
19  import com.amazonaws.services.lambda.AWSLambda;
20  import com.amazonaws.services.lambda.AWSLambdaClient;
21  import com.amazonaws.services.lambda.model.InvokeRequest;
22  import com.amazonaws.services.lambda.model.InvokeResult;
23  import com.fasterxml.jackson.core.type.TypeReference;
24  import com.fasterxml.jackson.databind.node.ObjectNode;
25  
26  import org.apache.maven.plugin.MojoFailureException;
27  import org.apache.maven.plugins.annotations.Mojo;
28  import org.apache.maven.plugins.annotations.Parameter;
29  import org.eclipse.jgit.api.Git;
30  import org.eclipse.jgit.lib.Repository;
31  import org.eclipse.jgit.lib.RepositoryBuilder;
32  import org.eclipse.jgit.lib.TextProgressMonitor;
33  import org.eclipse.jgit.transport.RefSpec;
34  
35  import java.io.File;
36  import java.util.Date;
37  import java.util.List;
38  
39  import static br.com.ingenieux.mojo.aws.util.CredentialsUtil.redact;
40  import static java.lang.String.format;
41  import static org.apache.commons.lang.StringUtils.isNotBlank;
42  
43  /**
44   * Uploads a packed war file to Amazon S3 for further Deployment.
45   *
46   * @since 0.2.8
47   */
48  @Mojo(name = "codecommit-fast-deploy")
49  public class CodeCommitFastDeployMojo extends FastDeployMojo {
50    @Parameter(property = "beanstalk.codeCommitRepoName", defaultValue = "${project.artifactId}-blobs")
51    String repoName;
52  
53    @Override
54    protected void configure() {
55      super.configure();
56    }
57  
58    @Override
59    protected String getRemoteUrl(String commitId, String environmentName) throws MojoFailureException {
60      return new CodeCommitRequestSigner(getAWSCredentials(), repoName, new Date()).getPushUrl();
61    }
62  
63    @Override
64    protected Git getGitRepo() throws Exception {
65      if (stagingDirectory.exists() && new File(stagingDirectory, "HEAD").exists()) {
66        Git git = Git.open(stagingDirectory);
67  
68        git.fetch().setRemote(getRemoteUrl(null, null)).setProgressMonitor(new TextProgressMonitor()).setRefSpecs(new RefSpec("refs/heads/master")).call();
69      } else {
70        Git.cloneRepository()
71            .setURI(getRemoteUrl(null, null))
72            .setProgressMonitor(new TextProgressMonitor())
73            .setDirectory(stagingDirectory)
74            .setNoCheckout(true)
75            .setBare(true)
76            .call();
77      }
78  
79      Repository r = null;
80  
81      RepositoryBuilder b = new RepositoryBuilder().setGitDir(stagingDirectory).setWorkTree(sourceDirectory);
82  
83      r = b.build();
84  
85      final Git git = Git.wrap(r);
86  
87      return git;
88    }
89  
90    @Override
91    protected String lookupVersionLabelForCommitId(String commitId) throws Exception {
92      String s3Bucket = getService().createStorageLocation().getS3Bucket();
93  
94      ObjectNode payload = objectMapper.createObjectNode();
95  
96      payload.put("applicationName", applicationName);
97  
98      payload.put("commitId", commitId);
99  
100     payload.put("repoName", repoName);
101 
102     payload.put("description", versionDescription);
103 
104     payload.put("accessKey", getAWSCredentials().getCredentials().getAWSAccessKeyId());
105 
106     payload.put("secretKey", getAWSCredentials().getCredentials().getAWSSecretKey());
107 
108     payload.put("region", getRegion().getName());
109 
110     payload.put("targetPath", format("s3://%s/apps/%s/versions/git-%s.zip", s3Bucket, applicationName, commitId));
111 
112     AWSLambda lambda = getClientFactory().getService(AWSLambdaClient.class);
113 
114     final String payloadAsString = objectMapper.writeValueAsString(payload);
115 
116     getLog().info("Calling beanstalk-codecommit-deployer with arguments set to: " + redact(payloadAsString));
117 
118     final InvokeResult invoke = lambda.invoke(new InvokeRequest().withFunctionName("beanstalker-codecommit-deployer").withPayload(payloadAsString));
119 
120     String resultAsString = new String(invoke.getPayload().array(), "utf-8");
121 
122     if (isNotBlank(invoke.getFunctionError())) {
123       final String errorMessage = "Unexpected: " + invoke.getFunctionError();
124 
125       getLog().info(errorMessage);
126 
127       throw new RuntimeException(errorMessage);
128     } else {
129       List<String> messages = objectMapper.readValue(resultAsString, new TypeReference<List<String>>() {});
130 
131       for (String m : messages) {
132         getLog().info(m);
133       }
134     }
135 
136     return super.lookupVersionLabelForCommitId(commitId);
137   }
138 }