List of usage examples for org.w3c.dom Node hasChildNodes
public boolean hasChildNodes();
From source file:org.dasein.cloud.azure.compute.vm.AzureVM.java
private void parseHostedService(@Nonnull ProviderContext ctx, @Nonnull Node entry, @Nullable String serviceName, @Nonnull List<VirtualMachine> virtualMachines) throws CloudException, InternalException { String regionId = ctx.getRegionId(); if (regionId == null) { throw new AzureConfigException("No region ID was specified for this request"); }//from www . ja v a 2 s . c o m NodeList attributes = entry.getChildNodes(); String uri = null; long created = 0L; String service = null; boolean mediaLocationFound = false; DataCenter dc = null; AffinityGroup affinityGroupModel = null; for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (attribute.getNodeType() == Node.TEXT_NODE) { continue; } if (attribute.getNodeName().equalsIgnoreCase("url") && attribute.hasChildNodes()) { uri = attribute.getFirstChild().getNodeValue().trim(); } else if (attribute.getNodeName().equalsIgnoreCase("servicename") && attribute.hasChildNodes()) { service = attribute.getFirstChild().getNodeValue().trim(); if (serviceName != null && !service.equals(serviceName)) { return; } } else if (attribute.getNodeName().equalsIgnoreCase("hostedserviceproperties") && attribute.hasChildNodes()) { NodeList properties = attribute.getChildNodes(); for (int j = 0; j < properties.getLength(); j++) { Node property = properties.item(j); if (property.getNodeType() == Node.TEXT_NODE) { continue; } if (property.getNodeName().equalsIgnoreCase("AffinityGroup") && property.hasChildNodes()) { //get the region for this affinity group String affinityGroup = property.getFirstChild().getNodeValue().trim(); if (affinityGroup != null && !affinityGroup.equals("")) { affinityGroupModel = getProvider().getComputeServices().getAffinityGroupSupport() .get(affinityGroup); if (affinityGroupModel == null) return; dc = getProvider().getDataCenterServices() .getDataCenter(affinityGroupModel.getDataCenterId()); if (dc != null && dc.getRegionId().equals(regionId)) { mediaLocationFound = true; } else { // not correct region/datacenter return; } } } else if (property.getNodeName().equalsIgnoreCase("location") && property.hasChildNodes()) { if (!mediaLocationFound && !regionId.equals(property.getFirstChild().getNodeValue().trim())) { return; } } else if (property.getNodeName().equalsIgnoreCase("datecreated") && property.hasChildNodes()) { created = getProvider().parseTimestamp(property.getFirstChild().getNodeValue().trim()); } } } } if (uri == null || service == null) { return; } AzureMethod method = new AzureMethod(getProvider()); //dmayne 20130416: get the deployment names for each hosted service so we can then extract the detail String deployURL = HOSTED_SERVICES + "/" + service + "?embed-detail=true"; Document deployDoc = method.getAsXML(ctx.getAccountNumber(), deployURL); if (deployDoc == null) { return; } NodeList deployments = deployDoc.getElementsByTagName("Deployments"); for (int i = 0; i < deployments.getLength(); i++) { Node deployNode = deployments.item(i); NodeList deployAttributes = deployNode.getChildNodes(); String deploymentName = ""; for (int j = 0; j < deployAttributes.getLength(); j++) { Node deployment = deployAttributes.item(j); if (deployment.getNodeType() == Node.TEXT_NODE) { continue; } if (deployment.getNodeName().equalsIgnoreCase("Deployment") && deployment.hasChildNodes()) { NodeList dAttribs = deployment.getChildNodes(); for (int k = 0; k < dAttribs.getLength(); k++) { Node mynode = dAttribs.item(k); if (mynode.getNodeName().equalsIgnoreCase("name") && mynode.hasChildNodes()) { deploymentName = mynode.getFirstChild().getNodeValue().trim(); parseDeployment(ctx, regionId, service + ":" + deploymentName, deployment, virtualMachines); for (VirtualMachine vm : virtualMachines) { if (vm.getCreationTimestamp() < 1L) { vm.setCreationTimestamp(created); } if (dc != null) { vm.setProviderDataCenterId(dc.getProviderDataCenterId()); } else { Collection<DataCenter> dcs = getProvider().getDataCenterServices() .listDataCenters(regionId); vm.setProviderDataCenterId(dcs.iterator().next().getProviderDataCenterId()); } if (affinityGroupModel != null) { vm.setAffinityGroupId(affinityGroupModel.getAffinityGroupId()); } } } } } } } }
From source file:org.dasein.cloud.azure.compute.vm.AzureVM.java
private ArrayList<String> getAttachedDisks(VirtualMachine vm) throws InternalException, CloudException { ProviderContext ctx = getProvider().getContext(); if (ctx == null) { throw new AzureConfigException("No context was set for this request"); }//from ww w .j a v a 2s.c o m ArrayList<String> list = new ArrayList<String>(); boolean diskFound = false; String serviceName, deploymentName; serviceName = vm.getTag("serviceName").toString(); deploymentName = vm.getTag("deploymentName").toString(); String resourceDir = HOSTED_SERVICES + "/" + serviceName + "/deployments/" + deploymentName; AzureMethod method = new AzureMethod(getProvider()); Document doc = method.getAsXML(ctx.getAccountNumber(), resourceDir); NodeList entries = doc.getElementsByTagName("Deployment"); for (int i = 0; i < entries.getLength(); i++) { Node entry = entries.item(i); NodeList attributes = entry.getChildNodes(); for (int j = 0; j < attributes.getLength(); j++) { Node attribute = attributes.item(j); if (attribute.getNodeName().equalsIgnoreCase("RoleList") && attribute.hasChildNodes()) { NodeList instances = attribute.getChildNodes(); for (int k = 0; k < instances.getLength(); k++) { Node instance = instances.item(k); if (instance.getNodeName().equalsIgnoreCase("Role") && instance.hasChildNodes()) { NodeList roles = instance.getChildNodes(); for (int l = 0; l < roles.getLength(); l++) { Node role = roles.item(l); if (role.getNodeName().equalsIgnoreCase("OSVirtualHardDisk") && role.hasChildNodes()) { NodeList disks = role.getChildNodes(); for (int m = 0; m < disks.getLength(); m++) { Node disk = disks.item(m); if (disk.getNodeName().equalsIgnoreCase("DiskName") && disk.hasChildNodes()) { String name = disk.getFirstChild().getNodeValue(); list.add(name); diskFound = true; break; } } } if (diskFound) { diskFound = false; break; } } } } } } } return list; }
From source file:org.dasein.cloud.azure.storage.BlobStore.java
@Override public boolean exists(@Nonnull String bucketName) throws InternalException, CloudException { TreeMap<String, String> queries = new TreeMap<String, String>(); AzureStorageMethod method = new AzureStorageMethod(provider); queries.put("comp", "list"); Document doc = method.getAsDoc(AzureStorageMethod.Storage_OPERATION_GET, "", queries, null, null, true); NodeList matches = doc.getElementsByTagName("Container"); if (matches != null) { for (int i = 0; i < matches.getLength(); i++) { Node bucket = matches.item(i); if (bucket.hasChildNodes()) { NodeList attributes = bucket.getChildNodes(); for (int j = 0; j < attributes.getLength(); j++) { Node attr = attributes.item(j); if (attr.getNodeName().equalsIgnoreCase("name") && attr.hasChildNodes() && attr.getFirstChild().getNodeValue().trim().equals(bucketName)) { return true; }// w w w .j a v a 2 s.c o m } } } } return false; }
From source file:org.dasein.cloud.cloudstack.compute.VirtualMachines.java
private @Nullable VirtualMachine toVirtualMachine(@Nullable Node node) throws CloudException, InternalException { if (node == null) { return null; }/*from ww w . j a v a 2 s . c om*/ HashMap<String, String> properties = new HashMap<String, String>(); VirtualMachine server = new VirtualMachine(); NodeList attributes = node.getChildNodes(); String productId = null; server.setProviderOwnerId(getContext().getAccountNumber()); server.setClonable(false); server.setImagable(false); server.setPausable(true); server.setPersistent(true); server.setArchitecture(Architecture.I64); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); String name = attribute.getNodeName().toLowerCase(); String value; if (attribute.getChildNodes().getLength() > 0) { value = attribute.getFirstChild().getNodeValue(); } else { value = null; } if (name.equals("virtualmachineid") || name.equals("id")) { server.setProviderVirtualMachineId(value); logger.info("Processing VM id '" + value + "'"); } else if (name.equals("name")) { server.setDescription(value); } /* else if( name.equals("haenable") ) { server.setPersistent(value != null && value.equalsIgnoreCase("true")); } */ else if (name.equals("displayname")) { server.setName(value); } else if (name.equals("ipaddress")) { // v2.1 if (value != null) { server.setPrivateAddresses(new RawAddress(value)); } server.setPrivateDnsAddress(value); } else if (name.equals("password")) { server.setRootPassword(value); } else if (name.equals("nic")) { // v2.2 if (attribute.hasChildNodes()) { NodeList parts = attribute.getChildNodes(); String addr = null; for (int j = 0; j < parts.getLength(); j++) { Node part = parts.item(j); if (part.getNodeName().equalsIgnoreCase("ipaddress")) { if (part.hasChildNodes()) { addr = part.getFirstChild().getNodeValue(); if (addr != null) { addr = addr.trim(); } } } else if (part.getNodeName().equalsIgnoreCase("networkid")) { server.setProviderVlanId(part.getFirstChild().getNodeValue().trim()); } } if (addr != null) { boolean pub = false; if (!addr.startsWith("10.") && !addr.startsWith("192.168.")) { if (addr.startsWith("172.")) { String[] nums = addr.split("\\."); if (nums.length != 4) { pub = true; } else { try { int x = Integer.parseInt(nums[1]); if (x < 16 || x > 31) { pub = true; } } catch (NumberFormatException ignore) { // ignore } } } else { pub = true; } } if (pub) { server.setPublicAddresses(new RawAddress(addr)); if (server.getPublicDnsAddress() == null) { server.setPublicDnsAddress(addr); } } else { server.setPrivateAddresses(new RawAddress(addr)); if (server.getPrivateDnsAddress() == null) { server.setPrivateDnsAddress(addr); } } } } } else if (name.equals("osarchitecture")) { if (value != null && value.equals("32")) { server.setArchitecture(Architecture.I32); } else { server.setArchitecture(Architecture.I64); } } else if (name.equals("created")) { DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); //2009-02-03T05:26:32.612278 try { server.setCreationTimestamp(df.parse(value).getTime()); } catch (ParseException e) { logger.warn("Invalid date: " + value); server.setLastBootTimestamp(0L); } } else if (name.equals("state")) { VmState state; //(Running, Stopped, Stopping, Starting, Creating, Migrating, HA). if (value.equalsIgnoreCase("stopped")) { state = VmState.STOPPED; server.setImagable(true); } else if (value.equalsIgnoreCase("running")) { state = VmState.RUNNING; } else if (value.equalsIgnoreCase("stopping")) { state = VmState.STOPPING; } else if (value.equalsIgnoreCase("starting")) { state = VmState.PENDING; } else if (value.equalsIgnoreCase("creating")) { state = VmState.PENDING; } else if (value.equalsIgnoreCase("migrating")) { state = VmState.REBOOTING; } else if (value.equalsIgnoreCase("destroyed")) { state = VmState.TERMINATED; } else if (value.equalsIgnoreCase("error")) { state = VmState.ERROR; } else if (value.equalsIgnoreCase("expunging")) { state = VmState.TERMINATED; } else if (value.equalsIgnoreCase("ha")) { state = VmState.REBOOTING; } else { throw new CloudException("Unexpected server state: " + value); } server.setCurrentState(state); } else if (name.equals("zoneid")) { server.setProviderRegionId(value); server.setProviderDataCenterId(value); } else if (name.equals("templateid")) { server.setProviderMachineImageId(value); } else if (name.equals("templatename")) { Platform platform = Platform.guess(value); if (platform.equals(Platform.UNKNOWN)) { platform = guessForWindows(value); } server.setPlatform(platform); } else if (name.equals("serviceofferingid")) { productId = value; } else if (value != null) { properties.put(name, value); } } if (server.getName() == null) { server.setName(server.getProviderVirtualMachineId()); } if (server.getDescription() == null) { server.setDescription(server.getName()); } server.setProviderAssignedIpAddressId(null); if (server.getProviderRegionId() == null) { server.setProviderRegionId(getContext().getRegionId()); } if (server.getProviderDataCenterId() == null) { server.setProviderDataCenterId(getContext().getRegionId()); } if (productId != null) { server.setProductId(productId); } /*final String finalServerId = server.getProviderVirtualMachineId(); // commenting out for now until we can find a way to return plain text rather than encrypted server.setPasswordCallback(new Callable<String>() { @Override public String call() throws Exception { return getRootPassword(finalServerId); } } ); */ server.setTags(properties); return server; }
From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java
@Override public @Nonnull VirtualMachine launch(@Nonnull final VMLaunchOptions withLaunchOptions) throws CloudException, InternalException { APITrace.begin(getProvider(), "launchVM"); final String pw = withLaunchOptions.getBootstrapPassword(); try {/*from w w w .j a v a 2 s . c om*/ final String fullname = withLaunchOptions.getHostName(); final String basename = validateHostName(withLaunchOptions.getHostName()); if (basename.length() > 27) { throw new CloudException( "The maximum name length is 27: '" + basename + "' is " + basename.length()); } String vdcId = withLaunchOptions.getDataCenterId(); if (vdcId == null) { for (DataCenter dc : getProvider().getDataCenterServices() .listDataCenters(getContext().getRegionId())) { if (dc.isActive() && dc.isAvailable()) { vdcId = dc.getProviderDataCenterId(); break; } } } if (vdcId == null) { throw new CloudException("Unable to identify a target data center for deploying VM"); } final VirtualMachineProduct product = getProduct(withLaunchOptions.getStandardProductId()); final vCloudMethod method = new vCloudMethod(getProvider()); final MachineImage img = getProvider().getComputeServices().getImageSupport() .getImage(withLaunchOptions.getMachineImageId()); if (img == null) { throw new CloudException("No such image: " + withLaunchOptions.getMachineImageId()); } StringBuilder xml = new StringBuilder(); xml.append( "<InstantiateVAppTemplateParams xmlns:ovf=\"http://schemas.dmtf.org/ovf/envelope/1\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" name=\"") .append(withLaunchOptions.getFriendlyName()) .append("\" xmlns=\"http://www.vmware.com/vcloud/v1.5\" deploy=\"false\" powerOn=\"false\">"); xml.append("<Description>").append(img.getProviderMachineImageId()).append("</Description>"); String vlanId = withLaunchOptions.getVlanId(); // If vlanId is not specified, explicitly use default in machine image. If left out, // default is not recognized in vCloud 1.5, error is: VCD entity network "X" // specified for VM "Y" does not exist (even though it does exist) if (vlanId == null || vlanId.trim().isEmpty()) { String defaultVlanName = (String) img.getTag("defaultVlanName"); String defaultVlanNameDHCP = (String) img.getTag("defaultVlanNameDHCP"); if (defaultVlanName != null && !defaultVlanName.trim().isEmpty()) { Iterable<VLAN> vlans = getProvider().getNetworkServices().getVlanSupport().listVlans(); for (VLAN vlan : vlans) { if (defaultVlanName.equalsIgnoreCase(vlan.getName())) { vlanId = vlan.getProviderVlanId(); } } if (vlanId == null) { throw new CloudException("Could not locate default vlan '" + defaultVlanName + "'"); } } else if (defaultVlanNameDHCP != null && !defaultVlanNameDHCP.trim().isEmpty()) { throw new CloudException( "No vlan selected and the default is DHCP-based which is not supported"); } else { throw new CloudException("No vlan specified and no default."); } } final VLAN vlan = getProvider().getNetworkServices().getVlanSupport().getVlan(vlanId); if (vlan != null) { //check image tags String parentName = null, parentId = null, parentHref = null; if (img.getTag("parentNetworkName") != null) { parentName = img.getTag("parentNetworkName").toString(); } if (img.getTag("parentNetworkId") != null) { parentId = img.getTag("parentNetworkId").toString(); } if (img.getTag("parentNetworkHref") != null) { parentHref = img.getTag("parentNetworkHref").toString(); if (parentHref.length() > 0) { parentHref = parentHref.substring(0, parentHref.indexOf("/network/") + 9); } else { logger.debug( "Not found network settings in the template so getting the base href from network"); parentHref = vlan.getTag("networkHref").toString(); parentHref = vlan.getTag("networkHref").toString().substring(0, parentHref.indexOf("/network/") + 9); } } else { logger.debug( "Not found network settings in the template so getting the base href from network"); parentHref = vlan.getTag("networkHref").toString(); parentHref = vlan.getTag("networkHref").toString().substring(0, parentHref.indexOf("/network/") + 9); } if (parentName == null || !vlan.getName().equals(parentName)) { // if we don't have the parent id we need to try and find it if (parentId == null && parentName != null) { Iterable<VLAN> vlanList = getProvider().getNetworkServices().getVlanSupport().listVlans(); while (vlanList.iterator().hasNext()) { VLAN v = vlanList.iterator().next(); if (v.getName().equals(parentName)) { // found a match parentId = v.getProviderVlanId(); break; } } if (parentId == null || parentHref == null) { throw new CloudException( "Unable to find the network config settings - cannot specify network for this vApp"); } } // new vapp network config xml.append("<InstantiationParams>"); xml.append("<NetworkConfigSection>"); xml.append( "<Info xmlns=\"http://schemas.dmtf.org/ovf/envelope/1\">Configuration parameters for logical networks</Info>"); xml.append("<NetworkConfig networkName=\"").append(vCloud.escapeXml(vlan.getName())) .append("\">"); xml.append("<Configuration>"); xml.append("<ParentNetwork name=\"").append(vCloud.escapeXml(vlan.getName())).append("\""); xml.append(" id=\"").append(vlanId).append("\""); xml.append(" href=\"").append(parentHref).append(vlanId).append("\"/>"); xml.append("<FenceMode>bridged</FenceMode>"); xml.append("</Configuration>"); xml.append("</NetworkConfig>"); if (parentName != null) { //existing network config from vapp template xml.append("<NetworkConfig networkName=\"").append(parentName).append("\">"); xml.append("<Configuration>"); xml.append("<ParentNetwork name=\"").append(parentName).append("\""); xml.append(" id=\"").append(parentId).append("\""); xml.append(" href=\"").append(parentHref).append(parentId).append("\"/>"); xml.append("<FenceMode>bridged</FenceMode>"); xml.append("</Configuration>"); xml.append("</NetworkConfig>"); } else if (img.getTag("fullNetConf") != null && img.getTag("fullNetConf").toString().length() > 0) { xml.append(img.getTag("fullNetConf")); } xml.append("</NetworkConfigSection>"); xml.append("</InstantiationParams>"); } String vAppTemplateUrl = method.toURL("vAppTemplate", img.getProviderMachineImageId()); xml.append("<Source href=\"").append(vAppTemplateUrl).append("\"/>"); } else { throw new CloudException("Failed to find vlan " + vlanId); } xml.append("<AllEULAsAccepted>true</AllEULAsAccepted>"); xml.append("</InstantiateVAppTemplateParams>"); if (logger.isDebugEnabled()) { try { method.parseXML(xml.toString()); logger.debug("XML passes"); } catch (Throwable t) { logger.error("XML parse failure: " + t.getMessage()); } } String instantiateResponse = method.post(vCloudMethod.INSTANTIATE_VAPP, vdcId, xml.toString()); try { method.waitFor(instantiateResponse); } catch (CloudException e) { logger.error("Error waiting for " + vCloudMethod.INSTANTIATE_VAPP + " task to complete", e); throw new CloudException( "Error waiting for " + vCloudMethod.INSTANTIATE_VAPP + " task to complete"); } Document composeDoc = method.parseXML(instantiateResponse); String docElementTagName = composeDoc.getDocumentElement().getTagName(); final String nsString; if (docElementTagName.contains(":")) { nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); } else { nsString = ""; } NodeList vapps = composeDoc.getElementsByTagName(nsString + "VApp"); if (vapps.getLength() < 1) { throw new CloudException("The instantiation operation succeeded, but no vApp was present"); } Node vapp = vapps.item(0); Node href = vapp.getAttributes().getNamedItem("href"); String vappId = getProvider().toID(href.getNodeValue().trim()); String vAppResponse = method.get("vApp", vappId); if (vAppResponse == null) { try { undeploy(vappId); method.delete("vApp", vappId); } catch (Throwable t) { logger.error("Problem backing out after vApp went away: " + t.getMessage()); } throw new CloudException("vApp went away"); } final Document doc = method.parseXML(vAppResponse); NodeList vmNodes = doc.getElementsByTagName(nsString + "Vm"); // vCloud has a 27 character limit on computer-name, reject upfront final boolean multipleVMs = (vmNodes.getLength() > 1); if (multipleVMs) { // take suffixes into account: if (basename.length() > 25) { try { vCloudMethod dmethod = new vCloudMethod(getProvider()); dmethod.delete("vApp", vappId); } catch (Throwable t) { logger.error("Problem cleaning up vApp " + vappId + ": " + t.getMessage()); } throw new CloudException( "Because there are multiple VMs in this vApp, the maximum name length is 25: '" + basename + "' is " + basename.length()); } if (fullname.length() > 126) { try { vCloudMethod dmethod = new vCloudMethod(getProvider()); dmethod.delete("vApp", vappId); } catch (Throwable t) { logger.error("Problem cleaning up vApp " + vappId + ": " + t.getMessage()); } throw new CloudException( "Because there are multiple VMs in this vApp, the maximum name length is 126: '" + basename + "' is " + basename.length()); } } else if (basename.length() > 27) { // should have been rejected already throw new CloudException( "The maximum name length is 27: '" + basename + "' is " + basename.length()); } else if (fullname.length() > 128) { throw new CloudException( "The maximum name length is 128: '" + basename + "' is " + basename.length()); } String vmId = parseVmId(vmNodes); if (vmId == null) { //Sometimes the vApp response comes back before the VM is included in it //Attempting a single (for the moment) retry in this case but may want to add a loop (potentially doing Thread.sleep) around the retry logger.error("Grabbed the vApp response before the VM was included - retrying"); vmId = retryListvApp(method, vappId, nsString); if (vmId == null) { try { undeploy(vappId); method.delete("vApp", vappId); } catch (Throwable t) { logger.error("Problem backing out after no virtual machines exist in response: " + t.getMessage()); } throw new CloudException("No virtual machines exist in response"); } } VirtualMachine vm = getVirtualMachine(vmId); if (vm == null) { try { undeploy(vappId); method.delete("vApp", vappId); } catch (Throwable t) { logger.error("Problem backing out after failing to identify VM in response: " + t.getMessage()); } throw new CloudException("Unable to identify VM " + vmId + "."); } final String fvmId = vmId; Thread t = new Thread() { public void run() { try { Map<String, Object> metadata = withLaunchOptions.getMetaData(); if (metadata == null) { metadata = new HashMap<String, Object>(); } metadata.put("dsnImageId", img.getProviderMachineImageId()); metadata.put("dsnCreated", String.valueOf(System.currentTimeMillis())); method.postMetaData("vApp", fvmId, metadata); } catch (Throwable warn) { logger.warn("Error updating meta-data on launch: " + warn.getMessage()); } NodeList vapps = doc.getElementsByTagName(nsString + "VApp"); if (vapps.getLength() < 1) { logger.error("The instantiation operation succeeded, but no vApp was present"); } Node vapp = vapps.item(0); Node href = vapp.getAttributes().getNamedItem("href"); if (href != null) { String vappId = getProvider().toID(href.getNodeValue().trim()); String vAppResponse; try { vAppResponse = method.get("vApp", vappId); } catch (CloudException e) { logger.error("Error getting vApp " + vappId, e); return; } catch (InternalException e) { logger.error("Error getting vApp " + vappId, e); return; } if (vAppResponse == null || vAppResponse.equals("")) { logger.error("vApp " + vappId + " went away"); } Document vAppDoc; try { vAppDoc = method.parseXML(vAppResponse); } catch (CloudException e) { logger.error("Error parsing vApp " + vappId + " xml: ", e); return; } catch (InternalException e) { logger.error("Error parsing vApp " + vappId + " xml: ", e); return; } String docElementTagName = vAppDoc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); vapps = vAppDoc.getElementsByTagName(nsString + "VApp"); if (vapps.getLength() < 1) { logger.error("No VApp in vApp request for " + vappId); } vapp = vapps.item(0); NodeList tasks = vapp.getChildNodes(); for (int i = 0; i < tasks.getLength(); i++) { Node task = tasks.item(i); if (task.getNodeName().contains(":")) nsString = task.getNodeName().substring(0, task.getNodeName().indexOf(":") + 1); else nsString = ""; if (task.getNodeName().equalsIgnoreCase(nsString + "Task")) { href = task.getAttributes().getNamedItem("href"); if (href != null) { try { method.waitFor(href.getNodeValue().trim()); } catch (CloudException e) { logger.error("Error waiting for task to complete.", e); } } } } String vAppGetResponse; try { vAppGetResponse = method.get("vApp", vappId); } catch (CloudException e) { logger.error("Error getting vApp " + vappId, e); return; } catch (InternalException e) { logger.error("Error getting vApp " + vappId, e); return; } if (vAppGetResponse == null) { logger.error("vApp went away"); } try { vAppDoc = method.parseXML(vAppGetResponse); } catch (CloudException e) { logger.error("Error parsing vApp " + vappId + " xml: ", e); return; } catch (InternalException e) { logger.error("Error parsing vApp " + vappId + " xml: ", e); return; } docElementTagName = vAppDoc.getDocumentElement().getTagName(); nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); vapps = vAppDoc.getElementsByTagName(nsString + "VApp"); if (vapps.getLength() < 1) { logger.error("vApp went away"); } vapp = vapps.item(0); NodeList attributes = vapp.getChildNodes(); String vmId = null; for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (attribute.getNodeName().contains(":")) nsString = attribute.getNodeName().substring(0, attribute.getNodeName().indexOf(":") + 1); else nsString = ""; if (attribute.getNodeName().equals(nsString + "Children") && attribute.hasChildNodes()) { NodeList children = attribute.getChildNodes(); int count = 1; for (int j = 0; j < children.getLength(); j++) { Node vm = children.item(j); if (vm.getNodeName().contains(":")) nsString = vm.getNodeName().substring(0, vm.getNodeName().indexOf(":") + 1); else nsString = ""; if (vm.getNodeName().equalsIgnoreCase(nsString + "Vm") && vm.hasAttributes()) { href = vm.getAttributes().getNamedItem("href"); if (href != null) { String suffix = (multipleVMs ? ("-" + count) : ""); count++; String vmUrl = href.getNodeValue().trim(); vmId = getProvider().toID(vmUrl); StringBuilder guestXml = new StringBuilder(); guestXml.append( "<GuestCustomizationSection xmlns=\"http://www.vmware.com/vcloud/v1.5\" "); guestXml.append( " xmlns:ovf=\"http://schemas.dmtf.org/ovf/envelope/1\" ovf:required=\"false\">"); guestXml.append( "<Info xmlns=\"http://schemas.dmtf.org/ovf/envelope/1\">Specifies Guest OS Customization Settings</Info>"); guestXml.append("<Enabled>true</Enabled>"); guestXml.append("<ChangeSid>") .append(String.valueOf(img.getPlatform().isWindows())) .append("</ChangeSid>"); guestXml.append("<VirtualMachineId>") .append(UUID.randomUUID().toString()) .append("</VirtualMachineId>"); guestXml.append("<JoinDomainEnabled>false</JoinDomainEnabled>"); guestXml.append("<UseOrgSettings>false</UseOrgSettings>"); guestXml.append("<AdminPasswordEnabled>true</AdminPasswordEnabled>"); if (pw != null) { guestXml.append("<AdminPassword>").append(vCloud.escapeXml(pw)) .append("</AdminPassword>"); //guestXml.append("<AdminPasswordAuto>false</AdminPasswordAuto>"); } else { guestXml.append("<AdminPasswordAuto>true</AdminPasswordAuto>"); } guestXml.append("<ResetPasswordRequired>false</ResetPasswordRequired>"); String userData = withLaunchOptions.getUserData(); if (userData != null && userData.length() > 0) { guestXml.append("<CustomizationScript>") .append(vCloud.escapeXml(userData)) .append("</CustomizationScript>"); } else { String customizationScript = parseCustomizationScript(vm); if (customizationScript != null) { guestXml.append("<CustomizationScript>") .append(vCloud.escapeXml(customizationScript)) .append("</CustomizationScript>"); } } guestXml.append("<ComputerName>") .append(vCloud.escapeXml(validateHostName( withLaunchOptions.getHostName() + suffix))) .append("</ComputerName>"); guestXml.append("</GuestCustomizationSection>"); try { method.waitFor(method.put("guestCustomizationSection", vmUrl + "/guestCustomizationSection", method.getMediaTypeForGuestCustomizationSection(), guestXml.toString())); } catch (CloudException e) { logger.error("Error configuring guest for vApp " + vappId, e); return; } catch (InternalException e) { logger.error("Error configuring guest for vApp " + vappId, e); return; } StringBuilder vmXml = new StringBuilder(); vmXml.append( "<vcloud:Vm xmlns:vcloud=\"http://www.vmware.com/vcloud/v1.5\" "); vmXml.append("name=\"").append(vCloud.escapeXml(fullname + suffix)) .append("\">"); vmXml.append("<vcloud:Description>") .append(withLaunchOptions.getDescription()) .append("</vcloud:Description>"); vmXml.append("</vcloud:Vm>"); try { method.waitFor(method.put("", vmUrl, method.getMediaTypeForVM(), vmXml.toString())); } catch (CloudException e) { logger.error("Error configuring vm for vApp " + vappId, e); return; } catch (InternalException e) { logger.error("Error configuring vm for vApp " + vappId, e); return; } if (product != null) { StringBuilder xml = new StringBuilder(); xml.append("<vcloud:Item " + "xmlns:vcloud=\"http://www.vmware.com/vcloud/v1.5\" " + "xmlns:rasd=\"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData\" " + "vcloud:type=\"application/vnd.vmware.vcloud.rasdItem+xml\" " + "vcloud:href=\"").append(vmUrl) .append("/virtualHardwareSection/cpu\">"); xml.append( "<rasd:AllocationUnits>hertz * 10^6</rasd:AllocationUnits>"); xml.append( "<rasd:Description>Number of Virtual CPUs</rasd:Description>"); xml.append("<rasd:ElementName>") .append(String.valueOf(product.getCpuCount())) .append(" virtual CPU(s)</rasd:ElementName>"); xml.append("<rasd:InstanceID>1</rasd:InstanceID>"); xml.append("<rasd:Reservation>0</rasd:Reservation>"); xml.append("<rasd:ResourceType>3</rasd:ResourceType>"); xml.append("<rasd:VirtualQuantity>") .append(String.valueOf(product.getCpuCount())) .append("</rasd:VirtualQuantity>"); xml.append("<rasd:Weight>") .append(String.valueOf(product.getCpuCount() * 1000)) .append("</rasd:Weight>"); //changed from 0 xml.append("<vcloud:Link href=\"").append(vmUrl).append( "/virtualHardwareSection/cpu\" rel=\"edit\" type=\"application/vnd.vmware.vcloud.rasdItem+xml\"/>"); xml.append("</vcloud:Item>"); try { method.waitFor(method.put("virtualHardwareSection/cpu", vmUrl + "/virtualHardwareSection/cpu", method.getMediaTypeForRasdItem(), xml.toString())); } catch (CloudException e) { logger.error("Error configuring virtual hardware cpu for vApp " + vappId, e); return; } catch (InternalException e) { logger.error("Error configuring virtual hardware cpu for vApp " + vappId, e); return; } xml = new StringBuilder(); xml.append("<vcloud:Item " + "xmlns:vcloud=\"http://www.vmware.com/vcloud/v1.5\" " + "xmlns:rasd=\"http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData\" " + "vcloud:type=\"application/vnd.vmware.vcloud.rasdItem+xml\" " + "vcloud:href=\"").append(vmUrl) .append("/virtualHardwareSection/memory\">"); xml.append( "<rasd:AllocationUnits>byte * 2^20</rasd:AllocationUnits>"); xml.append("<rasd:Description>Memory Size</rasd:Description>"); xml.append("<rasd:ElementName>") .append(product.getRamSize().toString()) .append("</rasd:ElementName>"); xml.append("<rasd:InstanceID>2</rasd:InstanceID>"); xml.append("<rasd:Reservation>0</rasd:Reservation>"); xml.append("<rasd:ResourceType>4</rasd:ResourceType>"); xml.append("<rasd:VirtualQuantity>") .append(String.valueOf(product.getRamSize().intValue())) .append("</rasd:VirtualQuantity>"); xml.append("<rasd:Weight>") .append(String .valueOf(product.getRamSize().intValue() * 10)) .append("</rasd:Weight>"); xml.append("<vcloud:Link href=\"").append(vmUrl).append( "/virtualHardwareSection/memory\" rel=\"edit\" type=\"application/vnd.vmware.vcloud.rasdItem+xml\"/>"); xml.append("</vcloud:Item>"); try { method.waitFor(method.put("virtualHardwareSection/memory", vmUrl + "/virtualHardwareSection/memory", method.getMediaTypeForRasdItem(), xml.toString())); } catch (CloudException e) { logger.error( "Error configuring virtual hardware memory for vApp " + vappId, e); return; } catch (InternalException e) { logger.error( "Error configuring virtual hardware memory for vApp " + vappId, e); return; } if (vlan != null) { xml = new StringBuilder(); xml.append("<NetworkConnectionSection href=\"").append(vmUrl) .append("/networkConnectionSection/").append("\" "); xml.append("xmlns=\"http://www.vmware.com/vcloud/v1.5\" "); xml.append(" type=\"") .append(method .getMediaTypeForNetworkConnectionSection()) .append("\">"); xml.append( "<Info xmlns=\"http://schemas.dmtf.org/ovf/envelope/1\">Specifies the available VM network connections</Info>"); xml.append( "<PrimaryNetworkConnectionIndex>0</PrimaryNetworkConnectionIndex>"); xml.append("<NetworkConnection network=\"") .append(vCloud.escapeXml(vlan.getName())).append("\">"); xml.append( "<NetworkConnectionIndex>0</NetworkConnectionIndex>"); xml.append("<IsConnected>true</IsConnected>"); xml.append( "<IpAddressAllocationMode>POOL</IpAddressAllocationMode>"); xml.append("</NetworkConnection>"); xml.append("</NetworkConnectionSection>"); try { method.waitFor(method.put("networkConnectionSection", vmUrl + "/networkConnectionSection", method.getMediaTypeForNetworkConnectionSection(), xml.toString())); } catch (CloudException e) { logger.error("Error configuring virtual hardware for vApp " + vappId, e); return; } catch (InternalException e) { logger.error("Error configuring virtual hardware for vApp " + vappId, e); return; } } } break; } } } } if (vmId != null) { break; } } if (vmId == null) { logger.error("No virtual machines exist in " + vappId); } try { deploy(vappId); } catch (CloudException e) { logger.error("Error deploying vApp " + vappId, e); return; } catch (InternalException e) { logger.error("Error deploying vApp " + vappId, e); return; } try { startVapp(vappId, true); } catch (CloudException e) { logger.error("Error starting vApp " + vappId, e); } catch (InternalException e) { logger.error("Error starting vApp " + vappId, e); } } } }; t.setName("Configure vCloud VM " + vm.getProviderVirtualMachineId()); t.setDaemon(true); t.start(); vm.setProviderMachineImageId(img.getProviderMachineImageId()); if (pw != null) { vm.setRootPassword(pw); } return vm; } finally { APITrace.end(); } }
From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java
private String parseCustomizationScript(@Nonnull Node vm) { NodeList attributes = vm.getChildNodes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (attribute.getNodeName().equalsIgnoreCase("GuestCustomizationSection") && attribute.hasChildNodes()) { NodeList elements = attribute.getChildNodes(); for (int j = 0; j < elements.getLength(); j++) { Node element = elements.item(j); if (element.getNodeName().equalsIgnoreCase("CustomizationScript") && element.hasChildNodes()) { String customizationScript = element.getFirstChild().getNodeValue().trim(); if (customizationScript != null) { return customizationScript; }/*from w ww. j a v a 2 s.co m*/ } } } } return null; }
From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java
@Override public @Nonnull Iterable<VirtualMachine> listVirtualMachines() throws InternalException, CloudException { getProvider().hold();/*from w w w.jav a 2 s .c o m*/ PopulatorThread<VirtualMachine> populator = new PopulatorThread<VirtualMachine>( new JiteratorPopulator<VirtualMachine>() { @Override public void populate(@Nonnull Jiterator<VirtualMachine> iterator) throws Exception { try { APITrace.begin(getProvider(), "VM.listVirtualMachines"); try { Iterable<VLAN> vlans = getProvider().getNetworkServices().getVlanSupport() .listVlans(); vCloudMethod method = new vCloudMethod(getProvider()); for (DataCenter dc : method.listDataCenters()) { String xml = method.get("vdc", dc.getProviderDataCenterId()); if (xml != null && !xml.equals("")) { Document doc = method.parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList vdcs = doc.getElementsByTagName(nsString + "Vdc"); if (vdcs.getLength() > 0) { NodeList attributes = vdcs.item(0).getChildNodes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (attribute.getNodeName().contains(":")) nsString = attribute.getNodeName().substring(0, attribute.getNodeName().indexOf(":") + 1); else nsString = ""; if (attribute.getNodeName() .equalsIgnoreCase(nsString + "ResourceEntities") && attribute.hasChildNodes()) { NodeList resources = attribute.getChildNodes(); for (int j = 0; j < resources.getLength(); j++) { Node resource = resources.item(j); if (resource.getNodeName() .equalsIgnoreCase(nsString + "ResourceEntity") && resource.hasAttributes()) { Node type = resource.getAttributes() .getNamedItem("type"); if (type != null && type.getNodeValue().equalsIgnoreCase( method.getMediaTypeForVApp())) { Node href = resource.getAttributes() .getNamedItem("href"); loadVmsFor(dc.getProviderDataCenterId(), getProvider() .toID(href.getNodeValue().trim()), iterator, vlans); } } } } } } } } } finally { APITrace.end(); } } finally { getProvider().release(); } } }); populator.populate(); return populator.getResult(); }
From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java
private void loadVmsFor(@Nonnull String vdcId, @Nonnull String id, @Nonnull Jiterator<VirtualMachine> vms, @Nonnull Iterable<VLAN> vlans) throws InternalException, CloudException { vCloudMethod method = new vCloudMethod(getProvider()); String xml = method.get("vApp", id); if (xml == null || xml.equals("")) { return;/*from w w w . j a v a 2 s .c o m*/ } Document doc = method.parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList vapps = doc.getElementsByTagName(nsString + "VApp"); if (vapps.getLength() < 1) { return; } NodeList attributes = vapps.item(0).getChildNodes(); for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (attribute.getNodeName().contains(":")) nsString = attribute.getNodeName().substring(0, attribute.getNodeName().indexOf(":") + 1); else nsString = ""; if (attribute.getNodeName().equals(nsString + "Children") && attribute.hasChildNodes()) { NodeList children = attribute.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node vmNode = children.item(j); if (vmNode.getNodeName().equalsIgnoreCase(nsString + "Vm") && vmNode.hasAttributes()) { VirtualMachine vm = toVirtualMachine(vdcId, id, vmNode, vlans); if (vm != null) { vms.push(vm); } } } } } }
From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java
@Override public void reboot(@Nonnull String vmId) throws CloudException, InternalException { APITrace.begin(getProvider(), "VM.reboot"); try {//from www . jav a 2 s . co m vCloudMethod method = new vCloudMethod(getProvider()); String xml = method.get("vApp", vmId); if (xml != null) { Document doc = method.parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList nodes = doc.getElementsByTagName(nsString + "VApp"); if (nodes.getLength() > 0) { for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (node.getNodeName().contains(":")) nsString = node.getNodeName().substring(0, node.getNodeName().indexOf(":") + 1); else nsString = ""; if (node.getNodeName().equalsIgnoreCase(nsString + "Link") && node.hasAttributes()) { Node rel = node.getAttributes().getNamedItem("rel"); if (rel != null && rel.getNodeValue().trim().equalsIgnoreCase("power:reboot")) { Node href = node.getAttributes().getNamedItem("href"); if (href != null) { String endpoint = href.getNodeValue().trim(); String action = method.getAction(endpoint); method.post(action, endpoint, null, null); break; } } } } } else { nodes = doc.getElementsByTagName(nsString + "Vm"); if (nodes.getLength() > 0) { Node vmNode = nodes.item(0); if (vmNode != null && vmNode.hasChildNodes()) { NodeList links = vmNode.getChildNodes(); for (int i = 0; i < links.getLength(); i++) { Node link = links.item(i); if (link.getNodeName().equalsIgnoreCase(nsString + "Link") && link.hasAttributes()) { Node rel = link.getAttributes().getNamedItem("rel"); if (rel != null && rel.getNodeValue().trim().equalsIgnoreCase("power:reboot")) { Node href = link.getAttributes().getNamedItem("href"); if (href != null) { String endpoint = href.getNodeValue().trim(); String action = method.getAction(endpoint); method.post(action, endpoint, null, null); break; } } } } } } } } } finally { APITrace.end(); } }
From source file:org.dasein.cloud.vcloud.compute.vAppSupport.java
private void stopVappOrOneVm(String vAppId, String vmId, boolean force) throws CloudException, InternalException { // 3. Does the vApp contain multiple VMs? vCloudMethod method = new vCloudMethod(getProvider()); String xml = method.get("vApp", vAppId); if (xml == null) { throw new CloudException("No information returned for ID: " + vAppId); }/*from w w w .j av a2 s . co m*/ Document doc = method.parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList nodes = doc.getElementsByTagName(nsString + "VApp"); NodeList attributes = nodes.item(0).getChildNodes(); int count = 0; for (int i = 0; i < attributes.getLength(); i++) { Node attribute = attributes.item(i); if (attribute.getNodeName().contains(":")) nsString = attribute.getNodeName().substring(0, attribute.getNodeName().indexOf(":") + 1); else nsString = ""; if (attribute.getNodeName().equals(nsString + "Children") && attribute.hasChildNodes()) { NodeList children = attribute.getChildNodes(); for (int j = 0; j < children.getLength(); j++) { Node vmNode = children.item(j); if (vmNode.getNodeName().equalsIgnoreCase(nsString + "Vm") && vmNode.hasAttributes()) { count++; } } } } String powerAction = null; if (!force) { powerAction = "shutdown"; } if (count > 1) { // 4a. If the vApp contains multiple VMs, undeploy VM undeploy(vmId, powerAction); } else if (count == 1) { // 4b. If the vApp contains just one VM, undeploy the vApp undeploy(vAppId, powerAction); } else { throw new CloudException("Expected at least one VM"); } }