Issue 167: removed vi module as it isn't relevant to how we want to cover vsphere support

This commit is contained in:
Adrian Cole 2011-02-20 08:27:41 -08:00
parent c2ef282acf
commit 3b752ea955
21 changed files with 0 additions and 2697 deletions

View File

@ -1,2 +0,0 @@

View File

@ -1 +0,0 @@
runNodesWithTag: pass VirtualMachineRelocateSpec using Template?

View File

@ -1,149 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2010 Cloud Conscious, LLC.
<info@cloudconscious.com>
====================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 Unless required by
applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions
and limitations under the License.
====================================================================
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-project</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../../project/pom.xml</relativePath>
</parent>
<groupId>org.jclouds.api</groupId>
<artifactId>vi</artifactId>
<name>jclouds example components for a vijava lib for VI 4 (VMware Infrastructure)</name>
<properties>
<!-- when instances are hung, open a ticket and add here -->
<jclouds.compute.blacklist.nodes>trmkrun-ccc,test.trmk-924</jclouds.compute.blacklist.nodes>
<test.vi.endpoint>test:///default</test.vi.endpoint>
<test.vi.apiversion>1.0</test.vi.apiversion>
<test.vi.identity>FIXME</test.vi.identity>
<test.vi.credential>FIXME</test.vi.credential>
</properties>
<dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.jvnet.hudson</groupId>
<artifactId>vijava</artifactId>
<version>2120100824</version>
</dependency>
<dependency>
<groupId>com.jamesmurty.utils</groupId>
<artifactId>java-xmlbuilder</artifactId>
<version>0.3</version>
</dependency>
<dependency>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-core</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-compute</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jclouds</groupId>
<artifactId>jclouds-compute</artifactId>
<version>${project.version}</version>
<type>test-jar</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jclouds.driver</groupId>
<artifactId>jclouds-log4j</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jclouds.driver</groupId>
<artifactId>jclouds-jsch</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<id>integration</id>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<systemProperties>
<property>
<name>test.vi.endpoint</name>
<value>${test.vi.endpoint}</value>
</property>
<property>
<name>test.vi.apiversion</name>
<value>${test.vi.apiversion}</value>
</property>
<property>
<name>test.vi.identity</name>
<value>${test.vi.identity}</value>
</property>
<property>
<name>test.vi.credential</name>
<value>${test.vi.credential}</value>
</property>
<property>
<name>jclouds.compute.blacklist.nodes</name>
<value>${jclouds.compute.blacklist.nodes}</value>
</property>
</systemProperties>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -1,418 +0,0 @@
/*================================================================================
Copyright (c) 2008 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25.mo;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.util.Calendar;
import com.vmware.vim25.AboutInfo;
import com.vmware.vim25.Capability;
import com.vmware.vim25.Event;
import com.vmware.vim25.HostVMotionCompatibility;
import com.vmware.vim25.InvalidState;
import com.vmware.vim25.ManagedObjectReference;
import com.vmware.vim25.ProductComponentInfo;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.ServiceContent;
import com.vmware.vim25.UserSession;
import com.vmware.vim25.VimPortType;
import com.vmware.vim25.VirtualMachinePowerState;
import com.vmware.vim25.mo.util.MorUtil;
import com.vmware.vim25.ws.WSClient;
/**
*
* jclouds
*
* The managed object class corresponding to the one defined in VI SDK API reference.
* @author Steve JIN (sjin@vmware.com)
*/
public class ServiceInstance extends ManagedObject
{
private ServiceContent serviceContent = null;
final static ManagedObjectReference SERVICE_INSTANCE_MOR;
public final static String VIM25_NAMESPACE = " xmlns=\"urn:vim25\">";
public final static String VIM20_NAMESPACE = " xmlns=\"urn:vim2\">";
static
{
SERVICE_INSTANCE_MOR = new ManagedObjectReference();
SERVICE_INSTANCE_MOR.set_value("ServiceInstance");
SERVICE_INSTANCE_MOR.setType("ServiceInstance");
}
// PATCHED CONSTRUCTOR
public ServiceInstance(WSClient wsc, String username, String password, String ignoreCert)
throws RemoteException, MalformedURLException
{
if(ignoreCert.equals("true")) {
this.ignoreCertificate();
}
if(username == null) {
throw new NullPointerException("username cannot be null.");
}
setMOR(SERVICE_INSTANCE_MOR);
// PATCH TO USE OUR wsc
VimPortType vimService = new VimPortType(wsc);
vimService.getWsc().setVimNameSpace(wsc.getVimNameSpace());
serviceContent = vimService.retrieveServiceContent(SERVICE_INSTANCE_MOR);
vimService.getWsc().setSoapActionOnApiVersion(serviceContent.getAbout().getApiVersion());
setServerConnection(new ServerConnection(wsc.getBaseUrl(), vimService, this));
// escape 5 special chars
// http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
password = password.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&apos;");
UserSession userSession = getSessionManager().login(username, password, null);
getServerConnection().setUserSession(userSession);
}
public ServiceInstance(URL url, String username, String password)
throws RemoteException, MalformedURLException
{
this(url, username, password, false);
}
public ServiceInstance(URL url, String username, String password, boolean ignoreCert)
throws RemoteException, MalformedURLException
{
this(url, username, password, ignoreCert, VIM25_NAMESPACE);
}
public ServiceInstance(URL url, String username, String password, boolean ignoreCert, String namespace)
throws RemoteException, MalformedURLException
{
if(url == null || username==null)
{
throw new NullPointerException("None of url, username can be null.");
}
setMOR(SERVICE_INSTANCE_MOR);
VimPortType vimService = new VimPortType(url.toString(), ignoreCert);
vimService.getWsc().setVimNameSpace(namespace);
serviceContent = vimService.retrieveServiceContent(SERVICE_INSTANCE_MOR);
vimService.getWsc().setSoapActionOnApiVersion(serviceContent.getAbout().getApiVersion());
setServerConnection(new ServerConnection(url, vimService, this));
// escape 5 special chars
// http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
password = password.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&apos;");
UserSession userSession = getSessionManager().login(username, password, null);
getServerConnection().setUserSession(userSession);
}
public ServiceInstance(URL url, String sessionStr, boolean ignoreCert)
throws RemoteException, MalformedURLException
{
this(url, sessionStr, ignoreCert, VIM25_NAMESPACE);
}
// sessionStr format: "vmware_soap_session=\"B3240D15-34DF-4BB8-B902-A844FDF42E85\""
public ServiceInstance(URL url, String sessionStr, boolean ignoreCert, String namespace)
throws RemoteException, MalformedURLException
{
if(url == null || sessionStr ==null)
{
throw new NullPointerException("None of url, session string can be null.");
}
setMOR(SERVICE_INSTANCE_MOR);
VimPortType vimService = new VimPortType(url.toString(), ignoreCert);
WSClient wsc = vimService.getWsc();
wsc.setCookie(sessionStr);
wsc.setVimNameSpace(namespace);
serviceContent = vimService.retrieveServiceContent(SERVICE_INSTANCE_MOR);
setServerConnection(new ServerConnection(url, vimService, this));
UserSession userSession = (UserSession) getSessionManager().getCurrentProperty("currentSession");
getServerConnection().setUserSession(userSession);
}
public ServiceInstance(ServerConnection sc)
{
super(sc, SERVICE_INSTANCE_MOR);
}
public Calendar getServerClock()
{
return (Calendar) getCurrentProperty("serverClock");
}
public Capability getCapability()
{
return (Capability) getCurrentProperty("capability");
}
public ClusterProfileManager getClusterProfileManager()
{
return (ClusterProfileManager) createMO(getServiceContent().getClusterProfileManager());
}
public Calendar currentTime() throws RuntimeFault, RemoteException
{
return getVimService().currentTime(getMOR());
}
public Folder getRootFolder()
{
return new Folder(this.getServerConnection(), this.getServiceContent().getRootFolder());
}
public HostVMotionCompatibility[] queryVMotionCompatibility(VirtualMachine vm, HostSystem[] hosts, String[] compatibility) throws RuntimeFault, RemoteException
{
if(vm==null || hosts==null)
{
throw new IllegalArgumentException("Neither vm or hosts can be null.");
}
return getVimService().queryVMotionCompatibility(getMOR(), vm.getMOR(), MorUtil.createMORs(hosts), compatibility);
}
public ProductComponentInfo[] retrieveProductComponents() throws RuntimeFault, RemoteException
{
return getVimService().retrieveProductComponents(getMOR());
}
private ServiceContent retrieveServiceContent() throws RuntimeFault, RemoteException
{
return getVimService().retrieveServiceContent(getMOR());
}
public Event[] validateMigration(VirtualMachine[] vms, VirtualMachinePowerState state, String[] testType
, ResourcePool pool, HostSystem host) throws InvalidState, RuntimeFault, RemoteException
{
if(vms==null)
{
throw new IllegalArgumentException("vms must not be null.");
}
return getVimService().validateMigration(getMOR(), MorUtil.createMORs(vms), state, testType,
pool==null? null: pool.getMOR(), host==null? null : host.getMOR());
}
public ServiceContent getServiceContent()
{
if(serviceContent == null)
{
try
{
serviceContent = retrieveServiceContent();
} catch(Exception e)
{
System.out.println("Exceptoin: " + e);
}
}
return serviceContent;
}
public AboutInfo getAboutInfo()
{
return getServiceContent().getAbout();
}
public AlarmManager getAlarmManager()
{
return (AlarmManager) createMO(getServiceContent().getAlarmManager());
}
public AuthorizationManager getAuthorizationManager()
{
return (AuthorizationManager) createMO(getServiceContent().getAuthorizationManager());
}
public CustomFieldsManager getCustomFieldsManager()
{
return (CustomFieldsManager) createMO(getServiceContent().getCustomFieldsManager());
}
public CustomizationSpecManager getCustomizationSpecManager()
{
return (CustomizationSpecManager) createMO(getServiceContent().getCustomizationSpecManager());
}
public EventManager getEventManager()
{
return (EventManager) createMO(getServiceContent().getEventManager());
}
public DiagnosticManager getDiagnosticManager()
{
return (DiagnosticManager) createMO(getServiceContent().getDiagnosticManager());
}
public DistributedVirtualSwitchManager getDistributedVirtualSwitchManager()
{
return (DistributedVirtualSwitchManager) createMO(getServiceContent().getDvSwitchManager());
}
public ExtensionManager getExtensionManager()
{
return (ExtensionManager) createMO(getServiceContent().getExtensionManager());
}
public FileManager getFileManager()
{
return (FileManager) createMO(getServiceContent().getFileManager());
}
public HostLocalAccountManager getAccountManager()
{
return (HostLocalAccountManager) createMO(getServiceContent().getAccountManager());
}
public LicenseManager getLicenseManager()
{
return (LicenseManager) createMO(getServiceContent().getLicenseManager());
}
public LocalizationManager getLocalizationManager()
{
return (LocalizationManager) createMO(getServiceContent().getLocalizationManager());
}
public PerformanceManager getPerformanceManager()
{
return (PerformanceManager) createMO(getServiceContent().getPerfManager());
}
public ProfileComplianceManager getProfileComplianceManager()
{
return (ProfileComplianceManager) createMO(getServiceContent().getComplianceManager());
}
public PropertyCollector getPropertyCollector()
{
return (PropertyCollector) createMO(getServiceContent().getPropertyCollector());
}
public ScheduledTaskManager getScheduledTaskManager()
{
return (ScheduledTaskManager) createMO(getServiceContent().getScheduledTaskManager());
}
public SearchIndex getSearchIndex()
{
return (SearchIndex) createMO(getServiceContent().getSearchIndex());
}
public SessionManager getSessionManager()
{
return (SessionManager) createMO(getServiceContent().getSessionManager());
}
public HostSnmpSystem getHostSnmpSystem()
{
return (HostSnmpSystem) createMO(getServiceContent().getSnmpSystem());
}
public HostProfileManager getHostProfileManager()
{
return (HostProfileManager) createMO(getServiceContent().getHostProfileManager());
}
public IpPoolManager getIpPoolManager()
{
return (IpPoolManager) createMO(getServiceContent().getIpPoolManager());
}
public VirtualMachineProvisioningChecker getVirtualMachineProvisioningChecker()
{
return (VirtualMachineProvisioningChecker) createMO(getServiceContent().getVmProvisioningChecker());
}
public VirtualMachineCompatibilityChecker getVirtualMachineCompatibilityChecker()
{
return (VirtualMachineCompatibilityChecker) createMO(getServiceContent().getVmCompatibilityChecker());
}
public TaskManager getTaskManager()
{
return (TaskManager) createMO(getServiceContent().getTaskManager());
}
public UserDirectory getUserDirectory()
{
return (UserDirectory) createMO(getServiceContent().getUserDirectory());
}
public ViewManager getViewManager()
{
return (ViewManager) createMO(getServiceContent().getViewManager());
}
public VirtualDiskManager getVirtualDiskManager()
{
return (VirtualDiskManager) createMO(getServiceContent().getVirtualDiskManager());
}
public OptionManager getOptionManager()
{
return (OptionManager) createMO(getServiceContent().getSetting());
}
public OvfManager getOvfManager()
{
return (OvfManager) createMO(getServiceContent().getOvfManager());
}
private ManagedObject createMO(ManagedObjectReference mor)
{
return MorUtil.createExactManagedObject(getServerConnection(), mor);
}
private void ignoreCertificate()
{
System.setProperty("org.apache.axis.components.net.SecureSocketFactory",
"org.apache.axis.components.net.SunFakeTrustSocketFactory");
}
// TODO vim.VirtualizationManager is defined in servicecontent but no documentation there. Filed a bug already
}

View File

@ -1,412 +0,0 @@
/*================================================================================
Copyright (c) 2009 VMware, Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25.ws;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URISyntaxException;
import java.net.URL;
import java.rmi.RemoteException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map.Entry;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.jclouds.util.Strings2;
import com.vmware.vim25.ManagedObjectReference;
/**
* The Web Service Engine
* @author Steve Jin (sjin@vmware.com)
*/
// MARKED NOT FINAL
public class WSClient
{
private final static String SOAP_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><soapenv:Envelope xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><soapenv:Body>";
private final static String SOAP_END = "</soapenv:Body></soapenv:Envelope>";
private final static String SOAP_ACTION_HEADER = "SOAPAction";
private final static String SOAP_ACTION_V40 = "urn:vim25/4.0";
private final static String SOAP_ACTION_V41 = "urn:vim25/4.1";
private URL baseUrl = null;
private String cookie = null;
private String vimNameSpace = null;
private String soapAction = SOAP_ACTION_V40;
private int connectTimeout = 0;
private int readTimeout = 0;
public WSClient(String serverUrl) throws MalformedURLException
{
this(serverUrl, true);
}
public WSClient(String serverUrl, boolean ignoreCert) throws MalformedURLException
{
if(serverUrl.endsWith("/"))
{
serverUrl = serverUrl.substring(0, serverUrl.length()-1);
}
this.baseUrl = new URL(serverUrl);
if(ignoreCert)
{
try
{
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier
(
new HostnameVerifier()
{
public boolean verify(String urlHostName, SSLSession session)
{
return true;
}
}
);
} catch (Exception e) {}
}
}
public Object invoke(ManagedObjectReference mor, String methodName, Argument[] paras, String returnType) throws IOException
{
Argument[] fullParas = new Argument[paras.length + 1];
fullParas[0] = new Argument("_this", "ManagedObjectReference", mor);
System.arraycopy(paras, 0, fullParas, 1, paras.length);
return invoke(methodName, fullParas, returnType);
}
public Object invoke(String methodName, Argument[] paras, String returnType) throws RemoteException
{
Element root = invoke(methodName, paras);
Element body = (Element) root.elements().get(0);
Element resp = (Element) body.elements().get(0);
if(resp.getName().indexOf("Fault")!=-1)
{
SoapFaultException sfe = null;
try
{
sfe = XmlGen.parseSoapFault(resp);
}
catch (Exception e)
{
throw new RemoteException("Exception in WSClient.invoke:", e);
}
if(sfe!=null && sfe.detail!=null)
{
throw (RemoteException) sfe.detail;
}
else
{
throw sfe;
}
}
else
{
if(returnType!=null)
{
try
{
return XmlGen.fromXML(returnType, resp);
}
catch (Exception e)
{
throw new RemoteException("Exception in WSClient.invoke:", e);
}
}
else
{
return null;
}
}
}
public Element invoke(String methodName, Argument[] paras) throws RemoteException
{
String soapMsg = createSoapMessage(methodName, paras);
Element root = null;
InputStream is = null;
try
{
is = post(soapMsg);
SAXReader reader = new SAXReader();
Document doc = reader.read(is);
root = doc.getRootElement();
} catch (Exception e)
{
throw new RemoteException("VI SDK invoke exception:" + e);
}
finally
{
if(is!=null)
try { is.close(); } catch(IOException ioe) {}
}
return root;
}
public StringBuffer invokeAsString(String methodName, Argument[] paras) throws RemoteException
{
String soapMsg = createSoapMessage(methodName, paras);
try
{
InputStream is = post(soapMsg);
return readStream(is);
} catch (Exception e)
{
throw new RemoteException("VI SDK invoke exception:" + e);
}
}
private String createSoapMessage(String methodName, Argument[] paras)
{
StringBuffer sb = new StringBuffer();
sb.append(SOAP_HEADER);
sb.append("<" + methodName + vimNameSpace);
for(int i=0; i<paras.length; i++)
{
String key = paras[i].getName();
String type = paras[i].getType();
Object obj = paras[i].getValue();
sb.append(XmlGen.toXML(key, type, obj)); //, null));
}
sb.append("</" + methodName + ">");
sb.append(SOAP_END);
return sb.toString();
}
public InputStream post(String soapMsg) throws IOException
{
HttpURLConnection postCon = (HttpURLConnection) baseUrl.openConnection();
if(connectTimeout > 0)
postCon.setConnectTimeout(connectTimeout);
if(readTimeout > 0)
postCon.setReadTimeout(readTimeout);
try {
postCon.setRequestMethod("POST");
} catch (ProtocolException e)
{
e.printStackTrace();
}
postCon.setDoOutput(true);
postCon.setDoInput(true);
postCon.setRequestProperty(SOAP_ACTION_HEADER, soapAction);
if(cookie!=null)
{
postCon.setRequestProperty("Cookie", cookie);
}
OutputStream os = postCon.getOutputStream();
OutputStreamWriter out = new OutputStreamWriter(os);
// PRINT REQUEST
try {
System.out.printf("%s %s HTTP/1.1%n", "POST", baseUrl.toURI().toASCIIString());
System.out.printf("%s: %s%n", SOAP_ACTION_HEADER, soapAction);
if(cookie!=null)
System.out.printf("%s: %s%n", "Cookie", cookie);
System.out.println(soapMsg);
} catch (URISyntaxException e1) {
}
// END PRINT REQUEST
out.write(soapMsg);
out.close();
InputStream is;
try
{
is = postCon.getInputStream();
}
catch(IOException ioe)
{
is = postCon.getErrorStream();
}
if(cookie==null)
{
cookie = postCon.getHeaderField("Set-Cookie");
}
// PRINT RESPONSE
System.out.printf("HTTP/1.1 %d %s", postCon.getResponseCode(), postCon.getResponseMessage());
for (Entry<String, List<String>> i : postCon.getHeaderFields().entrySet()) {
for (String v : i.getValue())
System.out.printf("%s: %s%n", i.getKey(), v);
}
String response = Strings2.toStringAndClose(is);
System.out.println(response);
is = new ByteArrayInputStream(response.getBytes());
// END PRINT RESPONSE
return is;
}
public URL getBaseUrl()
{
return this.baseUrl;
}
public void setBaseUrl(URL baseUrl)
{
this.baseUrl = baseUrl;
}
public String getCookie()
{
return cookie;
}
public void setCookie(String cookie)
{
this.cookie = cookie;
}
public String getVimNameSpace()
{
return vimNameSpace;
}
public void setVimNameSpace(String vimNameSpace)
{
this.vimNameSpace = vimNameSpace;
}
public void setConnectTimeout(int timeoutMilliSec)
{
this.connectTimeout = timeoutMilliSec;
}
public int getConnectTimeout()
{
return this.connectTimeout;
}
public void setReadTimeout(int timeoutMilliSec)
{
this.readTimeout = timeoutMilliSec;
}
public int getReadTimeout()
{
return this.readTimeout;
}
/*===============================================
* API versions *
"2.0.0" VI 3.0
"2.5.0" VI 3.5 (and u1)
"2.5u2" VI 3.5u2 (and u3, u4)
"4.0" vSphere 4.0 (and u1)
"4.1" vSphere 4.1
===============================================*/
public void setSoapActionOnApiVersion(String apiVersion)
{
//4.0 is set by default already, so skip it here
if("4.1".equals(apiVersion))
{
soapAction = SOAP_ACTION_V41;
}
}
private StringBuffer readStream(InputStream is) throws IOException
{
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String lineStr;
while ((lineStr = in.readLine()) != null)
{
sb.append(lineStr);
}
in.close();
return sb;
}
private static void trustAllHttpsCertificates()
throws NoSuchAlgorithmException, KeyManagementException
{
TrustManager[] trustAllCerts = new TrustManager[1];
trustAllCerts[0] = new TrustAllManager();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(
sc.getSocketFactory());
}
private static class TrustAllManager implements X509TrustManager
{
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
public void checkServerTrusted(X509Certificate[] certs,
String authType)
throws CertificateException
{
}
public void checkClientTrusted(X509Certificate[] certs,
String authType)
throws CertificateException
{
}
}
}

View File

@ -1,56 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi;
import com.google.common.base.Objects;
/**
* This would be replaced with the real java object related to the underlying image
*
* @author Adrian Cole
*/
public class Image {
public String id;
public String name;
public Image(String id, String name) {
this.id = id;
this.name = name;
}
@Override
public int hashCode() {
return Objects.hashCode(id, name);
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
return Objects.equal(this.toString(), that.toString());
}
@Override
public String toString() {
return Objects.toStringHelper(this).add("id", id).add("name", name).toString();
}
}

View File

@ -1,101 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.jclouds.Constants;
import org.jclouds.collect.Memoized;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.internal.BaseComputeService;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.compute.strategy.DestroyNodeStrategy;
import org.jclouds.compute.strategy.GetNodeMetadataStrategy;
import org.jclouds.compute.strategy.InitializeRunScriptOnNodeOrPlaceInBadMap;
import org.jclouds.compute.strategy.ListNodesStrategy;
import org.jclouds.compute.strategy.RebootNodeStrategy;
import org.jclouds.compute.strategy.ResumeNodeStrategy;
import org.jclouds.compute.strategy.CreateNodesInGroupThenAddToSet;
import org.jclouds.compute.strategy.SuspendNodeStrategy;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.vmware.vim25.mo.ServiceInstance;
/**
*
* @author andrea.turli
*
*/
@Singleton
public class ViComputeService extends BaseComputeService {
private final ServiceInstance client;
@Inject
protected ViComputeService(ComputeServiceContext context, Map<String, Credentials> credentialStore,
@Memoized Supplier<Set<? extends Image>> images,
@Memoized Supplier<Set<? extends Hardware>> hardwareProfiles,
@Memoized Supplier<Set<? extends Location>> locations, ListNodesStrategy listNodesStrategy,
GetNodeMetadataStrategy getNodeMetadataStrategy, CreateNodesInGroupThenAddToSet runNodesAndAddToSetStrategy,
RebootNodeStrategy rebootNodeStrategy, DestroyNodeStrategy destroyNodeStrategy,
ResumeNodeStrategy resumeNodeStrategy, SuspendNodeStrategy suspendNodeStrategy,
Provider<TemplateBuilder> templateBuilderProvider, Provider<TemplateOptions> templateOptionsProvider,
@Named("NODE_RUNNING") Predicate<NodeMetadata> nodeRunning,
@Named("NODE_TERMINATED") Predicate<NodeMetadata> nodeTerminated,
@Named("NODE_SUSPENDED") Predicate<NodeMetadata> nodeSuspended,
InitializeRunScriptOnNodeOrPlaceInBadMap.Factory initScriptRunnerFactory, Timeouts timeouts,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor, ServiceInstance client) {
super(context, credentialStore, images, hardwareProfiles, locations, listNodesStrategy, getNodeMetadataStrategy,
runNodesAndAddToSetStrategy, rebootNodeStrategy, destroyNodeStrategy, resumeNodeStrategy,
suspendNodeStrategy, templateBuilderProvider, templateOptionsProvider, nodeRunning, nodeTerminated,
nodeSuspended, initScriptRunnerFactory, timeouts, executor);
this.client = client;
}
@Override
public void destroyNode(String id) {
super.destroyNode(id);
}
protected <T> T propogate(Exception e) {
Throwables.propagate(e);
assert false;
return null;
}
}

View File

@ -1,46 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute;
import java.util.List;
import java.util.Properties;
import org.jclouds.compute.StandaloneComputeServiceContextBuilder;
import org.jclouds.vi.compute.config.ViComputeServiceContextModule;
import com.google.inject.Module;
import com.vmware.vim25.mo.ServiceInstance;
/**
*
* @author Adrian Cole
*/
public class ViComputeServiceContextBuilder extends StandaloneComputeServiceContextBuilder<ServiceInstance> {
public ViComputeServiceContextBuilder(Properties props) {
super(ServiceInstance.class, props);
}
@Override
protected void addContextModule(List<Module> modules) {
modules.add(new ViComputeServiceContextModule());
}
}

View File

@ -1,43 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute;
import org.jclouds.PropertiesBuilder;
import org.jclouds.compute.ComputeService;
import org.jclouds.rest.RestContextSpec;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;
/**
* @author Adrian Cole
*/
public class ViComputeServiceContextSpec extends RestContextSpec<ComputeService, ComputeService> {
@SuppressWarnings("unchecked")
public ViComputeServiceContextSpec(String endpoint, String identity, String credential, Iterable<Module> modules) {
super("vi", endpoint, "1", "", identity, credential, ComputeService.class, ComputeService.class,
PropertiesBuilder.class, (Class) ViComputeServiceContextBuilder.class, modules);
}
public ViComputeServiceContextSpec(String endpoint, String identity, String credential) {
this(endpoint, identity, credential, ImmutableSet.<Module> of());
}
}

View File

@ -1,52 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute;
import static org.jclouds.vi.reference.ViConstants.PROPERTY_VI_XML_NAMESPACE;
import static org.jclouds.vi.reference.ViConstants.PROPERTY_VI_IGNORE_CERTIFICATE;
import java.util.Properties;
import org.jclouds.PropertiesBuilder;
import com.vmware.vim25.mo.ServiceInstance;
/**
* Builds properties used in vi Clients
*
* @author Andrea Turli
*/
public class ViPropertiesBuilder extends PropertiesBuilder {
@Override
protected Properties defaultProperties() {
Properties properties = super.defaultProperties();
properties.setProperty(PROPERTY_VI_XML_NAMESPACE, ServiceInstance.VIM25_NAMESPACE);
properties.setProperty(PROPERTY_VI_IGNORE_CERTIFICATE, "true");
return properties;
}
public ViPropertiesBuilder(Properties properties) {
super(properties);
}
public ViPropertiesBuilder() {
super();
}
}

View File

@ -1,239 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute.config;
import static com.google.common.base.Predicates.notNull;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.transform;
import static org.jclouds.vi.reference.ViConstants.PROPERTY_VI_XML_NAMESPACE;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.rmi.RemoteException;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.ws.rs.core.HttpHeaders;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.jclouds.Constants;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.config.ComputeServiceAdapterContextModule;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.domain.Location;
import org.jclouds.http.HttpRequest;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.io.Payloads;
import org.jclouds.location.Provider;
import org.jclouds.location.suppliers.OnlyLocationOrFirstZone;
import org.jclouds.rest.HttpClient;
import org.jclouds.vi.Image;
import org.jclouds.vi.compute.functions.DatacenterToLocation;
import org.jclouds.vi.compute.functions.ViImageToImage;
import org.jclouds.vi.compute.functions.VirtualMachineToHardware;
import org.jclouds.vi.compute.functions.VirtualMachineToNodeMetadata;
import org.jclouds.vi.compute.strategy.ViComputeServiceAdapter;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.ImmutableMultimap.Builder;
import com.google.inject.Injector;
import com.google.inject.Provides;
import com.google.inject.TypeLiteral;
import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.VirtualMachine;
import com.vmware.vim25.ws.WSClient;
/**
*
* @author Adrian Cole
*/
public class ViComputeServiceContextModule
extends
ComputeServiceAdapterContextModule<ServiceInstance, ServiceInstance, VirtualMachine, VirtualMachine, Image, Datacenter> {
public ViComputeServiceContextModule() {
super(ServiceInstance.class, ServiceInstance.class);
}
@Override
protected void configure() {
super.configure();
bind(new TypeLiteral<ComputeServiceAdapter<VirtualMachine, VirtualMachine, Image, Datacenter>>() {
}).to(ViComputeServiceAdapter.class);
bind(new TypeLiteral<Supplier<Location>>() {
}).to(OnlyLocationOrFirstZone.class);
bind(new TypeLiteral<Function<VirtualMachine, NodeMetadata>>() {
}).to(VirtualMachineToNodeMetadata.class);
bind(new TypeLiteral<Function<Image, org.jclouds.compute.domain.Image>>() {
}).to(ViImageToImage.class);
bind(new TypeLiteral<Function<VirtualMachine, Hardware>>() {
}).to(VirtualMachineToHardware.class);
bind(new TypeLiteral<Function<Datacenter, Location>>() {
}).to(DatacenterToLocation.class);
}
@Provides
@Singleton
protected ServiceInstance createConnection(JcloudsWSClient client,
@Named(Constants.PROPERTY_IDENTITY) String identity,
@Named(Constants.PROPERTY_CREDENTIAL) String credential,
@Named(Constants.PROPERTY_TRUST_ALL_CERTS) boolean ignoreCertificate) throws RemoteException,
MalformedURLException {
// uncomment this to use jclouds http commands
// return new ServiceInstance(client, identity, credential, ignoreCertificate);
return new ServiceInstance(new WSClient(client.getBaseUrl().toString(), ignoreCertificate), identity, credential,
ignoreCertificate + "");
}
@Singleton
public static class JcloudsWSClient extends WSClient {
private final HttpClient client;
@Inject
public JcloudsWSClient(HttpClient client, @Provider URI baseUrl,
@Named(PROPERTY_VI_XML_NAMESPACE) String vimNameSpace,
@Named(Constants.PROPERTY_TRUST_ALL_CERTS) boolean ignoreCert) throws MalformedURLException {
super(baseUrl.toASCIIString(), ignoreCert);
this.setVimNameSpace(vimNameSpace);
this.client = client;
}
@Override
public InputStream post(String soapMsg) throws IOException {
Builder<String, String> headers = ImmutableMultimap.<String, String> builder();
headers.put("SOAPAction", "urn:vim25/4.0");
if (getCookie() != null)
headers.put(HttpHeaders.COOKIE, getCookie());
HttpRequest request;
try {
request = HttpRequest.builder().endpoint(getBaseUrl().toURI()).method("POST").headers(headers.build())
.payload(Payloads.newStringPayload(soapMsg)).build();
} catch (URISyntaxException e) {
Throwables.propagate(e);
return null;// unreachable as the above line will throw the exception.
}
HttpResponse response = client.invoke(request);
if (getCookie() != null && response.getFirstHeaderOrNull(HttpHeaders.SET_COOKIE) != null) {
setCookie(response.getFirstHeaderOrNull(HttpHeaders.SET_COOKIE));
}
return response.getPayload().getInput();
}
}
@Override
protected TemplateBuilder provideTemplate(Injector injector, TemplateBuilder template) {
// String domainDir = injector.getInstance(Key.get(String.class,
// Names.named(PROPERTY_LIBVIRT_DOMAIN_DIR)));
// String domainDir = "";
// String hardwareId = searchForHardwareIdInDomainDir(domainDir);
// String image = searchForImageIdInDomainDir(domainDir);
return template.hardwareId("vm-1221").imageId("winNetEnterprise64Guest");
}
private String searchForImageIdInDomainDir(String domainDir) {
// TODO
return "1";
}
@SuppressWarnings("unchecked")
private String searchForHardwareIdInDomainDir(String domainDir, final ParseSax.Factory factory,
final javax.inject.Provider<UUIDHandler> provider) {
// TODO: remove commons-io dependency
return Iterables.<String> getLast(filter(transform(FileUtils.listFiles(new File(domainDir),
new WildcardFileFilter("*.xml"), null), new Function<File, String>() {
@Override
public String apply(File input) {
try {
return factory.create(provider.get()).parse(new FileInputStream(input));
} catch (FileNotFoundException e) {
// log error.
return null;
}
}
}), notNull()));
}
public static class UUIDHandler extends ParseSax.HandlerWithResult<String> {
private StringBuilder currentText = new StringBuilder();
private boolean inDomain;
private String uuid;
public String getResult() {
return uuid;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
if (qName.equals("domain")) {
inDomain = true;
}
}
@Override
public void endElement(String uri, String localName, String qName) {
if (qName.equalsIgnoreCase("uuid") && inDomain) {
this.uuid = currentText.toString();
} else if (qName.equalsIgnoreCase("domain")) {
inDomain = false;
}
currentText = new StringBuilder();
}
public void characters(char ch[], int start, int length) {
currentText.append(ch, start, length);
}
}
/*
* Map<String, URI> regions = newLinkedHashMap(); for (String region :
* Splitter.on(',').split(regionString)) { regions.put( region,
* URI.create(injector.getInstance(Key.get(String.class, Names.named(Constants.PROPERTY_ENDPOINT
* + "." + region))))); } return regions;
*/
}

View File

@ -1,55 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
import org.jclouds.domain.Location;
import org.jclouds.domain.LocationBuilder;
import org.jclouds.domain.LocationScope;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.vmware.vim25.mo.Datacenter;
/**
* @author Adrian Cole
*/
@Singleton
public class DatacenterToLocation implements Function<Datacenter, Location> {
private final Provider<Supplier<Location>> provider;
// allow us to lazy discover the provider of a resource
@Inject
public DatacenterToLocation(Provider<Supplier<Location>> provider) {
this.provider = checkNotNull(provider, "provider");
}
@Override
public Location apply(Datacenter from) {
return new LocationBuilder().scope(LocationScope.ZONE).id(from.getName()).description(from.getName()).parent(
provider.get().get()).build();
}
}

View File

@ -1,63 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute.functions;
import javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.ImageBuilder;
import org.jclouds.compute.domain.OperatingSystemBuilder;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.logging.Logger;
import com.google.common.base.Function;
/**
* @author Adrian Cole
*/
@Singleton
public class ViImageToImage implements Function<org.jclouds.vi.Image, Image> {
@Resource
@Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL;
@Override
public Image apply(org.jclouds.vi.Image from) {
ImageBuilder builder = new ImageBuilder();
builder.ids(from.id + "");
builder.name(from.name);
builder.description(from.name);
OsFamily family = null;
try {
// TODO
family = OsFamily.fromValue(from.name);
builder.operatingSystem(new OperatingSystemBuilder().name(from.name).family(family).description(from.name).build());
} catch (IllegalArgumentException e) {
logger.debug("<< didn't match os(%s)", from);
}
return builder.build();
}
}

View File

@ -1,85 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute.functions;
import java.util.List;
import javax.inject.Singleton;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.HardwareBuilder;
import org.jclouds.compute.domain.Processor;
import org.jclouds.compute.domain.Volume;
import org.jclouds.compute.domain.internal.VolumeImpl;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.vmware.vim25.VirtualDevice;
import com.vmware.vim25.VirtualDeviceBackingInfo;
import com.vmware.vim25.VirtualDisk;
import com.vmware.vim25.VirtualDiskFlatVer2BackingInfo;
import com.vmware.vim25.mo.VirtualMachine;
/**
* @author Adrian Cole
*/
@Singleton
public class VirtualMachineToHardware implements Function<VirtualMachine, Hardware> {
@Override
public Hardware apply(VirtualMachine from) {
HardwareBuilder builder = new HardwareBuilder();
builder.id(from.getMOR().get_value() + "");
builder.providerId(from.getMOR().get_value() + "");
builder.name(from.getName());
List<Processor> processors = Lists.newArrayList();
for (int i = 0; i < from.getConfig().getHardware().getNumCPU(); i++) {
processors.add(new Processor(i + 1, 1));
}
builder.processors(processors);
builder.ram((int) from.getConfig().getHardware().getMemoryMB());
List<Volume> volumes = Lists.newArrayList();
// look for volumes
VirtualDevice[] devices = from.getConfig().getHardware().getDevice();
for (VirtualDevice virtualDevice : devices) {
if(virtualDevice.getDeviceInfo().getLabel().contains("Hard disk")) {
if(virtualDevice instanceof VirtualDisk) {
VirtualDisk disk = (VirtualDisk) virtualDevice;
VirtualDeviceBackingInfo backingInfo = disk.getBacking();
if(backingInfo instanceof VirtualDiskFlatVer2BackingInfo) {
VirtualDiskFlatVer2BackingInfo diskFlatVer2BackingInfo = (VirtualDiskFlatVer2BackingInfo) backingInfo;
volumes.add(new VolumeImpl(diskFlatVer2BackingInfo.getUuid(), Volume.Type.LOCAL, new Float(disk.getCapacityInKB() + ""), diskFlatVer2BackingInfo.getFileName(), true, false));
}
}
}
}
builder.volumes((List<Volume>) volumes);
return builder.build();
}
protected <T> T propagate(Exception e) {
Throwables.propagate(e);
assert false;
return null;
}
}

View File

@ -1,138 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.collect.FindResourceInSet;
import org.jclouds.collect.Memoized;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.NodeState;
import org.jclouds.compute.domain.OperatingSystemBuilder;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.Location;
import com.google.common.base.Function;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableMap;
import com.vmware.vim25.VirtualMachinePowerState;
import com.vmware.vim25.mo.VirtualMachine;
/**
* @author Adrian Cole
*/
@Singleton
public class VirtualMachineToNodeMetadata implements Function<VirtualMachine, NodeMetadata> {
public static final Map<VirtualMachinePowerState, NodeState> domainStateToNodeState =
ImmutableMap.<VirtualMachinePowerState, NodeState> builder()
.put(VirtualMachinePowerState.poweredOn, NodeState.RUNNING)//
//.put(VirtualMachinePowerState.suspended, NodeState.PENDING)//
.put(VirtualMachinePowerState.suspended, NodeState.SUSPENDED)//
.put(VirtualMachinePowerState.poweredOff, NodeState.TERMINATED)//
.build();
private final Function<VirtualMachine, Hardware> findHardwareForVirtualMachine;
private final FindLocationForVirtualMachine findLocationForVirtualMachine;
private final FindImageForVirtualMachine findImageForVirtualMachine;
private final Map<String, Credentials> credentialStore;
@Inject
VirtualMachineToNodeMetadata(Map<String, Credentials> credentialStore, Function<VirtualMachine, Hardware> findHardwareForVirtualMachine,
FindLocationForVirtualMachine findLocationForVirtualMachine, FindImageForVirtualMachine findImageForVirtualMachine) {
this.credentialStore = checkNotNull(credentialStore, "credentialStore");
this.findHardwareForVirtualMachine = checkNotNull(findHardwareForVirtualMachine, "findHardwareForVirtualMachine");
this.findLocationForVirtualMachine = checkNotNull(findLocationForVirtualMachine, "findLocationForVirtualMachine");
this.findImageForVirtualMachine = checkNotNull(findImageForVirtualMachine, "findImageForVirtualMachine");
}
@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();
}
@Singleton
public static class FindImageForVirtualMachine extends FindResourceInSet<VirtualMachine, Image> {
@Inject
public FindImageForVirtualMachine(@Memoized Supplier<Set<? extends Image>> hardware) {
super(hardware);
}
@Override
public boolean matches(VirtualMachine from, Image input) {
// TODO
// return input.getProviderId().equals(from.imageId + "");
return true;
}
}
@Singleton
public static class FindLocationForVirtualMachine extends FindResourceInSet<VirtualMachine, Location> {
@Inject
public FindLocationForVirtualMachine(@Memoized Supplier<Set<? extends Location>> hardware) {
super(hardware);
}
@Override
public boolean matches(VirtualMachine from, Location input) {
// TODO
// return input.getId().equals(from.datacenter + "");
return true;
}
}
}

View File

@ -1,443 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute.strategy;
import static com.google.common.base.Preconditions.checkNotNull;
import java.rmi.RemoteException;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceAdapter;
import org.jclouds.compute.domain.Template;
import org.jclouds.domain.Credentials;
import org.jclouds.vi.Image;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.vmware.vim25.CustomizationAdapterMapping;
import com.vmware.vim25.CustomizationDhcpIpGenerator;
import com.vmware.vim25.CustomizationFixedName;
import com.vmware.vim25.CustomizationGlobalIPSettings;
import com.vmware.vim25.CustomizationGuiUnattended;
import com.vmware.vim25.CustomizationIPSettings;
import com.vmware.vim25.CustomizationIdentification;
import com.vmware.vim25.CustomizationIdentitySettings;
import com.vmware.vim25.CustomizationLicenseDataMode;
import com.vmware.vim25.CustomizationLicenseFilePrintData;
import com.vmware.vim25.CustomizationPassword;
import com.vmware.vim25.CustomizationSpec;
import com.vmware.vim25.CustomizationSysprep;
import com.vmware.vim25.CustomizationUserData;
import com.vmware.vim25.CustomizationWinOptions;
import com.vmware.vim25.InvalidProperty;
import com.vmware.vim25.RuntimeFault;
import com.vmware.vim25.VirtualMachineCloneSpec;
import com.vmware.vim25.VirtualMachineRelocateSpec;
import com.vmware.vim25.mo.Datacenter;
import com.vmware.vim25.mo.Datastore;
import com.vmware.vim25.mo.Folder;
import com.vmware.vim25.mo.HostDatastoreBrowser;
import com.vmware.vim25.mo.HostSystem;
import com.vmware.vim25.mo.InventoryNavigator;
import com.vmware.vim25.mo.ManagedEntity;
import com.vmware.vim25.mo.ResourcePool;
import com.vmware.vim25.mo.ServiceInstance;
import com.vmware.vim25.mo.Task;
import com.vmware.vim25.mo.VirtualMachine;
/**
* defines the connection between the {@link VI} implementation and the jclouds
* {@link ComputeService}
*
*/
@Singleton
public class ViComputeServiceAdapter implements ComputeServiceAdapter<VirtualMachine, VirtualMachine, Image, Datacenter> {
private final ServiceInstance client;
private String resourcePoolName = "";
private String vmwareHostName = "";
private String datastoreName = "";
private String vmClonedName = "MyWinClone";
@Inject
public ViComputeServiceAdapter(ServiceInstance client) {
this.client = checkNotNull(client, "client");
}
@Override
public VirtualMachine createNodeWithGroupEncodedIntoNameThenStoreCredentials(String tag,
String name, Template template,
Map<String, Credentials> credentialStore) {
try {
Folder rootFolder = client.getRootFolder();
VirtualMachine from = (VirtualMachine) new InventoryNavigator(
rootFolder).searchManagedEntity("VirtualMachine", tag);
if (from == null) {
client.getServerConnection().logout();
return null;
}
VirtualMachineCloneSpec cloneSpec = new VirtualMachineCloneSpec();
VirtualMachineRelocateSpec virtualMachineRelocateSpec = new VirtualMachineRelocateSpec();
if (!vmwareHostName.equals("") && !datastoreName.equals("") && !resourcePoolName.equals("")) {
ResourcePool rp = (ResourcePool) new InventoryNavigator(rootFolder)
.searchManagedEntity("ResourcePool", resourcePoolName);
if(rp == null)
throw new Exception("The resourcePool specified '" + resourcePoolName + "' doesn't exist");
virtualMachineRelocateSpec.setPool(rp.getMOR());
Datastore ds = (Datastore) new InventoryNavigator(rootFolder)
.searchManagedEntity("Datastore", datastoreName);
HostSystem host = null;
host = (HostSystem) new InventoryNavigator(rootFolder)
.searchManagedEntity("HostSystem", vmwareHostName);
HostDatastoreBrowser hdb = host.getDatastoreBrowser();
if(ds == null)
throw new Exception("Cannot relocate this cloned machine to the specified datastore '" + datastoreName + "'");
Datastore dsFound = null;
Datastore[] dsArray = hdb.getDatastores();
for (Datastore d : dsArray) {
if(d.getName().equalsIgnoreCase(ds.getName()))
dsFound = d;
}
if(dsFound == null)
throw new Exception("Cannot relocate this cloned machine to the specified datastore '" + datastoreName + "'");
virtualMachineRelocateSpec.setDatastore(dsFound.getMOR());
}
CustomizationSpec custSpec = new CustomizationSpec();
CustomizationAdapterMapping cam = new CustomizationAdapterMapping();
CustomizationIPSettings cip = new CustomizationIPSettings();
cip.setIp(new CustomizationDhcpIpGenerator());
cam.setAdapter(cip);
// IP customization
// CustomizationAdapterMapping[] custAdapMapList = new CustomizationAdapterMapping[1];
// CustomizationAdapterMapping custAdapMap = new CustomizationAdapterMapping();
// CustomizationIPSettings custIPSettings = new CustomizationIPSettings();
// CustomizationFixedIp custFixedIp = new CustomizationFixedIp();
// custFixedIp.setIpAddress(ipAddress);
// custIPSettings.setIp(custFixedIp);
// custAdapMap.setAdapter(custIPSettings);
// custAdapMapList[0] = custAdapMap;
// custSpec.setNicSettingMap(custAdapMapList);
CustomizationGlobalIPSettings custGlobalIPSetting = new CustomizationGlobalIPSettings();
CustomizationIdentitySettings custIdentitySet = new CustomizationIdentitySettings();
// sysprep customization
CustomizationSysprep custSysprep = new CustomizationSysprep();
CustomizationGuiUnattended guiUnattended = new CustomizationGuiUnattended();
guiUnattended.setAutoLogon(false);
guiUnattended.setAutoLogonCount(0);
guiUnattended.setTimeZone(190);
// user data
CustomizationPassword custPasswd = new CustomizationPassword();
custPasswd.setPlainText(true);
custPasswd.setValue("password");
CustomizationIdentification custIdentification = new CustomizationIdentification();
custIdentification.setDomainAdmin("Administrator");
custIdentification.setDomainAdminPassword(custPasswd);
custIdentification.setJoinWorkgroup("WORKGROUP");
CustomizationUserData custUserData = new CustomizationUserData();
CustomizationFixedName custFixedName = new CustomizationFixedName();
custFixedName.setName("mycomputer");
custUserData.setComputerName(custFixedName);
custUserData.setFullName("sjain");
custUserData.setOrgName("vmware");
custUserData.setProductId("PDRXT-M9X8G-898BR-4K427-J2FFY");
///////
CustomizationWinOptions customizationWinOptions = new CustomizationWinOptions();
customizationWinOptions.setChangeSID(true);
customizationWinOptions.setDeleteAccounts(false);
CustomizationLicenseFilePrintData custLPD = new CustomizationLicenseFilePrintData();
custLPD.setAutoMode(CustomizationLicenseDataMode.perServer);
custSysprep.setLicenseFilePrintData(custLPD);
custSysprep.setUserData(custUserData);
custSysprep.setGuiUnattended(guiUnattended);
custSysprep.setIdentification(custIdentification);
custSpec.setIdentity(custSysprep);
custSpec.setNicSettingMap(new CustomizationAdapterMapping[] {cam});
custSpec.setGlobalIPSettings(custGlobalIPSetting);
custSpec.setOptions(customizationWinOptions);
cloneSpec.setCustomization(custSpec);
//location properties
cloneSpec.setLocation(virtualMachineRelocateSpec);
cloneSpec.setPowerOn(false);
cloneSpec.setTemplate(false);
Task task = from.cloneVM_Task((Folder) from.getParent(), vmClonedName,
cloneSpec);
String result = task.waitForTask();
return (VirtualMachine) new InventoryNavigator(
rootFolder).searchManagedEntity("VirtualMachine", vmClonedName);
} catch (RemoteException e) {
return propogate(e);
} catch (Exception e) {
return propogate(e);
}
}
@Override
public Iterable<VirtualMachine> listHardwareProfiles() {
// TODO
List<VirtualMachine> hardwareProfiles = Lists.newArrayList();
try {
ManagedEntity[] entities = new InventoryNavigator(
client.getRootFolder()).searchManagedEntities("VirtualMachine");
for (ManagedEntity entity : entities) {
hardwareProfiles.add((VirtualMachine) entity);
}
return hardwareProfiles;
} catch (Exception e) {
return propogate(e);
}
}
@Override
public Iterable<Image> listImages() {
List<Image> images = Lists.newArrayList();
try {
ManagedEntity[] entities = new InventoryNavigator(
client.getRootFolder()).searchManagedEntities("VirtualMachine");
for (ManagedEntity entity : entities) {
VirtualMachine vm = (VirtualMachine) entity;
images.add(new Image(vm.getConfig().getGuestId(), vm.getConfig().getGuestFullName()));
}
return images;
} catch (Exception e) {
return propogate(e);
}
}
@Override
public Iterable<VirtualMachine> listNodes() {
try {
ManagedEntity[] vmEntities = new InventoryNavigator(client.getRootFolder()).searchManagedEntities("VirtualMachine");
List<VirtualMachine> vms = Lists.newArrayList();
for (ManagedEntity entity : vmEntities) {
VirtualMachine vm = (VirtualMachine) entity;
vms.add(vm);
}
return vms;
} catch (InvalidProperty e) {
return propogate(e);
} catch (RuntimeFault e) {
return propogate(e);
} catch (RemoteException e) {
return propogate(e);
}
}
@Override
public Iterable<Datacenter> listLocations() {
ManagedEntity[] datacenterEntities;
try {
datacenterEntities = new InventoryNavigator(client.getRootFolder()).searchManagedEntities("Datacenter");
List<Datacenter> datacenters = Lists.newArrayList();
for (int i = 0; i< datacenterEntities.length; i++) {
datacenters.add((Datacenter) datacenterEntities[i]);
}
return datacenters;
} catch (InvalidProperty e) {
return propogate(e);
} catch (RuntimeFault e) {
return propogate(e);
} catch (RemoteException e) {
return propogate(e);
}
}
@Override
public VirtualMachine getNode(String vmName) {
Folder rootFolder = client.getRootFolder();
try {
return (VirtualMachine) new InventoryNavigator(
rootFolder).searchManagedEntity("VirtualMachine", vmName);
} catch (InvalidProperty e) {
return propogate(e);
} catch (RuntimeFault e) {
return propogate(e);
} catch (RemoteException e) {
return propogate(e);
}
}
@Override
public void destroyNode(String id) {
/*
try {
client.domainLookupByUUIDString(id).destroy();
XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(
client.domainLookupByUUIDString(id).getXMLDesc(0)
)));
String diskFileName = builder.xpathFind("//devices/disk[@device='disk']/source").getElement().getAttribute("file");
StorageVol storageVol = client.storageVolLookupByPath(diskFileName);
storageVol.delete(0);
client.domainLookupByUUIDString(id).undefine();
} catch (LibvirtException e) {
propogate(e);
} catch (Exception e) {
propogate(e);
}
*/
}
@Override
public void rebootNode(String id) {
/*
try {
client.domainLookupByUUIDString(id).reboot(0);
} catch (LibvirtException e) {
propogate(e);
}
*/
}
@Override
public void resumeNode(String id) {
/*
try {
client.domainLookupByUUIDString(id).resume();
} catch (LibvirtException e) {
propogate(e);
}
*/
}
@Override
public void suspendNode(String id) {
/*
try {
client.domainLookupByUUIDString(id).suspend();
} catch (LibvirtException e) {
propogate(e);
}
*/
}
protected <T> T propogate(Exception e) {
Throwables.propagate(e);
assert false;
return null;
}
/*
private static StorageVol cloneVolume(StoragePool storagePool, StorageVol from) throws LibvirtException,
XPathExpressionException, ParserConfigurationException, SAXException, IOException, TransformerException {
return storagePool.storageVolCreateXMLFrom(generateClonedVolumeXML(from.getXMLDesc(0)), from, 0);
}
private static String generateClonedVolumeXML(String fromXML) throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException, TransformerException {
Properties outputProperties = generateOutputXMLProperties();
XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(fromXML)));
String nodeNamingConvention = "%s-%s";
String tag = "-clone";
String suffix = String.format(nodeNamingConvention, tag, Integer.toHexString(new SecureRandom().nextInt(4095)));
builder.xpathFind("//volume/name").t(suffix);
builder.xpathFind("//volume/key").t(suffix);
builder.xpathFind("//volume/target/path").t(suffix);
return builder.asString(outputProperties);
}
private static String generateClonedDomainXML(String fromXML, StorageVol clonedVol) throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException, TransformerException, LibvirtException {
Properties outputProperties = generateOutputXMLProperties();
XMLBuilder builder = XMLBuilder.parse(new InputSource(new StringReader(fromXML)));
String nodeNamingConvention = "%s-%s";
String tag = "-clone";
String suffix = String.format(nodeNamingConvention, tag, Integer.toHexString(new SecureRandom().nextInt(4095)));
builder.xpathFind("//domain/name").t(suffix);
// change uuid domain
Element oldChild = builder.xpathFind("//domain/uuid").getElement();
Node newNode = oldChild.cloneNode(true);
newNode.getFirstChild().setNodeValue(UUID.randomUUID().toString());
builder.getDocument().getDocumentElement().replaceChild(newNode, oldChild);
//String fromVolPath = builder.xpathFind("//domain/devices/disk/source").getElement().getAttribute("file");
builder.xpathFind("//domain/devices/disk/source").a("file", clonedVol.getPath());
// generate valid MAC address
String fromMACaddress = builder.xpathFind("//domain/devices/interface/mac").getElement().getAttribute("address");
String lastMACoctet = Integer.toHexString(new SecureRandom().nextInt(255));
builder.xpathFind("//domain/devices/interface/mac").a("address",
fromMACaddress.substring(0, fromMACaddress.lastIndexOf(":")+1) + lastMACoctet
);
return builder.asString(outputProperties);
}
private static Properties generateOutputXMLProperties() {
Properties outputProperties = new Properties();
// Explicitly identify the output as an XML document
outputProperties.put(javax.xml.transform.OutputKeys.METHOD, "xml");
// Pretty-print the XML output (doesn't work in all cases)
outputProperties.put(javax.xml.transform.OutputKeys.INDENT, "yes");
// Get 2-space indenting when using the Apache transformer
outputProperties.put("{http://xml.apache.org/xslt}indent-amount", "2");
return outputProperties;
}
*/
}

View File

@ -1,33 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.reference;
/**
* Configuration properties and constants used in VI connections.
*
* @author Adrian Cole
*/
public interface ViConstants {
public static final String PROPERTY_VI_XML_NAMESPACE = "jclouds.vi.xml.ns";
public static final String PROPERTY_VI_IGNORE_CERTIFICATE = "jclouds.ignore-certificate";
}

View File

@ -1,52 +0,0 @@
package org.jclouds.vi.compute;
import static org.testng.Assert.assertEquals;
import java.util.Properties;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.rest.RestContext;
import org.testng.annotations.Test;
import com.vmware.vim25.mo.ServiceInstance;
/**
*
* @author andrea.turli
*
*/
@Test(groups = "unit")
public class ViComputeServiceContextBuilderTest {
@Test
public void testCanBuildWithContextSpec() {
ComputeServiceContext context = new ComputeServiceContextFactory().createContext(new ViComputeServiceContextSpec(
"https://localhost/sdk", "Administrator", "password"));
context.getComputeService().listNodes();
context.close();
}
@Test
public void testCanBuildWithRestProperties() {
Properties restProperties = new Properties();
restProperties.setProperty("vi.contextbuilder", ViComputeServiceContextBuilder.class.getName());
restProperties.setProperty("vi.propertiesbuilder", ViPropertiesBuilder.class.getName());
restProperties.setProperty("vi.endpoint", "https://localhost/sdk");
ComputeServiceContext context = new ComputeServiceContextFactory(restProperties).createContext("vi",
"identity", "credential");
context.close();
}
@Test
public void testProviderSpecificContextIsCorrectType() {
ComputeServiceContext context = new ViComputeServiceContextBuilder(new Properties()).buildComputeServiceContext();
RestContext<ServiceInstance, ServiceInstance> providerContext = context.getProviderSpecificContext();
assertEquals(providerContext.getApi().getClass(), ServiceInstance.class);
context.close();
}
}

View File

@ -1,57 +0,0 @@
package org.jclouds.vi.compute;
import static org.jclouds.compute.util.ComputeServiceUtils.getCores;
import static org.testng.Assert.assertEquals;
import java.util.Properties;
import org.jclouds.compute.BaseComputeServiceLiveTest;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.rest.RestContext;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.Test;
import com.vmware.vim25.mo.ServiceInstance;
/**
* @author Adrian Cole
*/
@Test(groups = "live", enabled = true, sequential = true)
public class ViComputeServiceLiveTest extends BaseComputeServiceLiveTest {
public ViComputeServiceLiveTest() {
provider = "vi";
}
@Override
protected Properties getRestProperties() {
Properties restProperties = new Properties();
restProperties.setProperty("vi.contextbuilder", ViComputeServiceContextBuilder.class.getName());
restProperties.setProperty("vi.propertiesbuilder", ViPropertiesBuilder.class.getName());
restProperties.setProperty("vi.endpoint", "https://localhost/sdk");
return restProperties;
}
@Test
public void testTemplateBuilder() {
Template defaultTemplate = client.templateBuilder().build();
assertEquals(defaultTemplate.getImage().getOperatingSystem().is64Bit(), true);
assertEquals(defaultTemplate.getImage().getOperatingSystem().getVersion(), "5.3");
assertEquals(defaultTemplate.getImage().getOperatingSystem().getFamily(), OsFamily.CENTOS);
assertEquals(defaultTemplate.getLocation().getId(), "1");
assertEquals(getCores(defaultTemplate.getHardware()), 0.5d);
}
@Override
protected JschSshClientModule getSshModule() {
return new JschSshClientModule();
}
public void testAssignability() throws Exception {
@SuppressWarnings("unused")
RestContext<ServiceInstance, ServiceInstance> viContext = new ComputeServiceContextFactory().createContext(
provider, identity, credential).getProviderSpecificContext();
}
}

View File

@ -1,116 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.vi.compute;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Set;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.domain.Image;
import org.jclouds.domain.Location;
import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Module;
/**
*
* @author Adrian Cole
*/
@Test(groups = "live", testName = "vsphere.ViExperimentLiveTest")
public class ViExperimentLiveTest {
protected String provider = "vsphere";
protected String identity;
protected String credential;
protected String endpoint;
protected String apiversion;
@BeforeClass
protected void setupCredentials() {
identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity");
credential = System.getProperty("test." + provider + ".credential");
endpoint = System.getProperty("test." + provider + ".endpoint");
apiversion = System.getProperty("test." + provider + ".apiversion");
}
@Test
public void testAndExperiment() {
ComputeServiceContext context = null;
try {
context = new ComputeServiceContextFactory().createContext(new ViComputeServiceContextSpec(endpoint, identity,
credential), ImmutableSet.<Module>of(new Log4JLoggingModule()), new ViPropertiesBuilder().build());
Set<? extends Location> locations = context.getComputeService().listAssignableLocations();
for (Location location : locations) {
System.out.println("location id: " + location.getId() + " - desc: " + location.getDescription());
}
Set<? extends Image> images = context.getComputeService().listImages();
for (Image image : images) {
System.out.println("id: " + image.getId() + " - name:" + image.getName());
// Set<? extends ComputeMetadata> nodes = context.getComputeService().listNodes();
//
Set<? extends Hardware> hardwares = context.getComputeService().listHardwareProfiles();
for (Hardware hardware : hardwares) {
System.out.println("hardware id: " + hardware.getId() + " - name: " + hardware.getName());
}
//
}
//
// NodeMetadata node = context.getComputeService().getNodeMetadata("MyWinServer");
// System.out.println(node);
/*
* We will probably make a default template out of properties at some point You can control
* the default template via overriding a method in standalonecomputeservicexontextmodule
*/
/*
* Template defaultTemplate = context.getComputeService().templateBuilder()
* .hardwareId("vm-1221").imageId("winNetEnterprise64Guest") //.locationId("") .build();
*
* Set<? extends NodeMetadata> nodeMetadataSet =
* context.getComputeService().runNodesWithTag("MyWinServer", 1); for (NodeMetadata
* nodeMetadata : nodeMetadataSet) {
*
* // context.getComputeService().suspendNode(nodeMetadata.getId()); //
* context.getComputeService().resumeNode(nodeMetadata.getId());
*
* //context.getComputeService().destroyNode(nodeMetadata.getId()); }
*/
} catch (Exception e) {
e.printStackTrace();
} finally {
if (context != null)
context.close();
}
}
}

View File

@ -1,136 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright (C) 2009 Cloud Conscious, LLC.
<info@cloudconscious.com>
====================================================================
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0 Unless required by
applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions
and limitations under the License.
====================================================================
-->
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<!--
For more configuration infromation and examples see the Apache
Log4j website: http://logging.apache.org/log4j/
-->
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
debug="false">
<!-- A time/date based rolling appender -->
<appender name="WIREFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-wire.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<!-- A time/date based rolling appender -->
<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<!-- A time/date based rolling appender -->
<appender name="COMPUTEFILE" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="target/test-data/jclouds-compute.log" />
<param name="Append" value="true" />
<!-- Rollover at midnight each day -->
<param name="DatePattern" value="'.'yyyy-MM-dd" />
<param name="Threshold" value="TRACE" />
<layout class="org.apache.log4j.PatternLayout">
<!-- The default pattern: Date Priority [Category] Message\n -->
<param name="ConversionPattern" value="%d %-5p [%c] (%t) %m%n" />
<!--
The full pattern: Date MS Priority [Category]
(Thread:NDC) Message\n <param name="ConversionPattern"
value="%d %-5r %-5p [%c] (%t:%x) %m%n"/>
-->
</layout>
</appender>
<appender name="ASYNCCOMPUTE" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="COMPUTEFILE" />
</appender>
<appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="FILE" />
</appender>
<appender name="ASYNCWIRE" class="org.apache.log4j.AsyncAppender">
<appender-ref ref="WIREFILE" />
</appender>
<!-- ================ -->
<!-- Limit categories -->
<!-- ================ -->
<category name="org.jclouds">
<priority value="DEBUG" />
<appender-ref ref="ASYNC" />
</category>
<category name="jclouds.headers">
<priority value="DEBUG" />
<appender-ref ref="ASYNCWIRE" />
</category>
<category name="jclouds.wire">
<priority value="DEBUG" />
<appender-ref ref="ASYNCWIRE" />
</category>
<category name="jclouds.compute">
<priority value="TRACE" />
<appender-ref ref="ASYNCCOMPUTE" />
</category>
<!-- ======================= -->
<!-- Setup the Root category -->
<!-- ======================= -->
<root>
<priority value="DEBUG" />
</root>
</log4j:configuration>