Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: refactor the code using different implementation and design refa… #194

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@

import org.gradle.api.GradleException;
import org.gradle.api.internal.ConventionTask;
import org.gradle.api.tasks.TaskAction;

import com.amazonaws.services.ec2.model.IpPermission;

Expand Down Expand Up @@ -94,4 +95,14 @@ protected Collection<IpPermission> parse(Object e) { // NOPMD
}
}).collect(Collectors.toList());
}

@TaskAction
protected void checkGroupsAndIpPermissions(String groupId, String groupName, Object ipPermissions) {
if (groupId == null && groupName == null) {
throw new GradleException("groupId nor groupName is not specified");
}
if (ipPermissions == null) {
throw new GradleException("ipPermissions is not specified");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import lombok.Getter;
import lombok.Setter;

import org.gradle.api.GradleException;
import org.gradle.api.tasks.TaskAction;

import com.amazonaws.AmazonServiceException;
Expand Down Expand Up @@ -52,12 +51,7 @@ public void authorizeIngress() {
String groupName = getGroupName();
Object ipPermissions = getIpPermissions();

if (groupId == null && groupName == null) {
throw new GradleException("groupId nor groupName is not specified");
}
if (ipPermissions == null) {
throw new GradleException("ipPermissions is not specified");
}
checkGroupsAndIpPermissions(groupId, groupName, ipPermissions);

AmazonEC2PluginExtension ext = getProject().getExtensions().getByType(AmazonEC2PluginExtension.class);
AmazonEC2 ec2 = ext.getClient();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import lombok.Getter;
import lombok.Setter;

import org.gradle.api.GradleException;
import org.gradle.api.tasks.TaskAction;

import com.amazonaws.AmazonServiceException;
Expand Down Expand Up @@ -52,12 +51,7 @@ public void revokeIngress() {
String groupName = getGroupName();
Object ipPermissions = getIpPermissions();

if (groupId == null && groupName == null) {
throw new GradleException("groupId nor groupName is not specified");
}
if (ipPermissions == null) {
throw new GradleException("ipPermissions is not specified");
}
checkGroupsAndIpPermissions(groupId, groupName, ipPermissions);

AmazonEC2PluginExtension ext = getProject().getExtensions().getByType(AmazonEC2PluginExtension.class);
AmazonEC2 ec2 = ext.getClient();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,31 +60,44 @@ public AmazonIdentityManagementCreateRoleTask() {
@TaskAction
public void createRole() {
// to enable conventionMappings feature
String roleName = getRoleName();
String assumeRolePolicyDocument = getAssumeRolePolicyDocument();

if (roleName == null) {
checkRoleParams();
AmazonIdentityManagementPluginExtension ext =
getProject().getExtensions().getByType(AmazonIdentityManagementPluginExtension.class);
AmazonIdentityManagement iam = ext.getClient();
createRole = createIAMRole(iam);
getLogger().info("Create Role requested: {}", createRole.getRole().getArn());
attachPoliciesToRole(iam);
}

@TaskAction
private void checkRoleParams() { // NOPMD
// to enable conventionMappings feature
if (getRoleName() == null) {
throw new GradleException("roleName is required");
}
if (assumeRolePolicyDocument == null) {
if (getAssumeRolePolicyDocument() == null) {
throw new GradleException("assumeRolePolicyDocument is required");
}
AmazonIdentityManagementPluginExtension ext =
getProject().getExtensions().getByType(AmazonIdentityManagementPluginExtension.class);
AmazonIdentityManagement iam = ext.getClient();

}

@TaskAction
private CreateRoleResult createIAMRole(AmazonIdentityManagement iam) { // NOPMD
// to enable conventionMappings feature
CreateRoleRequest request = new CreateRoleRequest()
.withRoleName(roleName)
.withRoleName(getRoleName())
.withPath(getPath())
.withAssumeRolePolicyDocument(assumeRolePolicyDocument);
createRole = iam.createRole(request);
getLogger().info("Create Role requested: {}", createRole.getRole().getArn());
.withAssumeRolePolicyDocument(getAssumeRolePolicyDocument());
return iam.createRole(request);
}

@TaskAction
private void attachPoliciesToRole(AmazonIdentityManagement iam) { // NOPMD
// to enable conventionMappings feature
policyArns.stream().forEach(policyArn -> {
iam.attachRolePolicy(new AttachRolePolicyRequest()
.withRoleName(roleName)
.withRoleName(getRoleName())
.withPolicyArn(policyArn));
getLogger().info("Attach Managed policy {} to Role {} requested", policyArn, roleName);
getLogger().info("Attach Managed policy {} to Role {} requested", policyArn, getRoleName());
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
*/
package jp.classmethod.aws.gradle.lambda;

import static groovy.lang.Closure.DELEGATE_FIRST;

import lombok.Getter;
import lombok.Setter;

Expand All @@ -29,8 +27,6 @@
import com.amazonaws.services.lambda.model.CreateAliasRequest;
import com.amazonaws.services.lambda.model.CreateAliasResult;

import groovy.lang.Closure;

/**
* Created by frankfarrell on 16/01/2018.
* https://docs.aws.amazon.com/cli/latest/reference/lambda/create-alias.html
Expand Down Expand Up @@ -119,12 +115,4 @@ private AWSLambda getAwsLambdaClient() {
return ext.getClient();
}

public void routingConfig(final Closure<RoutingConfig> c) {
c.setResolveStrategy(DELEGATE_FIRST);
if (routingConfig == null) {
routingConfig = new RoutingConfig();
}
c.setDelegate(routingConfig);
c.call();
}
}
45 changes: 23 additions & 22 deletions src/main/java/jp/classmethod/aws/gradle/lambda/RoutingConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/
package jp.classmethod.aws.gradle.lambda;

import static groovy.lang.Closure.DELEGATE_FIRST;

import java.util.Collections;

import lombok.Getter;
Expand All @@ -26,6 +28,8 @@

import com.amazonaws.services.lambda.model.AliasRoutingConfiguration;

import groovy.lang.Closure;

/**
* Created by frankfarrell on 16/01/2018.
*
Expand Down Expand Up @@ -62,6 +66,14 @@ public class RoutingConfig {
@Setter
private String additionalVersion;

@Getter
@Setter
private RoutingConfig routingConfig;

@Getter
@Setter
private Version version;


protected RoutingConfig() {
/*
Expand All @@ -80,36 +92,30 @@ public AliasRoutingConfiguration getAliasRoutingConfiguration(final String funct
final AliasRoutingConfiguration aliasRoutingConfiguration = new AliasRoutingConfiguration();

if (getAdditionalVersion() != null) {
validateFunctionVersion(getAdditionalVersion());
version.validateFunctionVersion(getAdditionalVersion());

aliasRoutingConfiguration.withAdditionalVersionWeights(
Collections.singletonMap(getAdditionalVersion(), additionalVersionWeight));
} else if (getUsePreviousVersion() != null && getUsePreviousVersion()) {

validateFunctionVersion(functionVersion);
version.validateFunctionVersion(functionVersion);

final Long functionVersionAsLong = Long.valueOf(functionVersion);
final Long prevVersion = getPreviousVersion(functionName, functionVersionAsLong);
final Long prevVersion = version.getPreviousVersion(functionName, functionVersionAsLong);
aliasRoutingConfiguration.withAdditionalVersionWeights(
Collections.singletonMap(prevVersion.toString(), additionalVersionWeight));

} else if (getUseNextVersion() != null && getUseNextVersion()) {
validateFunctionVersion(functionVersion);
version.validateFunctionVersion(functionVersion);
final Long functionVersionAsLong = Long.valueOf(functionVersion);
final Long nextVersion = getNextVersion(functionVersionAsLong);
final Long nextVersion = version.getNextVersion(functionVersionAsLong);
aliasRoutingConfiguration.withAdditionalVersionWeights(
Collections.singletonMap(nextVersion.toString(), additionalVersionWeight));

}
return aliasRoutingConfiguration;
}

private void validateFunctionVersion(final String functionVersion) {
if (!functionVersion.matches("[0-9]+")) {
throw new GradleException("functionVersion must be a number if usePreviousVersion is true");
}
}

private void validateRequiredProperties() throws GradleException {
if (getAdditionalVersionWeight() == null) {
throw new GradleException("Additional Version Weight for routing config is required");
Expand All @@ -122,17 +128,12 @@ && getUseNextVersion() == null) {
}
}

private Long getNextVersion(final Long functionVersion) {
return functionVersion + 1;
}

private Long getPreviousVersion(final String functionName,
final Long functionVersion) {
if (functionVersion <= 1L) {
throw new GradleException("There is no older version for "
+ functionName);
} else {
return functionVersion - 1;
public void routingConfig(final Closure<RoutingConfig> c) {
c.setResolveStrategy(DELEGATE_FIRST);
if (routingConfig == null) {
routingConfig = new RoutingConfig();
}
c.setDelegate(routingConfig);
c.call();
}
}
41 changes: 41 additions & 0 deletions src/main/java/jp/classmethod/aws/gradle/lambda/Version.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
* Copyright 2015-2016 the original author or authors.
*
* 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 jp.classmethod.aws.gradle.lambda;

import org.gradle.api.GradleException;

public class Version {

public Long getNextVersion(final Long functionVersion) {
return functionVersion + 1;
}

public Long getPreviousVersion(final String functionName,
final Long functionVersion) {
if (functionVersion <= 1L) {
throw new GradleException("There is no older version for "
+ functionName);
} else {
return functionVersion - 1;
}
}

public void validateFunctionVersion(final String functionVersion) {
if (!functionVersion.matches("[0-9]+")) {
throw new GradleException("functionVersion must be a number if usePreviousVersion is true");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ public class VpcConfigWrapper {

/**
* Validates that at least one subnet and one security group are provided.
* @throws {@link GradleException} if at least one subnet and one security group are not set
*/
public void validate() {
boolean missingSubnet = subnetIds == null || subnetIds.isEmpty();
Expand All @@ -54,7 +53,6 @@ public void validate() {

/**
* @return {@link VpcConfig} instance
* @throws {@link GradleException} if at least one subnet and one security group are not set
*/
public VpcConfig toVpcConfig() {
this.validate();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public AmazonRDSDeleteDBClusterTask() {
}

@TaskAction
public void deleteDBInstance() {
public void deleteDBCluster() {
String dbClusterIdentifier = getDbClusterIdentifier();

if (dbClusterIdentifier == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ public void waitInstanceForStatus() { // NOPMD
String dbInstanceIdentifier = getDbInstanceIdentifier();
List<String> successStatuses = getSuccessStatuses();
List<String> waitStatuses = getWaitStatuses();
int loopTimeout = getLoopTimeout();
int loopWait = getLoopWait();

if (dbInstanceIdentifier == null) {
Expand All @@ -91,9 +90,8 @@ public void waitInstanceForStatus() { // NOPMD
AmazonRDSPluginExtension ext = getProject().getExtensions().getByType(AmazonRDSPluginExtension.class);
AmazonRDS rds = ext.getClient();

long start = System.currentTimeMillis();
while (true) {
if (System.currentTimeMillis() > start + (loopTimeout * 1000)) {
if (checkTimeout()) {
throw new GradleException("Timeout");
}
try {
Expand Down Expand Up @@ -129,4 +127,12 @@ public void waitInstanceForStatus() { // NOPMD
}
}
}

@TaskAction
public boolean checkTimeout() { // NOPMD
// to enable conventionMappings feature
long start = System.currentTimeMillis();
int loopTimeout = getLoopTimeout();
return start > start + (loopTimeout * 1000L);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ public void consumeMessages() {
AmazonSQSPluginExtension ext = getProject().getExtensions().getByType(AmazonSQSPluginExtension.class);
AmazonSQS sqs = ext.getClient();

int counter = 0;
while (counter < maxNumberOfMessages) {
int messageCounter = 0;
while (messageCounter < maxNumberOfMessages) {
ReceiveMessageRequest request = new ReceiveMessageRequest().withQueueUrl(queueUrl)
.withMaxNumberOfMessages(MAX_MESSAGE_CONSUME_BATCH_SIZE).withVisibilityTimeout(30);
List<DeleteMessageBatchRequestEntry> messagesToDelete =
Expand All @@ -77,10 +77,10 @@ public void consumeMessages() {
}

deleteMessages(sqs, queueUrl, messagesToDelete);
counter += messagesToDelete.size();
messageCounter += messagesToDelete.size();
}

getLogger().lifecycle("Consumed a total of {} messages from {}", counter, queueUrl);
getLogger().lifecycle("Consumed a total of {} messages from {}", messageCounter, queueUrl);
}

private void deleteMessages(AmazonSQS sqs, String queueUrl, List<DeleteMessageBatchRequestEntry> messagesToDelete) {
Expand Down