org.jclouds.compute.functions.GroupNamingConvention类的使用及代码示例

x33g5p2x  于2022-01-20 转载在 其他  
字(20.3k)|赞(0)|评价(0)|浏览(80)

本文整理了Java中org.jclouds.compute.functions.GroupNamingConvention类的一些代码示例,展示了GroupNamingConvention类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。GroupNamingConvention类的具体详情如下:
包路径:org.jclouds.compute.functions.GroupNamingConvention
类名称:GroupNamingConvention

GroupNamingConvention介绍

[英]jclouds needs to understand the difference between resources it creates and those supplied by the user. For example, if jclouds creates a security group, it should be able to delete this as a part of cleanup without accidentally deleting resources the user specified manually.

uniqueness of a name

The naming convention must apply to both to resources shared across all members of a group, and those created for a subset of members.

  1. shared: something shared across all members of a group, and fully retrievable via api. Ex. security group or network
  2. unique: something that only applies to individuals or subsets of a group, or isn't fully retrievable via api. Ex. node names or keypair names
why repeat?

Some resources we'd otherwise want to share across a group must be redundantly created, if the user has no access to the complete object via api or otherwise. For example, ssh key apis generally do not store the private key data on the server. In order to ensure we can always log into a server without configuration, we may generate a temporary key on-demand for each call to ComputeService#createNodesInGroupTypically, a security group or network is something shared across all members of a group, so the name should be concise, yet unique. implementation Typically, a security group or network is something shared across all members of a group, so the name should be concise, yet unique.

character sets and delimiters

Character sets in apis are often bound to dns names, perhaps also allowing underscores. Since jclouds groups are allowed to be alphanumeric with hyphens (hostname style), care must be taken to implement this in a way that allows the delimiter to be also nested in the group name itself. In other words, we need to be able to encode a group into a name even when they share the same character set. Note that characters like # can sometimes break apis. As such, you may end preferring always using a hyphen.

shared resources

A good name for a shared resources might include a prefix of jclouds, a delimiter of - followed by the group name. The jclouds prefix signifies this resource is safe to delete, and the hash clearly delineates the encoding from what's in the group name.

example

given a jclouds group named mycluster, the naming convention for shared resources would produce jclouds-mycluster

unique resources

A good name for a unique resource might be the same as the shared, with a random hex string suffix. A few hex characters can give you 4096 combinations, giving a small degree of collision avoidance, yet without making the resource name difficult.

example

given a jclouds group named mycluster, the naming convention for unique resources could produce jclouds-mycluster-f3e the first time, and jclouds-mycluster-e64 the next.

note

It is typically safe to assume that an IllegalStateException is thrown when attempting to create a named resource which already exists. However, if you attempt to create a resource with a name generated by GroupNamingConvention, and receive an IllegalStateException, it may have been for another reason besides name conflict.
[中]jclouds需要理解它创建的资源和用户提供的资源之间的差异。例如,如果jclouds创建了一个安全组,那么它应该能够将其作为清理的一部分删除,而不会意外删除用户手动指定的资源。
####名称的唯一性
命名约定必须既适用于组中所有成员共享的资源,也适用于为成员子集创建的资源。
1.共享:在一个组的所有成员之间共享的东西,可以通过api完全检索。例如,安全组或网络
1.唯一性:仅适用于个人或组的子集,或不能通过api完全检索的内容。例如节点名称或密钥对名称
#####为什么要重复?
如果用户无法通过api或其他方式访问整个对象,则必须冗余地创建我们希望在组中共享的某些资源。例如,ssh密钥API通常不在服务器上存储私钥数据。为了确保我们始终可以在不进行配置的情况下登录到服务器,我们可以为ComputeService#CreateNodeSingGroup的每次调用按需生成一个临时密钥通常,安全组或网络是在组的所有成员之间共享的,因此名称应该简洁,但唯一。实现通常,安全组或网络是一个组的所有成员共享的东西,因此名称应该简洁、唯一。
#####字符集和分隔符
API中的字符集通常绑定到dns名称,可能还允许使用下划线。由于jclouds组可以是字母数字加连字符(主机名样式),因此必须注意以允许分隔符也嵌套在组名本身中的方式实现这一点。换句话说,我们需要能够将一个组编码为一个名称,即使它们共享相同的字符集。请注意,像#这样的字符有时会破坏API。因此,您可能会选择始终使用连字符。
#####共享资源
共享资源的好名称可能包括前缀jclouds,分隔符-后跟组名。jclouds前缀表示此资源可以安全删除,哈希表清楚地描述了组名中的编码。
####范例
给定名为mycluster的jclouds组,共享资源的命名约定将生成jclouds mycluster
#####独特资源
唯一资源的好名称可能与共享名称相同,带有随机十六进制字符串后缀。几个十六进制字符可以为您提供4096个组合,从而在一定程度上避免冲突,但不会使资源名称变得困难。
####范例
给定一个名为mycluster的jclouds组,唯一资源的命名约定可以第一次生成jclouds-mycluster-f3e,第二次生成jclouds-mycluster-e64。
####注
通常可以安全地假设,在尝试创建已存在的命名资源时,会引发IllegalStateException。但是,如果您试图使用GroupNamingConvention生成的名称创建资源,并收到一个IllegalStateException,则可能是由于名称冲突之外的其他原因。

代码示例

代码示例来源:origin: jclouds/legacy-jclouds

public void testPropertyChangesDelimiter() {
 GroupNamingConvention fn = Guice.createInjector(new AbstractModule() {
   @Override
   protected void configure() {
    bindConstant().annotatedWith(Names.named(RESOURCENAME_DELIMITER)).to('#');
   }
 }).getInstance(GroupNamingConvention.Factory.class).create();
 assertEquals(fn.sharedNameForGroup("cluster"), "jclouds#cluster");
 assertEquals(fn.groupInSharedNameOrNull("jclouds#cluster"), "cluster");
 assertEquals(fn.groupInUniqueNameOrNull("jclouds#cluster"), null);
 assertTrue(fn.containsGroup("cluster").apply("jclouds#cluster"));
}

代码示例来源:origin: org.apache.jclouds.api/ec2

@VisibleForTesting
  KeyPair createNewKeyPairInRegion(String region, String group) {
   checkNotNull(region, "region");
   checkNotNull(group, "group");
   logger.debug(">> creating keyPair region(%s) group(%s)", region, group);
   KeyPair keyPair = null;
   String prefix = group;
   
   while (keyPair == null) {
     String keyName = namingConvention.create().uniqueNameForGroup(prefix);
     try {
      keyPair = ec2Api.getKeyPairApi().get().createKeyPairInRegion(region, keyName);
     } catch (IllegalStateException e) {
      logger.trace("   invalid keyname (%s in %s); retrying", keyName, region);
     }
   }
   
   logger.debug("<< created keyPair(%s)", keyPair);
   return keyPair;
  }
}

代码示例来源:origin: jclouds/legacy-jclouds

private String parseGroupFrom(final RunningInstance instance, final Set<String> data) {
 String group = null;
 try {
   Predicate<String> containsAnyGroup = namingConvention.create().containsAnyGroup();
   String encodedGroup = Iterables.getOnlyElement(Iterables.filter(data, containsAnyGroup));
   group = namingConvention.create().extractGroup(encodedGroup);
 } catch (NoSuchElementException e) {
   logger.debug("no group parsed from %s's data: %s", instance.getId(), data);
 } catch (IllegalArgumentException e) {
   logger.debug("too many groups match naming convention; %s's data: %s", instance.getId(), data);
 }
 return group;
}

代码示例来源:origin: jclouds/legacy-jclouds

public void testCanChangeSuffixSupplier() {
 GroupNamingConvention fn = Guice.createInjector(new AbstractModule() {
   @Override
   protected void configure() {
    bind(new TypeLiteral<Supplier<String>>() {
    }).toInstance(Suppliers.ofInstance("foo"));
   }
 }).getInstance(GroupNamingConvention.Factory.class).create();
 assertEquals(fn.uniqueNameForGroup("cluster"), "jclouds-cluster-foo");
 // note accidental treatment of a unique node as a shared one can lead to 
 // incorrect group names, as long as we permit delimiter to be in group name
 assertEquals(fn.groupInSharedNameOrNull("jclouds-cluster-foo"), "cluster-foo");
 assertEquals(fn.groupInUniqueNameOrNull("jclouds-cluster-foo"), "cluster");
 assertTrue(fn.containsGroup("cluster").apply("jclouds-cluster-foo"));
}

代码示例来源:origin: jclouds/legacy-jclouds

private void cleanupOrphanedKeyPairsInZone(Set<String> groups, String zoneId) {
 Optional<? extends KeyPairApi> keyPairApi = novaApi.getKeyPairExtensionForZone(zoneId);
 if (keyPairApi.isPresent()) {
   for (String group : groups) {
    for (KeyPair pair : keyPairApi.get().list().filter(nameMatches(namingConvention.create().containsGroup(group)))) {
      ZoneAndName zoneAndName = ZoneAndName.fromZoneAndName(zoneId, pair.getName());
      logger.debug(">> deleting keypair(%s)", zoneAndName);
      keyPairApi.get().delete(pair.getName());
      // TODO: test this clear happens
      keyPairCache.invalidate(zoneAndName);
      logger.debug("<< deleted keypair(%s)", zoneAndName);
    }
    keyPairCache.invalidate(ZoneAndName.fromZoneAndName(zoneId,
         namingConvention.create().sharedNameForGroup(group)));
   }
 }
}

代码示例来源:origin: org.apache.jclouds.labs/cloudsigma2

@Override
public NodeMetadata apply(ServerInfo serverInfo) {
 NodeMetadataBuilder builder = new NodeMetadataBuilder();
 builder.ids(serverInfo.getUuid());
 builder.name(serverInfo.getName());
 builder.group(groupNamingConventionWithoutPrefix.extractGroup(serverInfo.getName()));
 builder.location(getOnlyElement(locations.get()));
 builder.hardware(new HardwareBuilder().ids(serverInfo.getUuid()).processor(new Processor(1, serverInfo.getCpu()))
    .ram(serverInfo.getMemory().intValue())
    .volumes(Iterables.transform(serverInfo.getDrives(), serverDriveToVolume)).build());
 builder.tags(readTags(serverInfo));
 builder.userMetadata(serverInfo.getMeta());
 builder.imageId(extractImageId(serverInfo));
 builder.status(serverStatusToNodeStatus.get(serverInfo.getStatus()));
 builder.publicAddresses(filter(transform(serverInfo.getNics(), nicToAddress), notNull()));
 // CloudSigma does not provide a way to get the credentials.
 // Try to return them from the credential store
 Credentials credentials = credentialStore.get("node#" + serverInfo.getUuid());
 if (credentials instanceof LoginCredentials) {
   builder.credentials(LoginCredentials.class.cast(credentials));
 }
 return builder.build();
}

代码示例来源:origin: jclouds/legacy-jclouds

@VisibleForTesting
void deleteKeyPair(String region, String group) {
 for (KeyPair keyPair : client.getKeyPairServices().describeKeyPairsInRegion(region)) {
   String keyName = keyPair.getKeyName();
   Predicate<String> keyNameMatcher = namingConvention.create().containsGroup(group);
   String oldKeyNameRegex = String.format("jclouds#%s#%s#%s", group, region, "[0-9a-f]+").replace('#', delimiter);
   // old keypair pattern too verbose as it has an unnecessary region qualifier
      if (keyNameMatcher.apply(keyName) || keyName.matches(oldKeyNameRegex)) {
    Set<String> instancesUsingKeyPair = extractIdsFromInstances(filter(concat(client.getInstanceServices()
       .describeInstancesInRegion(region)), usingKeyPairAndNotDead(keyPair)));
    if (instancesUsingKeyPair.size() > 0) {
      logger.debug("<< inUse keyPair(%s), by (%s)", keyPair.getKeyName(), instancesUsingKeyPair);
    } else {
      logger.debug(">> deleting keyPair(%s)", keyPair.getKeyName());
      client.getKeyPairServices().deleteKeyPairInRegion(region, keyPair.getKeyName());
      // TODO: test this clear happens
      credentialsMap.remove(new RegionAndName(region, keyPair.getKeyName()));
      credentialsMap.remove(new RegionAndName(region, group));
      logger.debug("<< deleted keyPair(%s)", keyPair.getKeyName());
    }
   }
 }
}

代码示例来源:origin: com.amysta.jclouds.api/openstack-nova

public SecurityGroup createSecurityGroup(String name, String region) {
 String markerGroup = namingConvention.create().sharedNameForGroup(name);
 RegionSecurityGroupNameAndPorts regionAndName = new RegionSecurityGroupNameAndPorts(region, markerGroup, ImmutableSet.<Integer> of());
 SecurityGroupInRegion rawGroup = groupCreator.getUnchecked(regionAndName);
 return groupConverter.apply(rawGroup);
}

代码示例来源:origin: org.apache.jclouds.labs/azurecompute-arm

private void configureSecurityGroupForOptions(String group, Location location, AzureTemplateOptions options) {
 checkArgument(options.getGroups().size() <= 1,
    "Only one security group can be configured for each network interface");
 if (!options.getGroups().isEmpty()) {
   ResourceGroupAndName securityGroupId = ResourceGroupAndName.fromSlashEncoded(getOnlyElement(options.getGroups()));
   NetworkSecurityGroup securityGroup = api.getNetworkSecurityGroupApi(securityGroupId.resourceGroup()).get(
      securityGroupId.name());
   checkArgument(securityGroup != null, "Security group %s was not found", securityGroupId.slashEncode());
   options.securityGroups(securityGroup.id());
 } else if (options.getInboundPorts().length > 0) {
   String name = namingConvention.create().sharedNameForGroup(group);
   ResourceGroupAndNameAndIngressRules regionAndIdAndIngressRules = ResourceGroupAndNameAndIngressRules.create(
      options.getResourceGroup(), location.getId(), name, options.getInboundPorts());
   // this will create if not yet exists.
   String securityGroupId = securityGroupMap.getUnchecked(regionAndIdAndIngressRules);
   options.securityGroups(securityGroupId);
 }
}

代码示例来源:origin: org.apache.jclouds.provider/profitbricks

Location location = find(locations.get(), idEquals(dataCenter.location().getId()));
    .group(groupNamingConvention.extractGroup(server.name()))
    .hostname(server.hostname())
    .name(server.name())
    .operatingSystem(mapOsType(server.osType()))
    .location(location)
    .privateAddresses(Iterables.filter(addresses, IsPrivateIPAddress.INSTANCE))
    .publicAddresses(Iterables.filter(addresses, not(IsPrivateIPAddress.INSTANCE)));

代码示例来源:origin: org.apache.jclouds.api/ec2

@VisibleForTesting
void deleteKeyPair(String region, String group) {
 for (KeyPair keyPair : client.getKeyPairApi().get().describeKeyPairsInRegionWithFilter(region,
     ImmutableMultimap.<String, String>builder()
         .put("key-name", String.format("jclouds#%s#*", group).replace('#', delimiter))
         .build())) {
   String keyName = keyPair.getKeyName();
   Predicate<String> keyNameMatcher = namingConvention.create().containsGroup(group);
   String oldKeyNameRegex = String.format("jclouds#%s#%s#%s", group, region, "[0-9a-f]+").replace('#', delimiter);
   // old keypair pattern too verbose as it has an unnecessary region qualifier
   if (keyNameMatcher.apply(keyName) || keyName.matches(oldKeyNameRegex)) {
    Set<String> instancesUsingKeyPair = extractIdsFromInstances(concat(client.getInstanceApi().get()
       .describeInstancesInRegionWithFilter(region, ImmutableMultimap.<String, String>builder()
           .put("instance-state-name", InstanceState.TERMINATED.toString())
           .put("instance-state-name", InstanceState.SHUTTING_DOWN.toString())
           .put("key-name", keyPair.getKeyName()).build())));
    if (!instancesUsingKeyPair.isEmpty()) {
      logger.debug("<< inUse keyPair(%s), by (%s)", keyPair.getKeyName(), instancesUsingKeyPair);
    } else {
      logger.debug(">> deleting keyPair(%s)", keyPair.getKeyName());
      client.getKeyPairApi().get().deleteKeyPairInRegion(region, keyPair.getKeyName());
      // TODO: test this clear happens
      credentialsMap.remove(new RegionAndName(region, keyPair.getKeyName()));
      credentialsMap.remove(new RegionAndName(region, group));
      logger.debug("<< deleted keyPair(%s)", keyPair.getKeyName());
    }
   }
 }
}

代码示例来源:origin: org.apache.jclouds.labs/docker

@Override
public NodeMetadata apply(Container container) {
 String name = cleanUpName(container.name());
 String group = nodeNamingConvention.extractGroup(name);
 NodeMetadataBuilder builder = new NodeMetadataBuilder();
 builder.ids(container.id())
     .name(name)
     .group(group)
     .hostname(container.config().hostname())
     // TODO Set up hardware
     .hardware(new HardwareBuilder()
         .id("")
         .ram(container.config().memory())
         .processor(new Processor(container.config().cpuShares(), container.config().cpuShares()))
         .build());
 builder.status(toPortableStatus.apply(container.state()));
 builder.loginPort(loginPortForContainer.apply(container).or(NO_LOGIN_PORT));
 builder.publicAddresses(getPublicIpAddresses(container));
 builder.privateAddresses(getPrivateIpAddresses(container));
 builder.location(Iterables.getOnlyElement(locations.get()));
 String imageId = container.image();
 builder.imageId(imageId);
 if (images.get().containsKey(imageId)) {
   Image image = images.get().get(imageId);
   builder.operatingSystem(image.getOperatingSystem());
 }
 return builder.build();
}

代码示例来源:origin: jclouds/legacy-jclouds

@Override
public NodeMetadata apply(ServerInfo from) {
 NodeMetadataBuilder builder = new NodeMetadataBuilder();
 builder.ids(from.getUuid());
 builder.name(from.getName());
 builder.location(locationSupplier.get());
 builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getName()));
 String imageId = getImageIdFromServer.apply(from);
 if (imageId != null) {
   Optional<? extends Image> image = FluentIterable.from(images.get()).firstMatch(idEquals(imageId));
   if (image.isPresent()) {
    builder.operatingSystem(image.get().getOperatingSystem());
   }
 }
 builder.hardware(new HardwareBuilder().ids(from.getUuid()).hypervisor("kvm")
    .processors(ImmutableList.of(new Processor(1, from.getCpu()))).ram(from.getMem())
    .volumes(Iterables.transform(from.getDevices().values(), deviceToVolume)).build());
 builder.status(serverStatusToNodeStatus.get(from.getStatus()));
 builder.publicAddresses(ImmutableSet.<String> of(from.getVnc().getIp()));
 builder.privateAddresses(ImmutableSet.<String> of());
 return builder.build();
}

代码示例来源:origin: org.apache.jclouds.api/openstack-nova

@Override
public SecurityGroup createSecurityGroup(String name, Location location) {
 String region = location.getId();
 if (region == null) {
   return null;
 }
 logger.debug(">> creating security group %s in %s...", name, location);
 String markerGroup = namingConvention.create().sharedNameForGroup(name);
 RegionSecurityGroupNameAndPorts regionAndName = new RegionSecurityGroupNameAndPorts(region, markerGroup, ImmutableSet.<Integer> of());
 return groupCreator.getUnchecked(regionAndName);
}

代码示例来源:origin: jclouds/legacy-jclouds

@Override
public NodeMetadata apply(Server from) {
 NodeMetadataBuilder builder = new NodeMetadataBuilder();
 builder.ids(from.getId() + "");
 builder.name(from.getName());
 Location location = Iterables.find(locations.get(), LocationPredicates.idEquals(from.getDatacenter().getId() + ""));
 builder.location(location);
 builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getName()));
 builder.hardware(parseHardware(from));
 builder.imageId(from.getImage().getId() + "");
 Image image = parseImage(from);
 if (image != null)
   builder.operatingSystem(image.getOperatingSystem());
 builder.status(serverStateToNodeStatus.get(from.getState()));
 builder.publicAddresses(ImmutableSet.of(from.getIp().getIp()));
 return builder.build();
}

代码示例来源:origin: io.cloudsoft.jclouds/jclouds-compute

Set<String> nodeNames = template.getOptions().getNodeNames();
if (nodeNames.size() >= count) {
  return ImmutableSet.copyOf(Iterables.limit(nodeNames, count));
} else {
  names.addAll(nodeNames);
int currentTries = 0;
while (names.size() < count && currentTries++ < maxTries) {
  final String name = namingConvention.createWithoutPrefix().uniqueNameForGroup(group);
  if (!any(currentNodes, new Predicate<ComputeMetadata>() {

代码示例来源:origin: com.amysta.jclouds.api/ec2

/**
* @throws IllegalStateException If the security group was in use
*/
@VisibleForTesting
void deleteSecurityGroup(String region, String group) {
 checkNotNull(emptyToNull(region), "region must be defined");
 checkNotNull(emptyToNull(group), "group must be defined");
 String groupName = namingConvention.create().sharedNameForGroup(group);
 if (!client.getSecurityGroupApi().get().describeSecurityGroupsInRegion(region, groupName).isEmpty()) {
   logger.debug(">> deleting securityGroup(%s)", groupName);
   client.getSecurityGroupApi().get().deleteSecurityGroupInRegion(region, groupName);
   // TODO: test this clear happens
   securityGroupMap.invalidate(new RegionNameAndIngressRules(region, groupName, null, false, null));
   logger.debug("<< deleted securityGroup(%s)", groupName);
 }
}

代码示例来源:origin: org.apache.jclouds.api/openstack-nova

private KeyPair generateKeyPair(String region, String prefix) {
 logger.debug(">> creating default keypair for node...");
 KeyPair keyPair = novaApi.getKeyPairApi(region).get().create(namingConvention.createWithoutPrefix().uniqueNameForGroup(prefix));
 logger.debug(">> keypair created! %s", keyPair.getName());
 return keyPair;
}

代码示例来源:origin: jclouds/legacy-jclouds

/**
* Find the next node names that can be used. These will be derived from the group and the
* template. We will pre-allocate a specified quantity, and attempt to verify that there is no
* name conflict with the current service.
* 
* @param group
* @param count
* @param template
* @return
*/
protected Set<String> getNextNames(final String group, final Template template, int count) {
 Set<String> names = newLinkedHashSet();
 Iterable<? extends ComputeMetadata> currentNodes = listNodesStrategy.listNodes();
 int maxTries = 100;
 int currentTries = 0;
 while (names.size() < count && currentTries++ < maxTries) {
   final String name = namingConvention.createWithoutPrefix().uniqueNameForGroup(group);
   if (!any(currentNodes, new Predicate<ComputeMetadata>() {
    @Override
    public boolean apply(ComputeMetadata input) {
      return name.equals(input.getName());
    }
   })) {
    names.add(name);
   }
 }
 return names;
}

代码示例来源:origin: com.amysta.jclouds.provider/google-compute-engine

private void cleanUpFirewallsForGroup(final String groupName) {
 GroupNamingConvention namingScheme = namingConvention.create();
 FirewallApi firewallApi = api.firewalls();
 for (Firewall firewall : concat(firewallApi.list())) {
   String foundGroup = namingScheme.groupInUniqueNameOrNull(firewall.name());
   if ((foundGroup != null) && foundGroup.equals(groupName)){
    AtomicReference<Operation> operation = Atomics.newReference(firewallApi.delete(firewall.name()));
    operationDone.apply(operation);
    if (operation.get().httpErrorStatusCode() != null) {
      logger.warn("delete orphaned firewall %s failed. Http Error Code: %d HttpError: %s",
         operation.get().targetId(), operation.get().httpErrorStatusCode(),
         operation.get().httpErrorMessage());
    }
   }
 }
}

相关文章