Removed the SecurityGroupExtension

This commit is contained in:
Ignasi Barrera 2014-12-23 18:28:45 +01:00
parent d6d1e7dde5
commit 2ba48dc9f6
9 changed files with 1 additions and 982 deletions

View File

@ -39,7 +39,6 @@ import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.config.ComputeServiceAdapterContextModule;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.SecurityGroup;
import org.jclouds.compute.extensions.ImageExtension;
import org.jclouds.compute.extensions.SecurityGroupExtension;
import org.jclouds.compute.options.TemplateOptions;
@ -47,15 +46,12 @@ import org.jclouds.domain.Location;
import org.jclouds.googlecomputeengine.compute.GoogleComputeEngineService;
import org.jclouds.googlecomputeengine.compute.GoogleComputeEngineServiceAdapter;
import org.jclouds.googlecomputeengine.compute.domain.NetworkAndAddressRange;
import org.jclouds.googlecomputeengine.compute.extensions.GoogleComputeEngineSecurityGroupExtension;
import org.jclouds.googlecomputeengine.compute.functions.CreateNetworkIfNeeded;
import org.jclouds.googlecomputeengine.compute.functions.FindNetworkOrCreate;
import org.jclouds.googlecomputeengine.compute.functions.FirewallTagNamingConvention;
import org.jclouds.googlecomputeengine.compute.functions.FirewallToIpPermission;
import org.jclouds.googlecomputeengine.compute.functions.GoogleComputeEngineImageToImage;
import org.jclouds.googlecomputeengine.compute.functions.InstanceToNodeMetadata;
import org.jclouds.googlecomputeengine.compute.functions.MachineTypeToHardware;
import org.jclouds.googlecomputeengine.compute.functions.NetworkToSecurityGroup;
import org.jclouds.googlecomputeengine.compute.functions.OrphanedGroupsFromDeadNodes;
import org.jclouds.googlecomputeengine.compute.functions.Resources;
import org.jclouds.googlecomputeengine.compute.options.GoogleComputeEngineTemplateOptions;
@ -63,7 +59,6 @@ import org.jclouds.googlecomputeengine.compute.predicates.AllNodesInGroupTermina
import org.jclouds.googlecomputeengine.compute.predicates.AtomicInstanceVisible;
import org.jclouds.googlecomputeengine.compute.predicates.AtomicOperationDone;
import org.jclouds.googlecomputeengine.compute.strategy.CreateNodesWithGroupEncodedIntoNameThenAddToSet;
import org.jclouds.googlecomputeengine.domain.Firewall;
import org.jclouds.googlecomputeengine.domain.Image;
import org.jclouds.googlecomputeengine.domain.Instance;
import org.jclouds.googlecomputeengine.domain.MachineType;
@ -71,7 +66,6 @@ import org.jclouds.googlecomputeengine.domain.Network;
import org.jclouds.googlecomputeengine.domain.Operation;
import org.jclouds.location.suppliers.ImplicitLocationSupplier;
import org.jclouds.location.suppliers.implicit.FirstZone;
import org.jclouds.net.domain.IpPermission;
import com.google.common.base.Function;
import com.google.common.base.Functions;
@ -116,12 +110,6 @@ public final class GoogleComputeEngineServiceContextModule
bind(new TypeLiteral<Function<Image, org.jclouds.compute.domain.Image>>() {
}).to(GoogleComputeEngineImageToImage.class);
bind(new TypeLiteral<Function<Firewall, Iterable<IpPermission>>>() {
}).to(FirewallToIpPermission.class);
bind(new TypeLiteral<Function<Network, SecurityGroup>>() {
}).to(NetworkToSecurityGroup.class);
bind(org.jclouds.compute.strategy.impl.CreateNodesWithGroupEncodedIntoNameThenAddToSet.class)
.to(CreateNodesWithGroupEncodedIntoNameThenAddToSet.class);
@ -139,7 +127,6 @@ public final class GoogleComputeEngineServiceContextModule
bind(new TypeLiteral<CacheLoader<NetworkAndAddressRange, Network>>() {
}).to(FindNetworkOrCreate.class);
bind(SecurityGroupExtension.class).to(GoogleComputeEngineSecurityGroupExtension.class);
bind(FirewallTagNamingConvention.Factory.class).in(Scopes.SINGLETON);
bindHttpApi(binder(), Resources.class);
}
@ -196,7 +183,7 @@ public final class GoogleComputeEngineServiceContextModule
}
@Override protected Optional<SecurityGroupExtension> provideSecurityGroupExtension(Injector i) {
return Optional.of(i.getInstance(SecurityGroupExtension.class));
return Optional.absent();
}
private static final Map<Instance.Status, NodeMetadata.Status> toPortableNodeStatus =

View File

@ -1,334 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.jclouds.googlecomputeengine.compute.extensions;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.jclouds.googlecloud.internal.ListPages.concat;
import static org.jclouds.googlecomputeengine.compute.predicates.NetworkFirewallPredicates.equalsIpPermission;
import static org.jclouds.googlecomputeengine.compute.predicates.NetworkFirewallPredicates.providesIpPermission;
import static org.jclouds.googlecomputeengine.compute.strategy.CreateNodesWithGroupEncodedIntoNameThenAddToSet.DEFAULT_INTERNAL_NETWORK_RANGE;
import static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.OPERATION_COMPLETE_INTERVAL;
import static org.jclouds.googlecomputeengine.config.GoogleComputeEngineProperties.OPERATION_COMPLETE_TIMEOUT;
import static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;
import static org.jclouds.util.Predicates2.retry;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import javax.inject.Inject;
import javax.inject.Named;
import org.jclouds.compute.domain.SecurityGroup;
import org.jclouds.compute.extensions.SecurityGroupExtension;
import org.jclouds.compute.functions.GroupNamingConvention;
import org.jclouds.domain.Location;
import org.jclouds.googlecomputeengine.GoogleComputeEngineApi;
import org.jclouds.googlecomputeengine.compute.domain.NetworkAndAddressRange;
import org.jclouds.googlecomputeengine.compute.functions.Resources;
import org.jclouds.googlecomputeengine.domain.Firewall;
import org.jclouds.googlecomputeengine.domain.Instance;
import org.jclouds.googlecomputeengine.domain.Instance.NetworkInterface;
import org.jclouds.googlecomputeengine.domain.Network;
import org.jclouds.googlecomputeengine.domain.Operation;
import org.jclouds.googlecomputeengine.options.FirewallOptions;
import org.jclouds.googlecomputeengine.options.ListOptions;
import org.jclouds.net.domain.IpPermission;
import org.jclouds.net.domain.IpProtocol;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.Atomics;
/** This implementation sets {@linkplain SecurityGroup#getId()} to {@link Network#name()}. */
public final class GoogleComputeEngineSecurityGroupExtension implements SecurityGroupExtension {
private final GoogleComputeEngineApi api;
private final Resources resources;
private final GroupNamingConvention.Factory namingConvention;
private final LoadingCache<NetworkAndAddressRange, Network> networkCreator;
private final Function<Network, SecurityGroup> groupConverter;
private final Predicate<AtomicReference<Operation>> operationDone;
private final long operationCompleteCheckInterval;
private final long operationCompleteCheckTimeout;
@Inject GoogleComputeEngineSecurityGroupExtension(GoogleComputeEngineApi api, Resources resources,
GroupNamingConvention.Factory namingConvention,
LoadingCache<NetworkAndAddressRange, Network> networkCreator, Function<Network, SecurityGroup> groupConverter,
Predicate<AtomicReference<Operation>> operationDone,
@Named(OPERATION_COMPLETE_INTERVAL) Long operationCompleteCheckInterval,
@Named(OPERATION_COMPLETE_TIMEOUT) Long operationCompleteCheckTimeout) {
this.api = api;
this.resources = resources;
this.namingConvention = namingConvention;
this.networkCreator = networkCreator;
this.groupConverter = groupConverter;
this.operationCompleteCheckInterval = operationCompleteCheckInterval;
this.operationCompleteCheckTimeout = operationCompleteCheckTimeout;
this.operationDone = operationDone;
}
@Override
public Set<SecurityGroup> listSecurityGroups() {
return FluentIterable.from(concat(api.networks().list())).transform(groupConverter).toSet();
}
@Override
public Set<SecurityGroup> listSecurityGroupsInLocation(final Location location) {
return listSecurityGroups();
}
@Override
public Set<SecurityGroup> listSecurityGroupsForNode(String id) {
Instance instance = resources.instance(URI.create(checkNotNull(id, "id")));
if (instance == null) {
return ImmutableSet.of();
}
ImmutableSet.Builder builder = ImmutableSet.builder();
for (NetworkInterface nwInterface : instance.networkInterfaces()) {
Network nw = resources.network(nwInterface.network());
SecurityGroup grp = groupForTagsInNetwork(nw, instance.tags().items());
if (grp != null) {
builder.add(grp);
}
}
return builder.build();
}
@Override
public SecurityGroup getSecurityGroupById(String id) {
checkNotNull(id, "id");
Network network = api.networks().get(id);
if (network == null) {
return null;
}
return groupConverter.apply(network);
}
@Override
public SecurityGroup createSecurityGroup(String name, Location location) {
return createSecurityGroup(name);
}
public SecurityGroup createSecurityGroup(String name) {
checkNotNull(name, "name");
NetworkAndAddressRange nAr = NetworkAndAddressRange.create(name, DEFAULT_INTERNAL_NETWORK_RANGE, null);
Network nw = networkCreator.apply(nAr);
return groupConverter.apply(nw);
}
@Override
public boolean removeSecurityGroup(String id) {
checkNotNull(id, "id");
if (api.networks().get(id) == null) {
return false;
}
ListOptions options = filter("network eq .*/" + id);
FluentIterable<Firewall> fws = FluentIterable.from(concat(api.firewalls().list(options)));
for (Firewall fw : fws) {
AtomicReference<Operation> operation = Atomics
.newReference(api.firewalls().delete(fw.name()));
retry(operationDone, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS)
.apply(operation);
checkState(operation.get().httpErrorStatusCode() == null,
"Could not delete firewall, operation failed" + operation);
}
AtomicReference<Operation> operation = Atomics.newReference(api.networks().delete(id));
retry(operationDone, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS)
.apply(operation);
checkState(operation.get().httpErrorStatusCode() == null,
"Could not insert network, operation failed" + operation);
return true;
}
@Override
public SecurityGroup addIpPermission(IpPermission ipPermission, SecurityGroup group) {
checkNotNull(group, "group");
checkNotNull(ipPermission, "ipPermission");
checkNotNull(api.networks().get(group.getId()) == null, "network for group is null");
ListOptions options = filter("network eq .*/" + group.getName());
if (Iterables
.any(concat(api.firewalls().list(options)), providesIpPermission(ipPermission))) {
// Permission already exists.
return group;
}
FirewallOptions fwOptions = new FirewallOptions();
String uniqueFwName = namingConvention.createWithoutPrefix().uniqueNameForGroup(group.getName());
fwOptions.name(uniqueFwName);
fwOptions.network(group.getUri());
if (!ipPermission.getGroupIds().isEmpty()) {
fwOptions.sourceTags(ipPermission.getGroupIds());
}
if (!ipPermission.getCidrBlocks().isEmpty()) {
fwOptions.sourceRanges(ipPermission.getCidrBlocks());
}
List<String> ports = Lists.newArrayList();
if (ipPermission.getFromPort() > 0) {
if (ipPermission.getFromPort() == ipPermission.getToPort()) {
ports.add(String.valueOf(ipPermission.getToPort()));
} else {
ports.add(ipPermission.getFromPort() + "-" + ipPermission.getToPort());
}
}
fwOptions.addAllowedRule(Firewall.Rule.create(ipPermission.getIpProtocol().value().toLowerCase(), ports));
AtomicReference<Operation> operation = Atomics.newReference(
api.firewalls().createInNetwork(uniqueFwName, group.getUri(), fwOptions));
retry(operationDone, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS)
.apply(operation);
checkState(operation.get().httpErrorStatusCode() == null,
"Could not insert firewall, operation failed" + operation);
return getSecurityGroupById(group.getId());
}
@Override
public SecurityGroup addIpPermission(IpProtocol protocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> cidrBlocks, Iterable<String> groupIds,
SecurityGroup group) {
IpPermission.Builder permBuilder = IpPermission.builder();
permBuilder.ipProtocol(protocol);
permBuilder.fromPort(fromPort);
permBuilder.toPort(toPort);
permBuilder.groupIds(groupIds);
permBuilder.cidrBlocks(cidrBlocks);
return addIpPermission(permBuilder.build(), group);
}
@Override
public SecurityGroup removeIpPermission(IpPermission ipPermission, SecurityGroup group) {
checkNotNull(group, "group");
checkNotNull(ipPermission, "ipPermission");
checkNotNull(api.networks().get(group.getId()) == null, "network for group is null");
ListOptions options = filter("network eq .*/" + group.getName());
FluentIterable<Firewall> fws = FluentIterable.from(concat(api.firewalls().list(options)));
for (Firewall fw : fws) {
if (equalsIpPermission(ipPermission).apply(fw)) {
AtomicReference<Operation> operation = Atomics
.newReference(api.firewalls().delete(fw.name()));
retry(operationDone, operationCompleteCheckTimeout, operationCompleteCheckInterval, MILLISECONDS)
.apply(operation);
checkState(operation.get().httpErrorStatusCode() == null,
"Could not delete firewall, operation failed" + operation);
}
}
return getSecurityGroupById(group.getId());
}
@Override
public SecurityGroup removeIpPermission(IpProtocol protocol, int fromPort, int toPort,
Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> cidrBlocks, Iterable<String> groupIds,
SecurityGroup group) {
IpPermission.Builder permBuilder = IpPermission.builder();
permBuilder.ipProtocol(protocol);
permBuilder.fromPort(fromPort);
permBuilder.toPort(toPort);
permBuilder.groupIds(groupIds);
permBuilder.cidrBlocks(cidrBlocks);
return removeIpPermission(permBuilder.build(), group);
}
@Override
public boolean supportsTenantIdGroupNamePairs() {
return false;
}
@Override
public boolean supportsTenantIdGroupIdPairs() {
return false;
}
@Override
public boolean supportsGroupIds() {
return true;
}
@Override
public boolean supportsPortRangesForGroups() {
return true;
}
@Override
public boolean supportsExclusionCidrBlocks() {
return false;
}
private SecurityGroup groupForTagsInNetwork(Network nw, final Collection<String> tags) {
ListOptions opts = filter("network eq .*/" + nw.name());
List<Firewall> fws = FluentIterable.from(concat(api.firewalls().list(opts)))
.filter(new Predicate<Firewall>() {
@Override public boolean apply(final Firewall input) {
// If any of the targetTags on the firewall apply or the firewall has no target tags...
return Iterables.any(input.targetTags(), Predicates.in(tags)) || Predicates.equalTo(0)
.apply(input.targetTags().size());
}
}).toList();
if (fws.isEmpty()) {
return null;
}
return groupConverter.apply(nw);
}
}

View File

@ -1,67 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.jclouds.googlecomputeengine.compute.functions;
import java.util.List;
import org.jclouds.googlecomputeengine.domain.Firewall;
import org.jclouds.googlecomputeengine.domain.Firewall.Rule;
import org.jclouds.net.domain.IpPermission;
import org.jclouds.net.domain.IpProtocol;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
public final class FirewallToIpPermission implements Function<Firewall, Iterable<IpPermission>> {
@Override public Iterable<IpPermission> apply(Firewall fw) {
ImmutableList.Builder<IpPermission> rules = ImmutableList.builder();
for (Rule rule : fw.allowed()) {
if (rule.ports() != null && !rule.ports().isEmpty()) {
for (String r : rule.ports()) {
IpPermission.Builder builder = populateBuilder(fw, rule.ipProtocol());
List<String> range = Splitter.on('-').splitToList(r);
int from = Integer.valueOf(range.get(0));
builder.fromPort(from);
builder.toPort(range.size() == 2 ? Integer.valueOf(range.get(1)) : from);
rules.add(builder.build());
}
} else {
rules.add(populateBuilder(fw, rule.ipProtocol()).build());
}
}
return rules.build();
}
private static IpPermission.Builder populateBuilder(Firewall fw, String protocol) {
IpPermission.Builder builder = IpPermission.builder();
builder.ipProtocol(IpProtocol.fromValue(protocol.toUpperCase()));
if (!fw.sourceRanges().isEmpty()) {
builder.cidrBlocks(fw.sourceRanges());
}
if (!fw.sourceTags().isEmpty()) {
builder.groupIds(fw.sourceTags());
}
return builder;
}
}

View File

@ -1,67 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.jclouds.googlecomputeengine.compute.functions;
import static org.jclouds.googlecloud.internal.ListPages.concat;
import static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;
import javax.inject.Inject;
import org.jclouds.compute.domain.SecurityGroup;
import org.jclouds.compute.domain.SecurityGroupBuilder;
import org.jclouds.googlecomputeengine.GoogleComputeEngineApi;
import org.jclouds.googlecomputeengine.domain.Firewall;
import org.jclouds.googlecomputeengine.domain.Network;
import org.jclouds.googlecomputeengine.options.ListOptions;
import org.jclouds.net.domain.IpPermission;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
public final class NetworkToSecurityGroup implements Function<Network, SecurityGroup> {
private final Function<Firewall, Iterable<IpPermission>> firewallToPerms;
private final GoogleComputeEngineApi api;
@Inject NetworkToSecurityGroup(Function<Firewall, Iterable<IpPermission>> firewallToPerms,
GoogleComputeEngineApi api) {
this.firewallToPerms = firewallToPerms;
this.api = api;
}
@Override public SecurityGroup apply(Network network) {
SecurityGroupBuilder builder = new SecurityGroupBuilder();
builder.id(network.name());
builder.providerId(network.id());
builder.name(network.name());
builder.uri(network.selfLink());
ImmutableList.Builder permBuilder = ImmutableList.builder();
ListOptions options = filter("network eq .*/" + network.name());
for (Firewall fw : concat(api.firewalls().list(options))) {
permBuilder.addAll(firewallToPerms.apply(fw));
}
builder.ipPermissions(permBuilder.build());
return builder.build();
}
}

View File

@ -1,125 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.jclouds.googlecomputeengine.compute.predicates;
import static com.google.common.collect.Sets.intersection;
import java.util.List;
import org.jclouds.googlecomputeengine.domain.Firewall;
import org.jclouds.googlecomputeengine.domain.Firewall.Rule;
import org.jclouds.net.domain.IpPermission;
import com.google.common.base.Predicate;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
public final class NetworkFirewallPredicates {
public static Predicate<Firewall> hasPortRange(final String protocol, final int fromPort, final int toPort) {
return new Predicate<Firewall>() {
@Override public boolean apply(Firewall fw) {
for (Rule rule : fw.allowed()) {
if (!rule.ipProtocol().equals(protocol)) {
continue;
}
if (rule.ports() == null || rule.ports().isEmpty()) {
return true;
}
for (String range : rule.ports()) {
if (range.indexOf('-') != -1) {
if (inRange(range, fromPort, toPort)) {
return true;
}
}
}
}
return false;
}
};
}
private static boolean inRange(String range, int fromPort, int toPort) {
List<String> ports = Splitter.on('-').splitToList(range);
return fromPort >= Integer.valueOf(ports.get(0)) && toPort <= Integer.valueOf(ports.get(1));
}
public static Predicate<Firewall> hasSourceTag(final String sourceTag) {
return new Predicate<Firewall>() {
@Override public boolean apply(Firewall input) {
return input.sourceTags().contains(sourceTag);
}
};
}
public static Predicate<Firewall> hasSourceRange(final String sourceRange) {
return new Predicate<Firewall>() {
@Override public boolean apply(Firewall input) {
return input.sourceRanges().contains(sourceRange);
}
};
}
public static Predicate<Firewall> equalsIpPermission(final IpPermission permission) {
return new Predicate<Firewall>() {
@Override public boolean apply(Firewall input) {
return Iterables.elementsEqual(permission.getGroupIds(), input.sourceTags())
&& Iterables.elementsEqual(permission.getCidrBlocks(), input.sourceRanges())
&& (input.allowed().size() == 1
&& ruleEqualsIpPermission(permission).apply(Iterables.getOnlyElement(input.allowed())));
}
};
}
public static Predicate<Firewall> providesIpPermission(final IpPermission permission) {
return new Predicate<Firewall>() {
@Override public boolean apply(Firewall input) {
boolean groupsMatchTags =
(permission.getGroupIds().isEmpty() && input.sourceTags().isEmpty()) || !intersection(
permission.getGroupIds(), ImmutableSet.copyOf(input.sourceTags())).isEmpty();
boolean cidrsMatchRanges =
(permission.getCidrBlocks().isEmpty() && input.sourceRanges().isEmpty()) || !intersection(
permission.getCidrBlocks(), ImmutableSet.copyOf(input.sourceRanges())).isEmpty();
boolean firewallHasPorts = hasPortRange(permission.getIpProtocol().value().toLowerCase(),
permission.getFromPort(), permission.getToPort()).apply(input);
return groupsMatchTags && cidrsMatchRanges && firewallHasPorts;
}
};
}
private static Predicate<Firewall.Rule> ruleEqualsIpPermission(final IpPermission permission) {
return new Predicate<Rule>() {
@Override public boolean apply(Firewall.Rule input) {
if (!permission.getIpProtocol().value().toLowerCase().equals(input.ipProtocol())) {
return false;
}
if (input.ports() == null
|| input.ports().isEmpty() && permission.getFromPort() == 0 && permission.getToPort() == 0) {
return true;
} else if (input.ports().size() == 1) {
String port = Iterables.getOnlyElement(input.ports());
if (permission.getFromPort() == permission.getToPort()) {
return port.equals(String.valueOf(permission.getFromPort()));
}
return port.equals(permission.getFromPort() + "-" + permission.getToPort());
}
return false;
}
};
}
}

View File

@ -1,35 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.jclouds.googlecomputeengine.compute.extensions;
import java.util.Properties;
import org.jclouds.compute.extensions.internal.BaseSecurityGroupExtensionLiveTest;
import org.jclouds.googlecloud.internal.TestProperties;
import org.testng.annotations.Test;
@Test(groups = "live", singleThreaded = true, testName = "GoogleComputeEngineSecurityGroupExtensionLiveTest")
public class GoogleComputeEngineSecurityGroupExtensionLiveTest extends BaseSecurityGroupExtensionLiveTest {
public GoogleComputeEngineSecurityGroupExtensionLiveTest() {
provider = "google-compute-engine";
}
@Override protected Properties setupProperties() {
return TestProperties.apply(provider, super.setupProperties());
}
}

View File

@ -1,93 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.jclouds.googlecomputeengine.compute.functions;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.net.URI;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.googlecomputeengine.domain.Firewall;
import org.jclouds.net.domain.IpPermission;
import org.jclouds.net.domain.IpProtocol;
import org.testng.annotations.Test;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
@Test
public class FirewallToIpPermissionTest {
public void testApply() {
Firewall fw = fwForTest();
FirewallToIpPermission converter = new FirewallToIpPermission();
Iterable<IpPermission> perms = converter.apply(fw);
assertEquals(Iterables.size(perms), 3,
"There should be three IpPermissions but there is only " + Iterables.size(perms));
assertTrue(Iterables.any(perms, Predicates.and(hasProtocol(IpProtocol.TCP), hasStartAndEndPort(1, 10))),
"No permission found for TCP, ports 1-10");
assertTrue(Iterables.any(perms, Predicates.and(hasProtocol(IpProtocol.TCP), hasStartAndEndPort(33, 33))),
"No permission found for TCP, port 33");
assertTrue(Iterables.any(perms, hasProtocol(IpProtocol.ICMP)), "No permission found for ICMP");
}
public static Firewall fwForTest() {
String baseUrl = "https://www.googleapis.com/compute/v1/projects";
return Firewall.create( //
"abcd", // id
URI.create(baseUrl + "/jclouds/global/firewalls/jclouds-test"), // selfLink
new SimpleDateFormatDateService().iso8601DateParse("2012-04-13T03:05:04.365"), // creationTimestamp
"jclouds-test", // name
null, // description
URI.create(baseUrl + "/jclouds/global/networks/jclouds-test"), // network
ImmutableList.of("0.0.0.0/0"), // sourceRanges
null, // sourceTags
null, // targetTags
ImmutableList.of( // allowed
Firewall.Rule.create("tcp", ImmutableList.of("1-10")), //
Firewall.Rule.create("tcp", ImmutableList.of("33")), //
Firewall.Rule.create("icmp", ImmutableList.<String>of()) //
));
}
public static Predicate<IpPermission> hasProtocol(final IpProtocol protocol) {
return new Predicate<IpPermission>() {
@Override
public boolean apply(IpPermission perm) {
return protocol.equals(perm.getIpProtocol());
}
};
}
public static Predicate<IpPermission> hasStartAndEndPort(final int startPort, final int endPort) {
return new Predicate<IpPermission>() {
@Override
public boolean apply(IpPermission perm) {
return startPort == perm.getFromPort() && endPort == perm.getToPort();
}
};
}
}

View File

@ -1,85 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.jclouds.googlecomputeengine.compute.functions;
import static com.google.common.collect.Iterators.singletonIterator;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.jclouds.googlecomputeengine.compute.functions.FirewallToIpPermissionTest.hasProtocol;
import static org.jclouds.googlecomputeengine.compute.functions.FirewallToIpPermissionTest.hasStartAndEndPort;
import static org.jclouds.googlecomputeengine.options.ListOptions.Builder.filter;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import java.net.URI;
import org.jclouds.compute.domain.SecurityGroup;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.googlecloud.domain.ForwardingListPage;
import org.jclouds.googlecomputeengine.GoogleComputeEngineApi;
import org.jclouds.googlecomputeengine.domain.Network;
import org.jclouds.googlecomputeengine.features.FirewallApi;
import org.jclouds.googlecomputeengine.options.ListOptions;
import org.jclouds.net.domain.IpProtocol;
import org.testng.annotations.Test;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
public class NetworkToSecurityGroupTest {
@Test
public void testApply() {
FirewallToIpPermission fwToPerm = new FirewallToIpPermission();
GoogleComputeEngineApi api = createMock(GoogleComputeEngineApi.class);
FirewallApi fwApi = createMock(FirewallApi.class);
ListOptions options = filter("network eq .*/party-test");
expect(api.firewalls()).andReturn(fwApi);
expect(fwApi.list(options)).andReturn(
singletonIterator(ForwardingListPage.create(ImmutableList.of(FirewallToIpPermissionTest.fwForTest()), null)));
replay(api, fwApi);
Network network = Network.create( //
"abcd", // id
new SimpleDateFormatDateService().iso8601DateParse("2014-07-18T09:47:30.826-07:00"), // creationTimestamp
URI.create("https://www.googleapis.com/compute/v1/projects/party/global/networks/party-test"),
"party-test", // name
"some description", // description
"0.0.0.0/0", // rangeIPv4
"1.2.3.4" // gatewayIPv4
);
NetworkToSecurityGroup netToSg = new NetworkToSecurityGroup(fwToPerm, api);
SecurityGroup group = netToSg.apply(network);
assertEquals(group.getId(), "party-test");
assertEquals(group.getUri(), URI.create("https://www.googleapis.com/compute/v1/projects/party/global/networks/party-test"));
assertEquals(group.getIpPermissions().size(), 3);
assertTrue(Iterables.any(group.getIpPermissions(), Predicates.and(hasProtocol(IpProtocol.TCP),
hasStartAndEndPort(1, 10))), "No permission found for TCP, ports 1-10");
assertTrue(Iterables.any(group.getIpPermissions(), Predicates.and(hasProtocol(IpProtocol.TCP),
hasStartAndEndPort(33, 33))), "No permission found for TCP, port 33");
assertTrue(Iterables.any(group.getIpPermissions(), hasProtocol(IpProtocol.ICMP)),
"No permission found for ICMP");
}
}

View File

@ -1,162 +0,0 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.jclouds.googlecomputeengine.predicates;
import static org.jclouds.googlecomputeengine.compute.functions.FirewallToIpPermissionTest.fwForTest;
import static org.jclouds.googlecomputeengine.compute.predicates.NetworkFirewallPredicates.equalsIpPermission;
import static org.jclouds.googlecomputeengine.compute.predicates.NetworkFirewallPredicates.hasPortRange;
import static org.jclouds.googlecomputeengine.compute.predicates.NetworkFirewallPredicates.hasSourceRange;
import static org.jclouds.googlecomputeengine.compute.predicates.NetworkFirewallPredicates.hasSourceTag;
import static org.jclouds.googlecomputeengine.compute.predicates.NetworkFirewallPredicates.providesIpPermission;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import java.net.URI;
import org.jclouds.date.internal.SimpleDateFormatDateService;
import org.jclouds.googlecomputeengine.domain.Firewall;
import org.jclouds.net.domain.IpPermission;
import org.jclouds.net.domain.IpProtocol;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
@Test(groups = "unit", testName = "NetworkFirewallPredicatesTest")
public class NetworkFirewallPredicatesTest {
protected static final String BASE_URL = "https://www.googleapis.com/compute/v1/projects";
public static Firewall getFwForTestSourceTags() {
return Firewall.create( //
"abcd", // id
URI.create(BASE_URL + "/party/global/firewalls/jclouds-test"), // selfLink
new SimpleDateFormatDateService().iso8601DateParse("2014-07-18T09:47:30.826-07:00"), // creationTimestamp
"jclouds-test", // name
null, // description
URI.create(BASE_URL + "/party/global/networks/jclouds-test"), // network
null, // sourceRanges
ImmutableList.of("tag-1"), // sourceTags
null, // targetTags
ImmutableList.of( // allowed
Firewall.Rule.create("tcp", ImmutableList.of("1-10")), //
Firewall.Rule.create("tcp", ImmutableList.of("33")) //
));
}
public static Firewall getFwForTestSourceTagsExact() {
return Firewall.create( //
"abcd", // id
URI.create(BASE_URL + "/party/global/firewalls/jclouds-test"), // selfLink
new SimpleDateFormatDateService().iso8601DateParse("2014-07-18T09:47:30.826-07:00"), // creationTimestamp
"jclouds-test", // name
null, // description
URI.create(BASE_URL + "/party/global/networks/jclouds-test"), // network
null, // sourceRanges
ImmutableList.of("tag-1"), // sourceTags
null, // targetTags
ImmutableList.of(Firewall.Rule.create("tcp", ImmutableList.of("1-10"))) // allowed
);
}
@Test
public void testHasPortRange() {
assertTrue(hasPortRange("tcp", 2, 9).apply(fwForTest()),
"Firewall " + fwForTest() + " should contain the port range 2-9.");
}
@Test
public void testHasPortRangeSame() {
assertTrue(hasPortRange("tcp", 2, 2).apply(fwForTest()),
"Firewall " + fwForTest() + " should contain the port range 2-2.");
}
@Test
public void testHasPortRangeFails() {
assertFalse(hasPortRange("tcp", 11, 15).apply(fwForTest()),
"Firewall " + fwForTest() + " should NOT contain the port range 11-15.");
}
@Test
public void testHasPortRangeFailsSame() {
assertFalse(hasPortRange("tcp", 15, 15).apply(fwForTest()),
"Firewall " + fwForTest() + " should NOT contain the port range 15-15.");
}
@Test
public void testHasSourceTag() {
assertTrue(hasSourceTag("tag-1").apply(getFwForTestSourceTags()),
"Firewall " + getFwForTestSourceTags() + " should contain the source tag 'tag-1'.");
}
@Test
public void testHasSourceTagFails() {
assertFalse(hasSourceTag("tag-1").apply(fwForTest()),
"Firewall " + fwForTest() + " should NOT contain the source tag 'tag-1'.");
}
@Test
public void testHasSourceRange() {
assertTrue(hasSourceRange("0.0.0.0/0").apply(fwForTest()),
"Firewall " + fwForTest() + " should contain the source range '0.0.0.0/0'.");
}
@Test
public void testHasSourceRangeFails() {
assertFalse(hasSourceRange("0.0.0.0/0").apply(getFwForTestSourceTags()),
"Firewall " + getFwForTestSourceTags() + " should NOT contain the source range '0.0.0.0/0'.");
}
@Test
public void testEqualsIpPermission() {
IpPermission perm = IpPermission.builder().groupId("tag-1").fromPort(1).toPort(10).ipProtocol(IpProtocol.TCP)
.build();
assertTrue(equalsIpPermission(perm).apply(getFwForTestSourceTagsExact()),
"Firewall " + getFwForTestSourceTagsExact() + " should match IpPermission " + perm + " but does not.");
}
@Test
public void testEqualsIpPermissionFails() {
IpPermission perm = IpPermission.builder().groupId("tag-1").fromPort(1).toPort(10).ipProtocol(IpProtocol.TCP)
.build();
assertFalse(equalsIpPermission(perm).apply(getFwForTestSourceTags()),
"Firewall " + getFwForTestSourceTags() + " should not match IpPermission " + perm + " but does.");
}
@Test
public void testProvidesIpPermission() {
IpPermission perm = IpPermission.builder().groupId("tag-1").fromPort(1).toPort(10).ipProtocol(IpProtocol.TCP)
.build();
assertTrue(providesIpPermission(perm).apply(getFwForTestSourceTagsExact()),
"Firewall " + getFwForTestSourceTagsExact() + " should provide IpPermission " + perm + " but does not.");
assertTrue(providesIpPermission(perm).apply(getFwForTestSourceTags()),
"Firewall " + getFwForTestSourceTags() + " should inexactly provide IpPermission " + perm
+ " but does not.");
}
@Test
public void testProvidesIpPermissionFails() {
IpPermission perm = IpPermission.builder().groupId("tag-1").fromPort(1).toPort(10).ipProtocol(IpProtocol.TCP)
.build();
assertFalse(providesIpPermission(perm).apply(fwForTest()),
"Firewall " + fwForTest() + " should not provide IpPermission " + perm + " but does.");
}
}