@Override
 public NodeMetadata apply(RunningInstance instance) {
   if (instance == null || instance.getId() == null) return null;
   NodeMetadataBuilder builder = new NodeMetadataBuilder();
   builder = buildInstance(instance, builder);
   return builder.build();
 }
 @Override
 public NodeMetadata getNode(String id) {
   NodeMetadata node = nodes.get(id);
   return node == null
       ? null
       : NodeMetadataBuilder.fromNodeMetadata(node)
           .credentials(credentialStore.get("node#" + node.getId()))
           .build();
 }
  @Override
  public NodeMetadata apply(@Nullable IMachine vm) {

    NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder();
    String s = vm.getName();
    nodeMetadataBuilder.name(s);

    // TODO Set up location properly
    LocationBuilder locationBuilder = new LocationBuilder();
    locationBuilder.description("");
    locationBuilder.id("");
    locationBuilder.scope(LocationScope.HOST);
    nodeMetadataBuilder.location(locationBuilder.build());

    HardwareBuilder hardwareBuilder = new HardwareBuilder();
    hardwareBuilder.ram(vm.getMemorySize().intValue());

    // TODO: Get more processor information
    Set<Processor> processors = new HashSet<Processor>();
    for (int i = 0; i < vm.getCPUCount(); i++) {
      Processor processor = new Processor(1, 0);
      processors.add(processor);
    }
    hardwareBuilder.processors(processors);

    // TODO: How to get this?
    hardwareBuilder.is64Bit(false);

    nodeMetadataBuilder.hostname(vm.getName());
    nodeMetadataBuilder.loginPort(18083);

    MachineState vmState = vm.getState();
    NodeState nodeState = machineToNodeState.get(vmState);
    if (nodeState == null) nodeState = NodeState.UNRECOGNIZED;
    nodeMetadataBuilder.state(nodeState);

    logger.debug("Setting virtualbox node to: " + nodeState + " from machine state: " + vmState);

    INetworkAdapter networkAdapter = vm.getNetworkAdapter(0l);
    if (networkAdapter != null) {
      String bridgedInterface = networkAdapter.getBridgedInterface();
      System.out.println("Interface: " + bridgedInterface);
    }

    // nodeMetadataBuilder.imageId("");
    // nodeMetadataBuilder.group("");

    nodeMetadataBuilder.id(vm.getId());
    return nodeMetadataBuilder.build();
  }
 @Override
 protected void addCredentialsForInstance(NodeMetadataBuilder builder, RunningInstance instance) {
   LoginCredentials creds =
       LoginCredentials.fromCredentials(
           credentialStore.get("node#" + instance.getRegion() + "/" + instance.getId()));
   String spotRequestId = AWSRunningInstance.class.cast(instance).getSpotInstanceRequestId();
   if (creds == null && spotRequestId != null) {
     creds =
         LoginCredentials.fromCredentials(
             credentialStore.get("node#" + instance.getRegion() + "/" + spotRequestId));
     if (creds != null)
       credentialStore.put("node#" + instance.getRegion() + "/" + instance.getId(), creds);
   }
   if (creds != null) builder.credentials(creds);
 }
  @Override
  public NodeMetadata apply(final VirtualGuest from) {

    // convert the result object to a jclouds NodeMetadata
    NodeMetadataBuilder builder = new NodeMetadataBuilder();
    builder.ids(from.getId() + "");
    builder.name(from.getHostname());
    builder.hostname(from.getHostname());
    builder.status(serverStateToNodeStatus.get(from.getPowerState().getKeyName()));

    // These are null for 'bad' guest orders in the HALTED state.
    if (from.getPrimaryIpAddress() != null)
      builder.publicAddresses(ImmutableSet.<String>of(from.getPrimaryIpAddress()));
    if (from.getPrimaryBackendIpAddress() != null)
      builder.privateAddresses(ImmutableSet.<String>of(from.getPrimaryBackendIpAddress()));
    return builder.build();
  }
 public void refreshSshIfNewAdminCredentialsConfigured(AdminAccess input) {
   if (input.getAdminCredentials() != null && input.shouldGrantSudoToAdminUser()) {
     ssh.disconnect();
     logger.debug(
         ">> reconnecting as %s@%s", input.getAdminCredentials().identity, ssh.getHostAddress());
     ssh =
         sshFactory.apply(
             node =
                 NodeMetadataBuilder.fromNodeMetadata(node)
                     .adminPassword(null)
                     .credentials(input.getAdminCredentials())
                     .build());
     ssh.connect();
     setupLinkToInitFile();
   }
 }
 protected void addCredentialsForInstance(NodeMetadataBuilder builder, RunningInstance instance) {
   builder.credentials(
       LoginCredentials.fromCredentials(
           credentialStore.get("node#" + instance.getRegion() + "/" + instance.getId())));
 }
  protected NodeMetadataBuilder buildInstance(
      final RunningInstance instance, NodeMetadataBuilder builder) {
    builder.providerId(instance.getId());
    builder.id(instance.getRegion() + "/" + instance.getId());
    String group = getGroupForInstance(instance);
    builder.group(group);
    // standard convention from aws-ec2, which might not be re-used outside.
    if (instance.getPrivateDnsName() != null)
      builder.hostname(instance.getPrivateDnsName().replaceAll("\\..*", ""));
    addCredentialsForInstance(builder, instance);
    builder.status(instanceToNodeStatus.get(instance.getInstanceState()));
    builder.backendStatus(instance.getRawState());

    // collect all ip addresses into one bundle in case the api mistakenly put a private address
    // into the public address field
    Builder<String> addressesBuilder = ImmutableSet.builder();
    if (Strings.emptyToNull(instance.getIpAddress()) != null)
      addressesBuilder.add(instance.getIpAddress());
    // Add dnsName (if available) to addresses, when the IPAddress is null
    // happens on Eucalyptus sometimes.
    else if (Strings.emptyToNull(instance.getDnsName()) != null)
      addressesBuilder.add(instance.getDnsName());
    if (Strings.emptyToNull(instance.getPrivateIpAddress()) != null)
      addressesBuilder.add(instance.getPrivateIpAddress());

    Set<String> addresses = addressesBuilder.build();

    builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE)));
    builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE));
    builder.hardware(parseHardware(instance));
    Location location = getLocationForAvailabilityZoneOrRegion(instance);
    builder.location(location);
    builder.imageId(instance.getRegion() + "/" + instance.getImageId());

    // extract the operating system from the image
    RegionAndName regionAndName = new RegionAndName(instance.getRegion(), instance.getImageId());
    try {
      Image image = imageMap.get().getUnchecked(regionAndName);
      if (image != null) builder.operatingSystem(image.getOperatingSystem());
    } catch (CacheLoader.InvalidCacheLoadException e) {
      logger.debug("image not found for %s: %s", regionAndName, e);
    } catch (UncheckedExecutionException e) {
      logger.debug("error getting image for %s: %s", regionAndName, e);
    }
    return builder;
  }
 @Override
 public NodeMetadata apply(VirtualGuest from) {
   NodeMetadataBuilder builder = new NodeMetadataBuilder();
   builder.ids(from.getId() + "");
   builder.name(from.getHostname());
   builder.hostname(from.getFullyQualifiedDomainName());
   if (from.getDatacenter() != null) {
     builder.location(
         from(locations.get())
             .firstMatch(LocationPredicates.idEquals(from.getDatacenter().getName()))
             .orNull());
   }
   builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getHostname()));
   builder.hardware(virtualGuestToHardware.apply(from));
   Image image = virtualGuestToImage.apply(from);
   if (image != null) {
     builder.imageId(image.getId());
     builder.operatingSystem(image.getOperatingSystem());
   }
   if (from.getPowerState() != null) {
     builder.status(serverStateToNodeStatus.get(from.getPowerState().getKeyName()));
   }
   if (from.getPrimaryIpAddress() != null)
     builder.publicAddresses(ImmutableSet.of(from.getPrimaryIpAddress()));
   if (from.getPrimaryBackendIpAddress() != null)
     builder.privateAddresses(ImmutableSet.of(from.getPrimaryBackendIpAddress()));
   // TODO simplify once we move domain classes to AutoValue
   if (from.getOperatingSystem() != null
       && from.getOperatingSystem().getPasswords() != null
       && !from.getOperatingSystem().getPasswords().isEmpty()) {
     Password password = getBestPassword(from.getOperatingSystem().getPasswords(), from);
     builder.credentials(
         LoginCredentials.builder()
             .identity(password.getUsername())
             .credential(password.getPassword())
             .build());
   }
   if (from.getTagReferences() != null && !from.getTagReferences().isEmpty()) {
     List<String> tags = Lists.newArrayList();
     for (TagReference tagReference : from.getTagReferences()) {
       if (tagReference != null) {
         tags.add(tagReference.getTag().getName());
       }
     }
     builder.tags(tags);
   }
   return builder.build();
 }
  @Override
  public NodeMetadata apply(VirtualMachine from) {

    // convert the result object to a jclouds NodeMetadata
    NodeMetadataBuilder builder = new NodeMetadataBuilder();
    try {
      builder.id(from.getConfig().getInstanceUuid());
      builder.providerId(from.getConfig().getLocationId() + "");
      builder.name(from.getName());
      builder.location(findLocationForVirtualMachine.apply(from));
      builder.group(parseGroupFromName(from.getName()));

      builder.operatingSystem(
          new OperatingSystemBuilder()
              .name(from.getConfig().getGuestFullName())
              .description(from.getConfig().getGuestFullName())
              .is64Bit(from.getConfig().getGuestId().contains("64"))
              .build());
      builder.hardware(findHardwareForVirtualMachine.apply(from));

      builder.state(domainStateToNodeState.get(from.getRuntime().getPowerState()));
      // builder.publicAddresses(ImmutableSet.<String> of(from.publicAddress));
      // builder.privateAddresses(ImmutableSet.<String> of(from.privateAddress));
      builder.credentials(credentialStore.get("node#" + from.getName()));

    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return builder.build();
  }
  @Override
  public NodeMetadata apply(ServerInZone serverInZone) {
    Location zone = locationIndex.get().get(serverInZone.getZone());
    checkState(
        zone != null,
        "location %s not in locationIndex: %s",
        serverInZone.getZone(),
        locationIndex.get());
    Server from = serverInZone.getServer();

    NodeMetadataBuilder builder = new NodeMetadataBuilder();
    builder.id(serverInZone.slashEncode());
    builder.providerId(from.getId());
    builder.name(from.getName());
    builder.hostname(from.getName());
    builder.location(
        from.getHostId() != null
            ? new LocationBuilder()
                .scope(LocationScope.HOST)
                .id(from.getHostId())
                .description(from.getHostId())
                .parent(zone)
                .build()
            : zone);
    addMetadataAndParseTagsFromCommaDelimitedValue(builder, from.getMetadata());
    builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.getName()));
    builder.imageId(
        ZoneAndId.fromZoneAndId(serverInZone.getZone(), from.getImage().getId()).slashEncode());
    builder.operatingSystem(findOperatingSystemForServerOrNull(serverInZone));
    builder.hardware(findHardwareForServerOrNull(serverInZone));
    builder.status(from.getStatus().getNodeStatus());
    builder.publicAddresses(
        filter(
            transform(
                filter(from.getAddresses().values(), Predicates.not(isPrivateAddress)),
                AddressToStringTransformationFunction.INSTANCE),
            isInet4Address));
    builder.privateAddresses(
        filter(
            transform(
                filter(from.getAddresses().values(), isPrivateAddress),
                AddressToStringTransformationFunction.INSTANCE),
            isInet4Address));

    return builder.build();
  }
  @Override
  public NodeMetadata apply(VirtualMachine from) {
    // convert the result object to a jclouds NodeMetadata
    NodeMetadataBuilder builder = new NodeMetadataBuilder();
    builder.ids(from.getId() + "");
    builder.name(from.getName());
    // TODO: in cloudstack 2.2.12, when "name" was set fine on the backend,
    // but wrong API response was returned to the user
    // http://bugs.cloud.com/show_bug.cgi?id=11664
    //
    // we set displayName to the same value as name, but this could be wrong
    // on hosts not started with jclouds
    builder.hostname(from.getDisplayName());
    builder.location(findLocationForVirtualMachine.apply(from));
    builder.group(parseGroupFromName(from.getDisplayName()));
    Image image = findImageForVirtualMachine.apply(from);
    if (image != null) {
      builder.imageId(image.getId());
      builder.operatingSystem(image.getOperatingSystem());
    }

    builder.hardware(
        new HardwareBuilder()
            .ids(from.getServiceOfferingId() + "")
            .name(from.getServiceOfferingName() + "")
            // .tags() TODO
            .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed())))
            .ram((int) from.getMemory()) //
            .hypervisor(from.getHypervisor()) //
            .build());

    builder.state(vmStateToNodeState.get(from.getState()));

    Set<String> publicAddresses = newHashSet(), privateAddresses = newHashSet();
    if (from.getIPAddress() != null) {
      boolean isPrivate = isPrivateIPAddress(from.getIPAddress());
      if (isPrivate) {
        privateAddresses.add(from.getIPAddress());
      } else {
        publicAddresses.add(from.getIPAddress());
      }
    }
    for (NIC nic : from.getNICs()) {
      if (nic.getIPAddress() != null) {
        if (isPrivateIPAddress(nic.getIPAddress())) {
          privateAddresses.add(nic.getIPAddress());
        } else {
          publicAddresses.add(nic.getIPAddress());
        }
      }
    }
    try {
      /* Also add to the list of public IPs any public IP address that has a
      forwarding rule that links to this machine */
      Iterables.addAll(
          publicAddresses,
          transform(
              filter(
                  getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()),
                  new Predicate<IPForwardingRule>() {
                    @Override
                    public boolean apply(@Nullable IPForwardingRule rule) {
                      return !"Deleting".equals(rule.getState());
                    }
                  }),
              new Function<IPForwardingRule, String>() {
                @Override
                public String apply(@Nullable IPForwardingRule rule) {
                  return rule.getIPAddress();
                }
              }));
    } catch (UncheckedExecutionException e) {
      if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) {
        Throwables.propagateIfPossible(e.getCause());
        throw e;
      }
    }
    return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build();
  }
 @Override
 public NodeMetadata apply(Server from) {
   NodeMetadataBuilder builder = new NodeMetadataBuilder();
   builder.ids(from.getId() + "");
   builder.name(from.getName());
   builder.hostname(from.getName());
   builder.location(
       new LocationBuilder()
           .scope(LocationScope.HOST)
           .id(from.getHostId())
           .description(from.getHostId())
           .parent(location.get())
           .build());
   addMetadataAndParseTagsFromCommaDelimitedValue(builder, from.getMetadata());
   builder.group(groupFromMapOrName(from.getMetadata(), from.getName(), nodeNamingConvention));
   builder.imageId(from.getImageId() + "");
   builder.operatingSystem(parseOperatingSystem(from));
   builder.hardware(parseHardware(from));
   builder.status(serverToNodeStatus.get(from.getStatus()));
   builder.publicAddresses(from.getAddresses().getPublicAddresses());
   builder.privateAddresses(from.getAddresses().getPrivateAddresses());
   return builder.build();
 }
 @Override
 public NodeMetadata createNodeWithGroupEncodedIntoNameThenStoreCredentials(
     String group, String name, Template template, Map<String, Credentials> credentialStore) {
   NodeMetadataBuilder builder = new NodeMetadataBuilder();
   String id = idProvider.get() + "";
   builder.ids(id);
   builder.name(name);
   // using a predictable name so tests will pass
   builder.hostname(group);
   builder.tags(template.getOptions().getTags());
   builder.group(group);
   builder.location(location.get());
   builder.imageId(template.getImage().getId());
   builder.operatingSystem(template.getImage().getOperatingSystem());
   builder.state(NodeState.PENDING);
   builder.publicAddresses(ImmutableSet.<String>of(publicIpPrefix + id));
   builder.privateAddresses(ImmutableSet.<String>of(privateIpPrefix + id));
   Credentials creds = template.getOptions().getOverridingCredentials();
   if (creds == null) creds = new Credentials(null, null);
   if (creds.identity == null) creds = creds.toBuilder().identity("root").build();
   if (creds.credential == null) creds = creds.toBuilder().credential(passwordPrefix + id).build();
   builder.credentials(creds);
   NodeMetadata node = builder.build();
   credentialStore.put("node#" + node.getId(), node.getCredentials());
   nodes.put(node.getId(), node);
   StubComputeServiceDependenciesModule.setState(node, NodeState.RUNNING, 100);
   return node;
 }
 @Override
 public NodeMetadata apply(Server from) {
   // convert the result object to a jclouds NodeMetadata
   NodeMetadataBuilder builder = new NodeMetadataBuilder();
   builder.ids(from.id + "");
   builder.name(from.name);
   builder.location(findLocationForServer.apply(from));
   builder.group(nodeNamingConvention.groupInUniqueNameOrNull(from.name));
   builder.imageId(from.imageId + "");
   Image image = findImageForServer.apply(from);
   if (image != null) builder.operatingSystem(image.getOperatingSystem());
   builder.hardware(findHardwareForServer.apply(from));
   builder.state(serverStatusToNodeState.get(from.status));
   builder.publicAddresses(ImmutableSet.<String>of(from.publicAddress));
   builder.privateAddresses(ImmutableSet.<String>of(from.privateAddress));
   builder.credentials(LoginCredentials.fromCredentials(credentialStore.get(from.id + "")));
   return builder.build();
 }
  @Override
  public String associatePredefinedAddress(NodeMetadata node, String ip) {
    if (log.isDebugEnabled()) {
      log.debug(
          String.format(
              "Trying to associate predefined IP address: [node-id] %s [ip] %s", node.getId(), ip));
    }

    ComputeServiceContext context = iaasProvider.getComputeService().getContext();
    String region = ComputeServiceBuilderUtil.extractRegion(iaasProvider);

    FloatingIPApi floatingIPApi =
        context.unwrapApi(NovaApi.class).getFloatingIPExtensionForZone(region).get();

    // get the list of all unassigned IP.
    ArrayList<FloatingIP> unassignedFloatingIPs =
        Lists.newArrayList(
            Iterables.filter(
                floatingIPApi.list(),
                new Predicate<FloatingIP>() {
                  @Override
                  public boolean apply(FloatingIP floatingIP) {
                    return StringUtils.isEmpty(floatingIP.getFixedIp());
                  }
                }));

    boolean isAvailable = false;
    for (FloatingIP floatingIP : unassignedFloatingIPs) {
      if (log.isDebugEnabled()) {
        log.debug(
            "OpenstackNovaIaas:associatePredefinedAddress:iterating over available floatingip:"
                + floatingIP);
      }
      if (ip.equals(floatingIP.getIp())) {
        if (log.isDebugEnabled()) {
          log.debug(
              String.format(
                  "OpenstackNovaIaas:associatePredefinedAddress:floating ip in use:%s /ip:%s",
                  floatingIP, ip));
        }
        isAvailable = true;
        break;
      }
    }

    if (isAvailable) {
      // assign ip
      if (log.isDebugEnabled()) {
        log.debug("OpenstackNovaIaas:associatePredefinedAddress:assign floating ip:" + ip);
      }
      // exercise same code as in associateAddress()
      // wait till the fixed IP address gets assigned - this is needed before
      // we associate a public IP

      while (node.getPrivateAddresses() == null) {
        CloudControllerUtil.sleep(1000);
      }

      int retries = 0;
      int retryCount = Integer.getInteger("stratos.public.ip.association.retry.count", 5);
      while (retries < retryCount && !associateIp(floatingIPApi, ip, node.getProviderId())) {
        // wait for 5s
        CloudControllerUtil.sleep(5000);
        retries++;
      }

      NodeMetadataBuilder.fromNodeMetadata(node).publicAddresses(ImmutableSet.of(ip)).build();
      log.info(
          String.format(
              "Successfully associated predefined IP address: [node-id] %s [ip] %s ",
              node.getId(), ip));
      return ip;
    } else {
      log.warn(
          String.format(
              "Could not associate predefined IP address: [node-id] %s [ip] %s ",
              node.getId(), ip));
      return null;
    }
  }
  @SuppressWarnings({"unchecked", "rawtypes"})
  @Override
  public NodeMetadata apply(ServerInfo from) {
    NodeMetadataBuilder builder = new NodeMetadataBuilder();
    builder.ids(from.getUuid());
    builder.name(from.getName());
    builder.location(locationSupplier.get());
    builder.group(parseGroupFromName(from.getName()));

    String imageId = getImageIdFromServer.apply(from);
    if (imageId != null) {
      Image image = findImageForId.apply(imageId);
      if (image != null) {
        builder.operatingSystem(image.getOperatingSystem());
        builder.adminPassword(image.getAdminPassword());
      }
    }
    builder.hardware(
        new HardwareBuilder()
            .ids(from.getUuid())
            .processors(ImmutableList.of(new Processor(1, from.getCpu())))
            .ram(from.getMem())
            .volumes(
                (List)
                    ImmutableList.of(
                        Iterables.transform(from.getDevices().values(), deviceToVolume)))
            .build());
    builder.state(serverStatusToNodeState.get(from.getStatus()));
    builder.publicAddresses(ImmutableSet.<String>of(from.getVnc().getIp()));
    builder.privateAddresses(ImmutableSet.<String>of());
    builder.credentials(credentialStore.get("node#" + from.getUuid()));
    return builder.build();
  }