Package org.jclouds.aws.ec2.features

Examples of org.jclouds.aws.ec2.features.AWSSecurityGroupApi


   @Override
   public String createNewKeyPairUnlessUserSpecifiedOtherwise(String region, String group, TemplateOptions options) {
      RegionAndName key = new RegionAndName(region, group);
      KeyPair pair;
      if (and(hasPublicKeyMaterial, or(doesntNeedSshAfterImportingPublicKey, hasLoginCredential)).apply(options)) {
         pair = importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, options.getPublicKey()));
         options.dontAuthorizePublicKey();
         if (hasLoginCredential.apply(options))
            pair = pair.toBuilder().keyMaterial(options.getLoginPrivateKey()).build();
         credentialsMap.put(key, pair);
      } else {
View Full Code Here


            LoginCredentials.builder().user("foo").privateKey(CREDENTIALS.credential).build());
      KeyPair keyPair = new KeyPair(region, group, "//TODO", null, null);

      // setup expectations
      expect(
            strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group,
                  CREDENTIALS.credential))).andReturn(keyPair);
      expect(
            strategy.credentialsMap.put(new RegionAndName(region, group),
                  keyPair.toBuilder().keyMaterial(CREDENTIALS.credential).build())).andReturn(null);
View Full Code Here

      CreateKeyPairPlacementAndSecurityGroupsAsNeededAndReturnRunOptions strategy = setupStrategy();

      KeyPair keyPair = new KeyPair(region, "jclouds#" + group, "fingerprint", null, null);

      // setup expectations
      expect(strategy.importExistingKeyPair.apply(new RegionNameAndPublicKeyMaterial(region, group, "ssh-rsa")))
            .andReturn(keyPair);
      expect(strategy.credentialsMap.put(new RegionAndName(region, group), keyPair)).andReturn(null);

      // replay mocks
      replayStrategy(strategy);
View Full Code Here

      for (String region : Region.DEFAULT_REGIONS) {
         SortedSet<SpotInstanceRequest> allResults = ImmutableSortedSet.copyOf(client.getSpotInstanceServices()
                  .describeSpotInstanceRequestsInRegion(region));
         assertNotNull(allResults);
         if (allResults.size() >= 1) {
            SpotInstanceRequest request = allResults.last();
            SortedSet<SpotInstanceRequest> result = ImmutableSortedSet.copyOf(client.getSpotInstanceServices()
                     .describeSpotInstanceRequestsInRegion(region, request.getId()));
            assertNotNull(result);
            SpotInstanceRequest compare = result.last();
            assertEquals(compare, request);
         }
      }

   }
View Full Code Here

      for (SpotInstanceRequest request : requests)
         verifySpotInstance(request);
   }

   private void verifySpotInstance(SpotInstanceRequest request) {
      SpotInstanceRequest spot = refresh(request);
      assertNotNull(spot);
      assertEquals(spot, request);
      assert activeTester.apply(request) : refresh(request);
      System.out.println(System.currentTimeMillis() - start);
      spot = refresh(request);
      assert spot.getInstanceId() != null : spot;
      instance = getOnlyElement(getOnlyElement(client.getInstanceServices().describeInstancesInRegion(spot.getRegion(),
               spot.getInstanceId())));
      assertEquals(instance.getSpotInstanceRequestId(), spot.getId());
   }
View Full Code Here

   @Override
   public RunningInstance getRunningInstanceInRegion(String region, String id) {
      if (id.indexOf("sir-") != 0)
         return super.getRunningInstanceInRegion(region, id);
      SpotInstanceRequest spot = getOnlyElement(client.getSpotInstanceServices().describeSpotInstanceRequestsInRegion(
               region, id));
      if (spot.getState() == SpotInstanceRequest.State.ACTIVE)
         return super.getRunningInstanceInRegion(region, spot.getInstanceId());
      else
         return spotConverter.apply(spot);
   }
View Full Code Here

    String ec2Msg = " ec2. Region: " + region + " - Key Pair Name: ";

    ComputeServiceContext context = iaasInfo.getComputeService()
        .getContext();
   
    AWSKeyPairApi keyPairApi = context.unwrapApi(AWSEC2Api.class).getKeyPairApiForRegion(region).get();

    KeyPair keyPair = keyPairApi.importKeyPairInRegion(region, keyPairName, publicKey);
   
    if (keyPair != null) {

      iaasInfo.getTemplate().getOptions().as(AWSEC2TemplateOptions.class)
          .keyPair(keyPair.getKeyName());
View Full Code Here

   @SuppressWarnings("unchecked")
   @Test
   public void testWhenPort22AndToItselfAuthorizesIngressOnce() throws ExecutionException {

      AWSSecurityGroupApi client = createMock(AWSSecurityGroupApi.class);
      Predicate<RegionAndName> tester = Predicates.alwaysTrue();

      SecurityGroup group = createNiceMock(SecurityGroup.class);
      Set<SecurityGroup> groups = ImmutableSet.<SecurityGroup> of(group);

      EC2SecurityGroupIdFromName groupIdFromName = createMock(EC2SecurityGroupIdFromName.class);

      ImmutableSet.Builder<IpPermission> permissions = ImmutableSet.builder();

      permissions.add(IpPermission.builder()
                      .fromPort(22)
                      .toPort(22)
                      .ipProtocol(IpProtocol.TCP)
                      .cidrBlock("0.0.0.0/0")
                      .build());

      permissions.add(IpPermission.builder()
                      .fromPort(0)
                      .toPort(65535)
                      .ipProtocol(IpProtocol.TCP)
                      .tenantIdGroupNamePair("ownerId", "sg-123456")
                      .build());
      permissions.add(IpPermission.builder()
                      .fromPort(0)
                      .toPort(65535)
                      .ipProtocol(IpProtocol.UDP)
                      .tenantIdGroupNamePair("ownerId", "sg-123456")
                      .build());
     
      client.createSecurityGroupInRegion("region", "group", "group");
      expect(group.getOwnerId()).andReturn("ownerId");
      expect(groupIdFromName.apply("region/group")).andReturn("sg-123456");
      client.authorizeSecurityGroupIngressInRegion("region", "sg-123456", permissions.build());
      expect(client.describeSecurityGroupsInRegion("region", "group")).andReturn(Set.class.cast(groups));


      replay(client);
      replay(group);
      replay(groupIdFromName);
View Full Code Here

   @Override
   @Test
   public void testExtendedOptionsAndLogin() throws Exception {
      String region = "us-west-2";

      AWSSecurityGroupApi securityGroupApi = view.unwrapApi(AWSEC2Api.class).getSecurityGroupApi().get();

      KeyPairApi keyPairApi = view.unwrapApi(AWSEC2Api.class).getKeyPairApi().get();

      InstanceApi instanceApi = view.unwrapApi(AWSEC2Api.class).getInstanceApi().get();

      String group = this.group + "o";

      Date before = new Date();

      ImmutableMap<String, String> userMetadata = ImmutableMap.<String, String> of("test", group);

      ImmutableSet<String> tags = ImmutableSet.of(group);

      // note that if you change the location, you must also specify image parameters
      Template template = client.templateBuilder().locationId(region).osFamily(AMZN_LINUX).os64Bit(true).build();
      template.getOptions().tags(tags);
      template.getOptions().userMetadata(userMetadata);
      template.getOptions().tags(tags);
      template.getOptions().as(AWSEC2TemplateOptions.class).enableMonitoring();
      template.getOptions().as(AWSEC2TemplateOptions.class).spotPrice(0.3f);

      String startedId = null;
      try {
         cleanupExtendedStuffInRegion(region, securityGroupApi, keyPairApi, group);

         Thread.sleep(3000);// eventual consistency if deletes actually occurred.

         // create a security group that allows ssh in so that our scripts later
         // will work
         String groupId = securityGroupApi.createSecurityGroupInRegionAndReturnId(region, group, group);

         securityGroupApi.authorizeSecurityGroupIngressInRegion(region, groupId, permit(IpProtocol.TCP).port(22));

         template.getOptions().as(AWSEC2TemplateOptions.class).securityGroupIds(groupId);

         // create a keypair to pass in as well
         KeyPair result = keyPairApi.createKeyPairInRegion(region, group);
         template.getOptions().as(AWSEC2TemplateOptions.class).keyPair(result.getKeyName());

         // pass in the private key, so that we can run a script with it
         assert result.getKeyMaterial() != null : result;
         template.getOptions().overrideLoginPrivateKey(result.getKeyMaterial());

         Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, template);
         NodeMetadata first = getOnlyElement(nodes);

         checkUserMetadataContains(first, userMetadata);
         checkTagsInNodeEquals(first, tags);

         assert first.getCredentials() != null : first;
         assert first.getCredentials().identity != null : first;

         startedId = first.getProviderId();

         AWSRunningInstance instance = AWSRunningInstance.class.cast(getOnlyElement(getOnlyElement(instanceApi
                  .describeInstancesInRegion(region, startedId))));

         assertEquals(instance.getKeyName(), group);
         assert instance.getSpotInstanceRequestId() != null;
         assertEquals(instance.getMonitoringState(), MonitoringState.ENABLED);

         // generate some load
         ListenableFuture<ExecResponse> future = client.submitScriptOnNode(first.getId(), Statements
                  .exec("while true; do true; done"), runAsRoot(false).nameTask("cpuSpinner"));

         // monitoring granularity for free tier is 5 minutes, so lets make sure we have data.
         Thread.sleep(TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES));

         // stop the spinner
         future.cancel(true);

         CloudWatchApi monitoringApi = ContextBuilder.newBuilder(new AWSCloudWatchProviderMetadata())
                                                     .credentials(identity, credential)
                                                     .modules(setupModules())
                                                     .buildApi(CloudWatchApi.class);

         try {
            GetMetricStatisticsResponse datapoints = monitoringApi.getMetricApiForRegion(instance.getRegion())
                     .getMetricStatistics(GetMetricStatistics.builder()
                                                             .dimension(new Dimension(EC2Constants.Dimension.INSTANCE_ID, instance.getId()))
                                                             .unit(Unit.PERCENT)
                                                             .namespace("AWS/EC2")
                                                             .metricName("CPUUtilization")
                                                             .startTime(before)
                                                             .endTime(new Date())
                                                             .period(60)
                                                             .statistic(Statistics.AVERAGE)
                                                             .build());
            assert datapoints.size() > 0 : instance;
         } finally {
            monitoringApi.close();
         }

         // make sure we made our dummy group and also let in the user's group
         assertEquals(newTreeSet(instance.getGroupNames()), ImmutableSortedSet.<String> of("jclouds#" + group, group));

         // make sure our dummy group has no rules
         SecurityGroup secgroup = getOnlyElement(securityGroupApi.describeSecurityGroupsInRegion(instance
                  .getRegion(), "jclouds#" + group));

         assert secgroup.size() == 0 : secgroup;

         // try to run a script with the original keyPair
         runScriptWithCreds(group, first.getOperatingSystem(), LoginCredentials.builder().user(
                  first.getCredentials().identity).privateKey(result.getKeyMaterial()).build());

      } finally {
         client.destroyNodesMatching(NodePredicates.inGroup(group));
         if (startedId != null) {
            // ensure we didn't delete these resources!
            assertEquals(keyPairApi.describeKeyPairsInRegion(region, group).size(), 1);
            assertEquals(securityGroupApi.describeSecurityGroupsInRegion(region, group).size(), 1);
         }
         cleanupExtendedStuffInRegion(region, securityGroupApi, keyPairApi, group);
      }
   }
View Full Code Here

   @Override
   @Test
   public void testExtendedOptionsAndLogin() throws Exception {
      String region = "us-west-2";

      AWSSecurityGroupApi securityGroupApi = view.unwrapApi(AWSEC2Api.class).getSecurityGroupApi().get();

      KeyPairApi keyPairApi = view.unwrapApi(AWSEC2Api.class).getKeyPairApi().get();

      InstanceApi instanceApi = view.unwrapApi(AWSEC2Api.class).getInstanceApi().get();

      String group = this.group + "o";

      Date before = new Date();

      ImmutableMap<String, String> userMetadata = ImmutableMap.<String, String> of("test", group);

      ImmutableSet<String> tags = ImmutableSet.of(group);

      // note that if you change the location, you must also specify image parameters
      Template template = client.templateBuilder().locationId(region).osFamily(AMZN_LINUX).os64Bit(true).build();
      template.getOptions().tags(tags);
      template.getOptions().userMetadata(userMetadata);
      template.getOptions().tags(tags);
      template.getOptions().as(AWSEC2TemplateOptions.class).enableMonitoring();
      template.getOptions().as(AWSEC2TemplateOptions.class).spotPrice(0.3f);

      String startedId = null;
      try {
         cleanupExtendedStuffInRegion(region, securityGroupApi, keyPairApi, group);

         Thread.sleep(3000);// eventual consistency if deletes actually occurred.

         // create a security group that allows ssh in so that our scripts later
         // will work
         String groupId = securityGroupApi.createSecurityGroupInRegionAndReturnId(region, group, group);

         securityGroupApi.authorizeSecurityGroupIngressInRegion(region, groupId, permit(IpProtocol.TCP).port(22));

         template.getOptions().as(AWSEC2TemplateOptions.class).securityGroupIds(groupId);

         // create a keypair to pass in as well
         KeyPair result = keyPairApi.createKeyPairInRegion(region, group);
         template.getOptions().as(AWSEC2TemplateOptions.class).keyPair(result.getKeyName());

         // pass in the private key, so that we can run a script with it
         assert result.getKeyMaterial() != null : result;
         template.getOptions().overrideLoginPrivateKey(result.getKeyMaterial());

         Set<? extends NodeMetadata> nodes = client.createNodesInGroup(group, 1, template);
         NodeMetadata first = getOnlyElement(nodes);

         checkUserMetadataContains(first, userMetadata);
         checkTagsInNodeEquals(first, tags);

         assert first.getCredentials() != null : first;
         assert first.getCredentials().identity != null : first;

         startedId = first.getProviderId();

         AWSRunningInstance instance = AWSRunningInstance.class.cast(getOnlyElement(getOnlyElement(instanceApi
                  .describeInstancesInRegion(region, startedId))));

         assertEquals(instance.getKeyName(), group);
         assert instance.getSpotInstanceRequestId() != null;
         assertEquals(instance.getMonitoringState(), MonitoringState.ENABLED);

         // generate some load
         ListenableFuture<ExecResponse> future = client.submitScriptOnNode(first.getId(), Statements
                  .exec("while true; do true; done"), runAsRoot(false).nameTask("cpuSpinner"));

         // monitoring granularity for free tier is 5 minutes, so lets make sure we have data.
         Thread.sleep(TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES));

         // stop the spinner
         future.cancel(true);

         CloudWatchApi monitoringApi = ContextBuilder.newBuilder(new AWSCloudWatchProviderMetadata())
                                                     .credentials(identity, credential)
                                                     .modules(setupModules())
                                                     .buildApi(CloudWatchApi.class);

         try {
            GetMetricStatisticsResponse datapoints = monitoringApi.getMetricApiForRegion(instance.getRegion())
                     .getMetricStatistics(GetMetricStatistics.builder()
                                                             .dimension(new Dimension(EC2Constants.Dimension.INSTANCE_ID, instance.getId()))
                                                             .unit(Unit.PERCENT)
                                                             .namespace("AWS/EC2")
                                                             .metricName("CPUUtilization")
                                                             .startTime(before)
                                                             .endTime(new Date())
                                                             .period(60)
                                                             .statistic(Statistics.AVERAGE)
                                                             .build());
            assert datapoints.size() > 0 : instance;
         } finally {
            monitoringApi.close();
         }

         // make sure we made our dummy group and also let in the user's group
         assertEquals(newTreeSet(instance.getGroupNames()), ImmutableSortedSet.<String> of("jclouds#" + group, group));

         // make sure our dummy group has no rules
         SecurityGroup secgroup = getOnlyElement(securityGroupApi.describeSecurityGroupsInRegion(instance
                  .getRegion(), "jclouds#" + group));

         assert secgroup.size() == 0 : secgroup;

         // try to run a script with the original keyPair
         runScriptWithCreds(group, first.getOperatingSystem(), LoginCredentials.builder().user(
                  first.getCredentials().identity).privateKey(result.getKeyMaterial()).build());

      } finally {
         client.destroyNodesMatching(NodePredicates.inGroup(group));
         if (startedId != null) {
            // ensure we didn't delete these resources!
            assertEquals(keyPairApi.describeKeyPairsInRegion(region, group).size(), 1);
            assertEquals(securityGroupApi.describeSecurityGroupsInRegion(region, group).size(), 1);
         }
         cleanupExtendedStuffInRegion(region, securityGroupApi, keyPairApi, group);
      }
   }
View Full Code Here

TOP

Related Classes of org.jclouds.aws.ec2.features.AWSSecurityGroupApi

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.