1
0
mirror of https://github.com/OpenNebula/one.git synced 2025-03-22 18:50:08 +03:00

Remove java vmware drivers from OpenNebula distribution

Now moved to a separate project: http://dev.opennebula.org/projects/vmware-java
This commit is contained in:
Tino Vázquez 2010-10-15 19:43:02 +02:00
parent dfb9114cf6
commit ced309d4aa
16 changed files with 0 additions and 2617 deletions

View File

@ -1,304 +0,0 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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. */
/* -------------------------------------------------------------------------- */
import com.vmware.vim.*;
import com.vmware.apputils.*;
import com.vmware.apputils.vim.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.rmi.RemoteException;
/*
* Used to obtain properties from Managed Object Reference from ESXi
*/
public class GetProperty
{
String[] args;
String entity;
String entityName;
// Helpers from VI samples
private static ServiceContent content;
private static AppUtil cb = null;
private static VimPortType service;
private ManagedObjectReference moRef;
// Measure of the property
private double measure;
/*
* Gets first property that matches propertyName
* @param moRef, objet to get property from
* @param propertyName, name of the property
* @return representation of the property
*/
Object getObjectProperty(String propertyName)
throws RuntimeFault, RemoteException
{
return getProperties(new String[] { propertyName })[0];
}
/*
* Gets properties that matches any of the strings
* @param moRef, objet to get properties from
* @param propertyName, name of the property
* @return representation of the properties
*/
Object[] getProperties(String[] properties)
throws RuntimeFault, RemoteException
{
// PropertySpec specifies what properties to
// retrieve and from type of Managed Object
PropertySpec pSpec = new PropertySpec();
pSpec.setType(moRef.getType());
pSpec.setPathSet(properties);
// ObjectSpec specifies the starting object and
// any TraversalSpecs used to specify other objects
// for consideration
ObjectSpec oSpec = new ObjectSpec();
oSpec.setObj(moRef);
// PropertyFilterSpec is used to hold the ObjectSpec and
// PropertySpec for the call
PropertyFilterSpec pfSpec = new PropertyFilterSpec();
pfSpec.setPropSet(new PropertySpec[] {pSpec});
pfSpec.setObjectSet(new ObjectSpec[] {oSpec});
// retrieveProperties() returns the properties
// selected from the PropertyFilterSpec
ObjectContent[] ocs = service.retrieveProperties(
content.getPropertyCollector(),
new PropertyFilterSpec[] {pfSpec});
// Return value, one object for each property specified
Object[] ret = new Object[properties.length];
if(ocs != null)
{
for(int i=0; i<ocs.length; ++i)
{
ObjectContent oc = ocs[i];
DynamicProperty[] dps = oc.getPropSet();
if(dps != null)
{
for(int j=0; j<dps.length; ++j)
{
DynamicProperty dp = dps[j];
// find property path index
for(int p=0; p<ret.length; ++p)
{
if(properties[p].equals(dp.getName()))
{
ret[p] = dp.getVal();
}
}
}
}
}
}
return ret;
}
/*
* Gets performance counter from a MOB (ManagedObjectReference). Sets measure to
* be retrieved using getMeasure
* @param mor, ManagedObjectReference
* @param counter, name of the performance counter
* @return representation of the properties
*/
public boolean getPerformanceCounter(String counter,
int intervalInt) throws Exception
{
int counterID;
int key;
String group;
String name;
String rollup;
// Get the Performance Manager
ManagedObjectReference pmRef
= cb.getConnection().getServiceContent().getPerfManager();
// Get supported perf counters in the system
PerfCounterInfo[] cInfo
= (PerfCounterInfo[])cb.getServiceUtil().getDynamicProperty(pmRef,
"perfCounter");
// Create a hashmap for these counters
TreeMap PerfByID = new TreeMap();
TreeMap PerfByName = new TreeMap();
for (int i = 0; i < cInfo.length; i++)
{
key = cInfo[i].getKey();
group = cInfo[i].getGroupInfo().getKey();
name = cInfo[i].getNameInfo().getKey();
rollup = cInfo[i].getRollupType().toString();
PerfByID.put (key, group + "." + name + "." + rollup);
PerfByName.put(group + "." + name + "." + rollup, key);
}
Integer origCounterId = (Integer)PerfByName.get(counter);
PerfProviderSummary perfSum
= cb.getConnection().getService().queryPerfProviderSummary(pmRef, moRef);
Integer interval = perfSum.getRefreshRate();
// Get available Performance metrics for the entity
PerfMetricId[] Ids =
cb.getConnection().getService().queryAvailablePerfMetric(pmRef,
moRef, null, null, interval);
boolean idExists = false;
PerfMetricId[] metricId = null;
if (Ids != null)
{
for (int j = 0; j < Ids.length; j++)
{
// Check if the counter exists for the entity
if (Ids[j].getCounterId() == origCounterId)
{
idExists = true;
metricId = new PerfMetricId[]{Ids[j]};
break;
}
}
if (idExists)
{
Integer Intv = new Integer(intervalInt);
PerfQuerySpec qSpec = new PerfQuerySpec();
qSpec.setEntity(moRef);
qSpec.setMetricId(metricId);
qSpec.setFormat("normal");
qSpec.setIntervalId(interval);
qSpec.setMaxSample(1);
PerfQuerySpec[] qSpecs = new PerfQuerySpec[] {qSpec};
if (moRef != null)
{
PerfEntityMetricBase[] pEntity = getPerfIdsAvailable(qSpecs, pmRef);
if (pEntity != null)
{
for (int i = 0; i < pEntity.length; i++)
{
PerfMetricSeries[] vals = ((PerfEntityMetric)pEntity[i]).getValue();
PerfSampleInfo[] infos = ((PerfEntityMetric)pEntity[i]).getSampleInfo();
if (vals != null)
{
for (int vi=0; vi<vals.length; ++vi)
{
counterID = vals[vi].getId().getCounterId();
if(vals[vi] instanceof PerfMetricIntSeries)
{
PerfMetricIntSeries val = (PerfMetricIntSeries)vals[vi];
long[] longs = val.getValue();
if (longs !=null && longs.length>=1)
{
measure = longs[(longs.length-1)];
return true;
}
}
}
}
}
}
}
}
else
{
return false;
}
}
return false;
}
private PerfEntityMetricBase[] getPerfIdsAvailable(PerfQuerySpec[] querySpecs,
ManagedObjectReference entityMoRef) throws Exception
{
PerfEntityMetricBase[] perfEntity = null;
if (entityMoRef != null)
{
try
{
perfEntity
= cb.getConnection().getService().queryPerf(entityMoRef, querySpecs);
}
catch (Exception e)
{
}
}
return perfEntity;
}
public double getMeasure()
{
return measure;
}
public boolean connect()
{
try
{
cb = AppUtil.initialize("GetProperty", null, args);
cb.connect();
moRef = cb.getServiceUtil().getDecendentMoRef(null,entity,
entityName);
com.vmware.apputils.vim.ServiceConnection sc = cb.getConnection();
content = sc.getServiceContent();
service = sc.getService();
return true;
}
catch(Exception e)
{
return false;
}
}
public void disconnect()
{
try
{
cb.disConnect();
}
catch(Exception e){}
}
GetProperty(String[] arguments, String _entity, String _entityName)
{
args = arguments;
entity = _entity;
entityName = _entityName;
}
}

View File

@ -1,321 +0,0 @@
/*
# -------------------------------------------------------------------------#
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
# 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. #
#--------------------------------------------------------------------------#
*/
import java.io.*;
import java.text.*;
import java.util.*;
import com.vmware.vim.*;
import com.vmware.apputils.*;
import com.vmware.apputils.vim.*;
/************************************
* Monitors physical VMware hosts *
* through the VI API *
************************************/
class OneImVmware extends Thread
{
private String[] arguments;
boolean debug;
PrintStream stdout;
PrintStream stderr;
// Entry point - main procedure
public static void main(String[] args)
{
boolean debug_flag;
if (System.getProperty("debug").equals("1"))
{
debug_flag=true;
}
else
{
debug_flag=false;
}
OneImVmware oiv = new OneImVmware(args,debug_flag);
oiv.loop();
}
// Constructor
OneImVmware(String[] args,boolean _debug)
{
debug = _debug;
arguments = args;
// Get out and err descriptors
stdout = System.out;
stderr = System.err;
// No VMware library output to standard out
// or err. This will be activated when needed
disable_standard_output();
disable_standard_error();
}
// Main loop
void loop()
{
String str = null;
String action = null;
String host;
String hid_str = null;
String hostToMonitor;
boolean end = false;
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
while (!end)
{
// Read a line a parse it
try
{
str = in.readLine();
}
catch (IOException e)
{
String message = e.getMessage().replace('\n', ' ');
send_message(action + " FAILURE " + hid_str + " " + message);
send_error (action + " FAILURE " + hid_str +
" Action malformed. Reason: " + message);
}
String str_split[] = str.split(" ", 4);
action = str_split[0].toUpperCase();
// Perform the action
if (action.equals("INIT"))
{
init();
}
else if (action.equals("FINALIZE"))
{
finalize_mad();
end = true;
} else if (str_split.length != 3)
{
send_message("FAILURE Unknown command");
}
else
{
action = str_split[0].toUpperCase();
hid_str = str_split[1];
hostToMonitor = str_split[2];
if (action.equals("MONITOR"))
{
// Let's gather data from the host
GetProperty gP;
boolean rf;
String response = "HYPERVISOR=vmware";
String[] argsWithHost =
new String[arguments.length+2];
for(int i=0;i<arguments.length;i++)
{
argsWithHost[i] = arguments[i];
}
argsWithHost[arguments.length] = "--url";
argsWithHost[arguments.length + 1 ] =
"https://" + hostToMonitor + ":443/sdk";
gP = new GetProperty(argsWithHost,
"HostSystem",
hostToMonitor);
try
{
if(!gP.connect())
{
throw new Exception("Connection to host " +
hostToMonitor + " failed.");
}
// Now it's time to build the response
// gathering the needed properties
// Static Information
long totalMemory =
Long.parseLong(gP.getObjectProperty("hardware.memorySize").toString().trim());
totalMemory /= 1024;
response = response + ",TOTALMEMORY=" + totalMemory;
int numCpus =
Integer.parseInt(gP.getObjectProperty("hardware.cpuInfo.numCpuCores").
toString().trim());
numCpus *= 100;
response = response + ",TOTALCPU=" + numCpus;
response = response + ",MODELNAME=\""
+ gP.getObjectProperty("hardware.systemInfo.model")
+ "\"";
double cpuSpeed =
Double.parseDouble(gP.getObjectProperty("hardware.cpuInfo.hz").toString().trim());
// From hz to Mhz
cpuSpeed/=1000000;
response = response + ",CPUSPEED=" + (int)cpuSpeed;
// Dynamic Information
// CPU
rf = gP.getPerformanceCounter("cpu.usage.average", 60);
if (!rf) throw new Exception();
// Convert from 1/10000 to 1/100
int usedCpu = (int)(gP.getMeasure()/100);
response = response + ",USEDCPU="+usedCpu;
response = response + ",FREECPU="+(100-usedCpu);
// MEM
rf = gP.getPerformanceCounter("mem.usage.average", 60);
if (!rf) throw new Exception();
// Convert from percentage to actual value
int usedMemory = (int)(totalMemory * (gP.getMeasure()/100))/100;
response = response + ",USEDMEMORY=" + usedMemory;
response = response + ",FREEMEMORY=" + (totalMemory-usedMemory);
// NET
int net=0;
rf = gP.getPerformanceCounter("net.transmitted.average", 60);
if (!rf) net = 0;
else net = (int)gP.getMeasure();
response = response + ",NETTX=" + net;
rf = gP.getPerformanceCounter("net.received.average", 60);
if (!rf) net = 0;
else net = (int)gP.getMeasure();
response = response + ",NETRX=" + net;
// Send the actual response
send_message("MONITOR SUCCESS " + hid_str + " " + response);
gP.disconnect();
}
catch(Exception e)
{
gP.disconnect();
send_message("MONITOR FAILURE " + hid_str + " Failed monitoring host " +
hostToMonitor + ".");
if(debug)
{
send_error("Failed monitoring host " + hostToMonitor +
".Reason: "+ e.getMessage() +
"\n---- Debug stack trace ----");
enable_standard_error();
e.printStackTrace();
disable_standard_error();
send_error("---------------------------");
}
else
{ // If debug activated, this will be replicated in send_message
send_error("MONITOR FAILURE " + hid_str + " Failed monitoring host " + hostToMonitor);
}
} // catch
} // if (action.equals("MONITOR"))
} // else if (str_split.length != 4)
} // while(!end)
} // loop
void init()
{
// Nothing to do here
send_message("INIT SUCCESS");
}
void finalize_mad()
{
// Nothing to do here
send_message("FINALIZE SUCCESS");
}
void enable_standard_output()
{
System.setOut(stdout);
}
void enable_standard_error()
{
System.setErr(stderr);
}
void disable_standard_output()
{
try
{
System.setOut(new PrintStream(new FileOutputStream("/dev/null")));
}
catch(Exception e)
{}
}
void disable_standard_error()
{
try
{
System.setErr(new PrintStream(new FileOutputStream("/dev/null")));
}
catch(Exception e)
{}
}
void send_message(String str)
{
synchronized (System.out)
{
enable_standard_output();
System.out.println(str);
disable_standard_output();
}
if(debug) send_error(str);
}
void send_error(String str)
{
Date date = new Date();
Format formatter;
formatter = new SimpleDateFormat("[dd.MM.yyyy HH:mm:ss] ");
synchronized (System.err)
{
enable_standard_error();
System.err.println(formatter.format(date)+str);
disable_standard_error();
}
}
}

View File

@ -1,23 +0,0 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
# 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. #
#--------------------------------------------------------------------------- #
# This must point to a java keystore with appropriate certificates for accessing
# all the ESXi hosts
#VMWARE_TRUSTORE=<path_to_keystore>
# Uncomment the following line to active MAD debug
#ONE_MAD_DEBUG=1

View File

@ -1,55 +0,0 @@
#!/bin/bash
# -------------------------------------------------------------------------- #
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
# 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. #
#--------------------------------------------------------------------------- #
#Setup driver variables
DRIVER_NAME="im_vmware"
if [ -z "${ONE_LOCATION}" ]; then
DRIVERRC=/etc/one/${DRIVER_NAME}/${DRIVER_NAME}rc
MADCOMMON=/usr/lib/one/mads/madcommon.sh
else
DRIVERRC=$ONE_LOCATION/etc/${DRIVER_NAME}/${DRIVER_NAME}rc
MADCOMMON=$ONE_LOCATION/lib/mads/madcommon.sh
fi
. $MADCOMMON
# Export the im_mad specific rc
export_rc_vars $DRIVERRC
LOG_FILE=$DRIVER_NAME
MAD_FILE="OneImVmware"
if [ -z "${ONE_LOCATION}" ]; then
MAD_LOG_PATH=/var/log/one/$LOG_FILE.log
else
MAD_LOG_PATH=$ONE_LOCATION/var/$LOG_FILE.log
fi
# Execute the actual MAD
if [ -n "${ONE_MAD_DEBUG}" ]; then
exec nice -n $PRIORITY java -cp $ONE_LOCATION/lib/mads:$CLASSPATH -Ddebug=$ONE_MAD_DEBUG -Djavax.net.ssl.trustStore=$VMWARE_TRUSTORE -Xmx1024M $MAD_FILE $* 2>> $MAD_LOG_PATH
else
exec nice -n $PRIORITY java -cp $ONE_LOCATION/lib/mads:$CLASSPATH -Ddebug=$ONE_MAD_DEBUG -Djavax.net.ssl.trustStore=$VMWARE_TRUSTORE -Xmx1024M $MAD_FILE $* 2> /dev/null
fi

View File

@ -1,48 +0,0 @@
#!/bin/bash
# -------------------------------------------------------------------------- #
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
# 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. #
#--------------------------------------------------------------------------- #
SRC=$1
DST=$2
if [ -z "${ONE_LOCATION}" ]; then
TMCOMMON=/usr/lib/one/mads/tm_common.sh
else
TMCOMMON=$ONE_LOCATION/lib/mads/tm_common.sh
fi
. $TMCOMMON
SRC_PATH=`arg_path $SRC`
log "$1 $2"
case $SRC in
http://*)
log "Downloading $SRC"
exec_and_log "$SSH $DST_HOST $WGET -O $DST_PATH $SRC_PATH"
;;
*)
log "Cloning $SRC"
VM_ID=`echo $DST | $SED -e 's/.*\/\([0-9]\+\)\/images\/.*/\1/'`
cp -r $SRC_PATH $DATASTORE_PATH/one-$VM_ID &>/dev/null
mv $DATASTORE_PATH/one-$VM_ID/*.vmx $DATASTORE_PATH/one-$VM_ID/one-$VM_ID.vmx
;;
esac

View File

@ -1,31 +0,0 @@
#!/bin/bash
# -------------------------------------------------------------------------- #
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
# 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. #
#--------------------------------------------------------------------------- #
if [ -z "${ONE_LOCATION}" ]; then
TMCOMMON=/usr/lib/one/mads/tm_common.sh
else
TMCOMMON=$ONE_LOCATION/lib/mads/tm_common.sh
fi
. $TMCOMMON
# We just need the <vid> bit
VM_ID=`echo $1 | $SED -e 's/.*\/\([0-9]\+\)\/images\/.*/\1/'`
log "Deleting $SRC_PATH"
exec_and_log "rm -rf $DATASTORE_PATH/one-$VM_ID"

View File

@ -1,6 +0,0 @@
CLONE = vmware/tm_clone.sh
LN = dummy/tm_dummy.sh
MKSWAP = dummy/tm_dummy.sh
MKIMAGE = dummy/tm_dummy.sh
DELETE = vmware/tm_delete.sh
MV = dummy/tm_dummy.sh

View File

@ -1,21 +0,0 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
# 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. #
#--------------------------------------------------------------------------- #
# Uncomment the following line to active MAD debug
#ONE_MAD_DEBUG=1
# Local path of the datastore
DATASTORE_PATH=/images/vmware

View File

@ -1,464 +0,0 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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. */
/* -------------------------------------------------------------------------- */
import com.vmware.vim.*;
import com.vmware.apputils.*;
import com.vmware.apputils.vim.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.rmi.RemoteException;
/*
* Used to register a VM preloaded
*/
public class DeployVM
{
String[] args;
String hostName;
// Helpers from VI samples
private static ServiceContent content;
static AppUtil cb = null;
private static VimPortType service;
private String datacenterName = "";
private String datastoreName = "";
private String vmName = "";
private String vmDiskName = "";
private String vid = "";
ParseXML pXML;
// VM configuration objects
VirtualMachineConfigSpec vmConfigSpec;
VirtualMachineConfigInfo vmConfigInfo;
ManagedObjectReference virtualMachine;
com.vmware.vim.ManagedObjectReference hostMor;
public boolean registerVirtualMachine() throws Exception
{
boolean registered = false;
ManagedObjectReference host = null;
ManagedObjectReference dcmor
= cb.getServiceUtil().getDecendentMoRef(null, "Datacenter", getDataCenterName());
com.vmware.vim.ManagedObjectReference vmFolderMor
= (com.vmware.vim.ManagedObjectReference)
cb.getServiceUtil().getDynamicProperty(dcmor,"vmFolder");
// Default Host
com.vmware.vim.ManagedObjectReference hostFolderMor
= (com.vmware.vim.ManagedObjectReference)
cb.getServiceUtil().getDynamicProperty(dcmor,"hostFolder");
ArrayList hostList = (ArrayList)cb.getServiceUtil().getDecendentMoRefs(
hostFolderMor,"HostSystem");
if(hostList.size() < 1)
{
System.out.println("No host found in datacenter to"
+" register the Virtual Machine");
return registered;
}
else
{
boolean hostFound = false;
for(int i=0; i<hostList.size(); i++)
{
com.vmware.vim.ManagedObjectReference [] datastores
= (com.vmware.vim.ManagedObjectReference [])
cb.getServiceUtil().getDynamicProperty(hostMor,"datastore");
for(int j=0; j<datastores.length; j++)
{
com.vmware.vim.DatastoreSummary datastoreSummary
= (com.vmware.vim.DatastoreSummary)
cb.getServiceUtil().getDynamicProperty(datastores[j],"summary");
if(datastoreSummary.getName().equalsIgnoreCase(getDataStoreName()))
{
com.vmware.vim.DatastoreInfo datastoreInfo
= (com.vmware.vim.DatastoreInfo)
cb.getServiceUtil().getDynamicProperty(datastores[j],"info");
host = hostMor;
hostFound = true;
i = hostList.size()+1;
j = datastores.length+1;
}
}
}
if(hostFound)
{
String vmxPath = "[" + getDataStoreName() + "]one-"+getID()+"/one-"+getID()+".vmx";
// Resource Pool
ManagedObjectReference resourcePool
= cb.getServiceUtil().getFirstDecendentMoRef(null, "ResourcePool");
// Registering The Virtual machine
ManagedObjectReference taskmor
= cb.getConnection().getService().registerVM_Task(
vmFolderMor,vmxPath,getVmName(),false,resourcePool,host);
String result = cb.getServiceUtil().waitForTask(taskmor);
if (result.equalsIgnoreCase("Sucess")) // sic
{
registered = true;
}
else
{
System.out.println("Exception registering the VM");
registered = false;
}
return registered;
}
else
{
System.out.println("No host in datacenter got the"
+" specified datastore and free space");
return registered;
}
}
}
/**
* Gets the name of the VM
* @returns name of the VM
*/
private String getVmName()
{
return vmName;
}
/**
* Gets the name of the VMX file and folder
* @returns name of the VMX file and folder
*/
private String getDiskName()
{
return vmDiskName;
}
/**
* Gets the name of the datacenter
* @returns name of the datacenter
*/
private String getDataCenterName()
{
return datacenterName;
}
/**
* Gets the name of the datastore
* @returns name of the datastore
*/
private String getDataStoreName()
{
return datastoreName;
}
/**
* Gets the vid
* @returns vid
*/
private String getID()
{
return vid;
}
public boolean shapeVM() throws Exception
{
virtualMachine
= cb.getServiceUtil().getDecendentMoRef(null, "VirtualMachine", vmName);
vmConfigInfo
= (VirtualMachineConfigInfo)cb.getServiceUtil().getDynamicProperty(
virtualMachine,"config");
vmConfigSpec = new VirtualMachineConfigSpec();
vmConfigSpec.setMemoryMB((long)Integer.parseInt(pXML.getMemory()));
vmConfigSpec.setNumCPUs(Integer.parseInt(pXML.getCPU()));
// DISKs
// TODO finish disk support
// addDisks();
// Network
configureNetwork();
// TODO CD for contextualization
/* if(deviceType.equalsIgnoreCase("cd")) {
System.out.println("Reconfiguring The Virtual Machine For CD Update "
+ cb.get_option("vmname"));
VirtualDeviceConfigSpec cdSpec = getCDDeviceConfigSpec();
if(cdSpec != null) {
VirtualDeviceConfigSpec [] cdSpecArray = {cdSpec};
vmConfigSpec.setDeviceChange(cdSpecArray);
}*/
ManagedObjectReference tmor
= cb.getConnection().getService().reconfigVM_Task(
virtualMachine, vmConfigSpec);
String result = cb.getServiceUtil().waitForTask(tmor);
if(!result.equalsIgnoreCase("sucess"))
{
return false;
}
return true;
}
void configureNetwork()
{
String[][] nics = pXML.getNet();
int nics_toRemove_counter = 0;
if(nics==null)
{
return;
}
if(nics.length==1 && nics[0].equals(""))
{
return;
}
// First, let's find out the number of NICs to be removed
VirtualDevice [] test = vmConfigInfo.getHardware().getDevice();
VirtualDeviceConfigSpec [] nicSpecArray_toRemove = new VirtualDeviceConfigSpec[test.length];
// Let's remove existing NICs
for(int i=0;i<test.length;i++)
{
VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec();
VirtualEthernetCard nic;
nicSpec.setOperation(VirtualDeviceConfigSpecOperation.remove);
try
{
nic = (VirtualEthernetCard)test[i];
}
catch(Exception e)
{
continue;
}
nicSpec.setDevice(nic);
nicSpecArray_toRemove[nics_toRemove_counter++] = nicSpec;
}
VirtualDeviceConfigSpec [] nicSpecArray = new VirtualDeviceConfigSpec[nics_toRemove_counter+
nics.length];
// Let's add specified NICs
for(int i=nics_toRemove_counter;i<(nics.length+nics_toRemove_counter);i++)
{
VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec();
String networkName = nics[i-nics_toRemove_counter][1];
nicSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
VirtualEthernetCard nic = new VirtualPCNet32();
VirtualEthernetCardNetworkBackingInfo nicBacking
= new VirtualEthernetCardNetworkBackingInfo();
nicBacking.setDeviceName(networkName);
nic.setAddressType("manual");
nic.setMacAddress(nics[i-nics_toRemove_counter][0]);
nic.setBacking(nicBacking);
nic.setKey(4);
nicSpec.setDevice(nic);
nicSpecArray[i] = nicSpec;
}
for(int i=0;i<nics_toRemove_counter;i++)
{
nicSpecArray[i] = nicSpecArray_toRemove[i];
}
vmConfigSpec.setDeviceChange(nicSpecArray);
}
public boolean connect()
{
try
{
cb = AppUtil.initialize("DeployVM", null, args);
cb.connect();
// Get reference to host
hostMor = cb.getServiceUtil().getDecendentMoRef(null,"HostSystem",
hostName);
com.vmware.apputils.vim.ServiceConnection sc = cb.getConnection();
content = sc.getServiceContent();
service = sc.getService();
return true;
}
catch(Exception e)
{
return false;
}
}
public void disconnect()
{
try
{
cb.disConnect();
}
catch(Exception e){}
}
DeployVM(String[] arguments, String _hostName, String _vid, ParseXML _pXML, String _datastore, String _datacenter) throws Exception
{
args = new String[arguments.length+2];
for(int i=0;i<arguments.length;i++)
{
args[i] = arguments[i];
}
args[arguments.length] = "--url";
args[arguments.length + 1 ] = "https://" + _hostName + ":443/sdk";
datastoreName = _datastore;
datacenterName = _datacenter;
vmName = _pXML.getName() + "-" + _vid;
vmDiskName = _pXML.getName();
pXML = _pXML;
vid = _vid;
hostName = _hostName;
}
DeployVM(String[] arguments, String _hostName, String _vmName, String _vid, String _datastore, String _datacenter) throws Exception
{
args = new String[arguments.length+2];
for(int i=0;i<arguments.length;i++)
{
args[i] = arguments[i];
}
args[arguments.length] = "--url";
args[arguments.length + 1 ] = "https://" + _hostName + ":443/sdk";
datastoreName = _datastore;
datacenterName = _datacenter;
vmName = _vmName;
vmDiskName = _vmName.substring(0,_vmName.lastIndexOf("-"));
vid = _vid;
hostName = _hostName;
}
/*
void addDisks()
{
String[] disks = pXML.getDisk();
if(disks.length==1 && disks[0].equals(""))
{
return;
}
VirtualDeviceConfigSpec [] vdiskSpecArray = new VirtualDeviceConfigSpec[disks.length];
for(int i=0;i<disks.length;i++)
{
VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec();
VirtualDisk disk = new VirtualDisk();
VirtualDiskFlatVer2BackingInfo diskfileBacking
= new VirtualDiskFlatVer2BackingInfo();
int ckey = 0;
int unitNumber = 0;
VirtualDevice [] test = vmConfigInfo.getHardware().getDevice();
for(int k=0;k<test.length;k++)
{
if(test[k].getDeviceInfo().getLabel().equalsIgnoreCase(
"SCSI Controller 0"))
{
ckey = test[k].getKey();
}
}
unitNumber = test.length + 1;
String fileName = "["+datastoreName+"] "+ getVmName()
+ "/"+ disks[i];
diskfileBacking.setFileName(fileName);
// TODO make this configurable
diskfileBacking.setDiskMode("persistent");
disk.setControllerKey(ckey);
disk.setUnitNumber(unitNumber);
// TODO does this work
disk.setBacking(diskfileBacking);
//int size = 1024 * (Integer.parseInt(cb.get_option("disksize")));
disk.setCapacityInKB(8388608);
disk.setKey(-1);
diskSpec.setOperation(VirtualDeviceConfigSpecOperation.add);
diskSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.create);
diskSpec.setDevice(disk);
vdiskSpecArray[i]=diskSpec;
}
vmConfigSpec.setDeviceChange(vdiskSpecArray);
}*/
}

View File

@ -1,667 +0,0 @@
/*
# -------------------------------------------------------------------------#
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
# 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. #
#--------------------------------------------------------------------------#
*/
import java.io.*;
import java.util.*;
import java.text.*;
import com.vmware.vim.*;
import com.vmware.apputils.*;
import com.vmware.apputils.vim.*;
/************************************
* Manages VMware VMs *
* through the VI API *
************************************/
class OneVmmVmware extends Thread
{
private String[] arguments;
OperationsOverVM oVM;
DeployVM dVM;
boolean debug;
PrintStream stdout;
PrintStream stderr;
public static void main(String[] args)
{
boolean debug_flag;
if (System.getProperty("debug").equals("1"))
{
debug_flag=true;
}
else
{
debug_flag=false;
}
OneVmmVmware omv = new OneVmmVmware(args, debug_flag);
omv.loop();
}
// Constructor
OneVmmVmware(String[] args, boolean _debug)
{
debug = _debug;
arguments = args;
// Get out and err descriptors
stdout = System.out;
stderr = System.err;
// No VMware library output to standard out
// or err. This will be activated when needed
disable_standard_output();
disable_standard_error();
}
// Main loop
void loop()
{
String str = null;
String action = null;
String vid_str = null;
String hostName;
String fileName;
boolean end = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!end)
{
action = null;
vid_str = null;
hostName = null;
fileName = null;
// Read a line and parse it
try
{
str = in.readLine();
}
catch (IOException e)
{
String message = e.getMessage().replace('\n', ' ');
send_message(action + " FAILURE " + vid_str + " " + message);
send_error (action + " FAILURE " + vid_str +
" Action malformed. Reason: " + message);
}
String str_split[] = str.split(" ", 5);
action = str_split[0].toUpperCase();
// Perform the action
if (action.equals("INIT"))
{
init();
}
else if (action.equals("FINALIZE"))
{
finalize_mad();
end = true;
}
else
{
if (action.equals("DEPLOY"))
{
if (str_split.length != 5)
{
send_message(action + " FAILURE " + vid_str);
send_error("FAILURE Wrong number of arguments for DEPLOY action. Number args = [" +
str_split.length + "].");
continue;
}
else
{
vid_str = str_split[1];
hostName = str_split[2];
fileName = str_split[3];
try
{
fileName = fileName.replace("/images", "");
// let's read the XML file and extract needed info
ParseXML pXML = new ParseXML(fileName);
// First, register the VM
dVM = new DeployVM(arguments,
hostName,
vid_str,
pXML,
System.getProperty("datastore"),
System.getProperty("datacenter"));
if(!dVM.connect())
{
throw new Exception("DeployVM: Failed connection to host " + hostName);
}
if(!dVM.registerVirtualMachine())
{
// We will skip this error, it may be pre-registered
}
// Now, proceed with the reconfiguration
if(!dVM.shapeVM())
{
// Will try and deregister VM
try
{
oVM = new OperationsOverVM(arguments,hostName);
String vmName = pXML.getName() + "-" + vid_str;
oVM.deregisterVM(vmName);
}
catch(Exception e){}
throw new Exception("Error reconfiguring VM (" + pXML.getName() + ").");
}
dVM.disconnect();
try
{
oVM = new OperationsOverVM(arguments,hostName);
if(!oVM.connect())
{
throw new Exception("Failed connection to host " + hostName);
}
}
catch(Exception e)
{
oVM.disconnect();
send_message(action + " FAILURE " + vid_str + " " + e.getMessage());
if (!debug)
send_error (action + " FAILURE " + vid_str + " " + e.getMessage());
continue;
}
if(!oVM.powerOn(pXML.getName() + "-" + vid_str))
{
// Will try and deregister VM
try
{
String vmName = pXML.getName() + "-" + vid_str;
oVM.deregisterVM(vmName);
}
catch(Exception e)
{
oVM.disconnect();
}
throw new Exception("Error powering on VM(" + pXML.getName() + ").");
}
send_message("DEPLOY SUCCESS " + vid_str + " " + pXML.getName() + "-" + vid_str);
oVM.disconnect();
continue;
}
catch(Exception e)
{
send_message("DEPLOY FAILURE " + vid_str + " Failed deploying VM in host " +
hostName + ".");
if(debug)
{
send_error("Failed deploying VM " + vid_str + " into " + hostName +
".Reason: "+ e.getMessage() +
"\n---- Debug stack trace ----");
enable_standard_error();
e.printStackTrace();
disable_standard_error();
send_error("---------------------------");
}
else
{ // If debug activated, this will be replicated in send_message
send_error("Failed deploying VM " + vid_str + " into " + hostName +
".Reason:" + e.getMessage());
}
} // catch
} // else if (str_split.length != 4)
} // if (action.equals("DEPLOY"))
if (action.equals("SHUTDOWN") || action.equals("CANCEL"))
{
if (str_split.length < 3 )
{
send_message(action + " FAILURE " + vid_str);
send_error("FAILURE Wrong number of arguments for " + action +
" action. Number args = [" +
str_split.length + "].");
}
else
{
vid_str = str_split[1];
hostName = str_split[2];
String vmName = str_split[3];
try
{
oVM = new OperationsOverVM(arguments,hostName);
if(!oVM.connect())
{
throw new Exception("Failed connection to host " + hostName);
}
}
catch(Exception e)
{
send_message(action + " FAILURE " + vid_str + " " + e.getMessage());
if(!debug)
send_error(action + " FAILURE " + vid_str + " " + e.getMessage());
oVM.disconnect();
continue;
}
if(!oVM.powerOff(vmName))
{
send_message(action + " FAILURE " + vid_str + " Failed shutdown VM in host " +
hostName);
oVM.disconnect();
continue;
}
if(!oVM.deregisterVM(vmName))
{
send_message(action + " FAILURE " + vid_str + " Failed deregistering of " +vmName
+ " in host " + hostName +".");
oVM.disconnect();
continue;
}
else
{
send_message(action + " SUCCESS " + vid_str);
}
}
oVM.disconnect();
continue;
} // if (action.equals("SHUTDOWN or CANCEL"))
if (action.equals("SAVE"))
{
if (str_split.length < 5)
{
send_message(action + " FAILURE " + vid_str);
send_error("FAILURE Wrong number of arguments for SAVE action. Number args = [" +
str_split.length + "].");
continue;
}
else
{
vid_str = str_split[1];
hostName = str_split[2];
String vmName = str_split[3];
String checkpointName = str_split[4];
try
{
oVM = new OperationsOverVM(arguments,hostName);
if(!oVM.connect())
{
throw new Exception("Failed connection to host " + hostName);
}
}
catch(Exception e)
{
send_message(action + " FAILURE " + vid_str + " " + e.getMessage());
if(!debug)
send_error(action + " FAILURE " + vid_str + " " + e.getMessage());
oVM.disconnect();
continue;
}
if(!oVM.save(vmName))
{
send_message(action + " FAILURE " + vid_str + " Failed suspending VM in host " +
hostName);
oVM.disconnect();
continue;
}
if(!oVM.deregisterVM(vmName))
{
send_message(action + " FAILURE " + vid_str + " Failed deregistering of " +vmName
+ " in host " + hostName +".");
oVM.disconnect();
continue;
}
else
{
send_message(action + " SUCCESS " + vid_str);
}
oVM.disconnect();
continue;
}
} // if (action.equals("SAVE"))
if (action.equals("CHECKPOINT"))
{
if (str_split.length < 4)
{
send_message(action + " FAILURE " + vid_str);
send_error("FAILURE Wrong number of arguments for CHECKPOINT action. Number args = [" +
str_split.length + "].");
continue;
}
else
{
vid_str = str_split[1];
hostName = str_split[2];
String vmName = str_split[3];
String checkpointName = str_split[4];
try
{
oVM = new OperationsOverVM(arguments,hostName);
if(!oVM.connect())
{
throw new Exception("Failed connection to host " + hostName);
}
}
catch(Exception e)
{
send_message(action + " FAILURE " + vid_str + " " + e.getMessage());
oVM.disconnect();
continue;
}
if(!oVM.createCheckpoint(vmName))
{
send_message(action + " FAILURE " + vid_str + " Failed suspending VM in host " +
hostName);
oVM.disconnect();
continue;
}
else
{
send_message(action + " SUCCESS " + vid_str);
}
oVM.disconnect();
continue;
}
} // if (action.equals("CHECKPOINT"))
if (action.equals("RESTORE"))
{
if (str_split.length < 4)
{
send_message(action + " FAILURE " + vid_str);
send_error("FAILURE Wrong number of arguments for RESTORE " +
"action. Number args = [" + str_split.length + "].");
continue;
}
else
{
vid_str = str_split[1];
hostName = str_split[2];
String vmName = str_split[3];
boolean result;
try
{
oVM = new OperationsOverVM(arguments,hostName);
dVM = new DeployVM(arguments,
hostName,
vmName,
vid_str,
System.getProperty("datastore"),
System.getProperty("datacenter"));
if(!oVM.connect())
{
throw new Exception("Failed connection to host " + hostName);
}
if(!dVM.connect())
{
throw new Exception("Failed connection to host " + hostName);
}
if(!dVM.registerVirtualMachine())
{
// We will skip this error, it may be pre-registered
}
}
catch(Exception e)
{
send_message(action + " FAILURE " + vid_str + " " + e.getMessage());
if(!debug)
send_error(action + " FAILURE " + vid_str + " " + e.getMessage());
oVM.disconnect();
dVM.disconnect();
continue;
}
if(!oVM.restoreCheckpoint(vmName))
{
send_message(action + " FAILURE " + vid_str + " Failed restoring VM in host " +
hostName);
oVM.disconnect();
dVM.disconnect();
continue;
}
else
{
try
{
if(!oVM.powerOn(vmName))
{
send_message(action + " FAILURE " + vid_str + " Failed restoring VM in host " +
hostName);
}
else
{
send_message(action + " SUCCESS " + vid_str);
oVM.disconnect();
dVM.disconnect();
continue;
}
}
catch(Exception e)
{
send_message(action + " FAILURE " + vid_str + " Failed connection to host " +
hostName +". Reason: " + e.getMessage());
oVM.disconnect();
dVM.disconnect();
continue;
}
}
oVM.disconnect();
dVM.disconnect();
continue;
}
} // if (action.equals("RESTORE"))
if (action.equals("MIGRATE"))
{
send_message(action + " FAILURE " + vid_str + " Action not implemented.");
if(!debug)
send_error(action + " FAILURE " + vid_str + " Action not implemented.");
continue;
} // if (action.equals("MIGRATE"))
if (action.equals("POLL"))
{
if (str_split.length < 4)
{
send_message(action + " FAILURE " + vid_str);
send_error("FAILURE Wrong number of arguments for POLL " +
"action. Number args = [" + str_split.length + "].");
continue;
}
else
{
vid_str = str_split[1];
hostName = str_split[2];
String vmName = str_split[3];
String pollInfo;
try
{
String[] argsWithHost = new String[arguments.length+2];
for(int i=0;i<arguments.length;i++)
{
argsWithHost[i] = arguments[i];
}
argsWithHost[arguments.length] = "--url";
argsWithHost[arguments.length + 1 ] = "https://" + hostName + ":443/sdk";
GetProperty gPHost = new GetProperty(argsWithHost, "HostSystem", hostName);
GetProperty gPVM = new GetProperty(argsWithHost, "VirtualMachine", vmName);
if(!gPHost.connect())
{
throw new Exception();
}
String hostCPUMhz = gPHost.getObjectProperty("summary.hardware.cpuMhz").toString();
gPHost.disconnect();
if(!gPVM.connect())
{
throw new Exception();
}
String powerState =
gPVM.getObjectProperty("runtime.powerState").toString();
if (powerState.equals("poweredOn"))
{
String vmCPUMhz =
gPVM.getObjectProperty("summary.quickStats.overallCpuUsage").toString();
String vmMEMMb =
gPVM.getObjectProperty("summary.quickStats.guestMemoryUsage").toString();
gPVM.disconnect();
int hostCPUMhz_i = Integer.parseInt(hostCPUMhz);
int vmCPUMhz_i = Integer.parseInt(vmCPUMhz);
int vmCPUperc = (vmCPUMhz_i / hostCPUMhz_i) * 100;
pollInfo = "STATE=a USEDMEMORY=" + vmMEMMb + " USEDCPU=" + vmCPUperc;
}
else
{
if (powerState.equals("suspended"))
{
pollInfo = "STATE=p";
}
else // Machine poweredOff
{
pollInfo = "STATE=d";
}
}
}
catch(Exception e)
{
pollInfo = "STATE=-";
}
send_message(action + " SUCCESS " + vid_str + " " + pollInfo);
continue;
}
} // if (action.equals("POLL"))
} // else if (action.equals("FINALIZE"))
} // while(!fin)
} // loop
void init()
{
// Nothing to do here
send_message("INIT SUCCESS");
}
void finalize_mad()
{
send_message("FINALIZE SUCCESS");
}
void enable_standard_output()
{
System.setOut(stdout);
}
void enable_standard_error()
{
System.setErr(stderr);
}
void disable_standard_output()
{
try
{
System.setOut(new PrintStream(new FileOutputStream("/dev/null")));
}
catch(Exception e)
{}
}
void disable_standard_error()
{
try
{
System.setErr(new PrintStream(new FileOutputStream("/dev/null")));
}
catch(Exception e)
{}
}
void send_message(String str)
{
synchronized (System.out)
{
enable_standard_output();
System.out.println(str);
disable_standard_output();
}
if(debug){ send_error(str);}
}
void send_error(String str)
{
Date date = new Date();
Format formatter;
formatter = new SimpleDateFormat("[dd.MM.yyyy HH:mm:ss] ");
synchronized (System.err)
{
enable_standard_error();
System.err.println(formatter.format(date)+str);
disable_standard_error();
}
}
}

View File

@ -1,323 +0,0 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */
/* */
/* 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. */
/* -------------------------------------------------------------------------- */
import com.vmware.vim.*;
import com.vmware.apputils.*;
import com.vmware.apputils.vim.*;
import java.util.*;
import java.io.*;
import java.lang.*;
import java.rmi.RemoteException;
/*
* Used to enforce an operaton over a VM
*/
public class OperationsOverVM
{
String[] args;
// Helpers from VI samples
private static AppUtil cb = null;
ManagedObjectReference virtualMachine;
private String datacenterName = "";
private String datastoreName = "";
private boolean getTaskInfo(ManagedObjectReference taskmor) throws Exception
{
DynamicProperty[] scsiArry = getDynamicProperties(taskmor,"info");
TaskInfo tinfo = ((TaskInfo)(scsiArry[0]).getVal());
String res = cb.getServiceUtil().waitForTask(taskmor);
if(res.equalsIgnoreCase("sucess"))
{
return true;
}
else
{
return false;
}
}
private DynamicProperty[] getDynamicProperties
(ManagedObjectReference mobjRef,String pName )throws Exception
{
ObjectContent[] objContent =
cb.getServiceUtil().getObjectProperties(null, mobjRef,
new String[] { pName });
ObjectContent contentObj = objContent[0];
DynamicProperty[] objArr = contentObj.getPropSet();
return objArr;
}
public boolean powerOn(String vmName) throws Exception
{
ManagedObjectReference taskmor = null;
ManagedObjectReference virtualMachine
= cb.getServiceUtil().getDecendentMoRef(null, "VirtualMachine", vmName);
taskmor = cb.getConnection().getService().powerOnVM_Task(virtualMachine, null);
boolean result = getTaskInfo(taskmor);
return result;
}
public boolean powerOff(String vmName)
{
try
{
ManagedObjectReference taskmor = null;
ManagedObjectReference virtualMachine
= cb.getServiceUtil().getDecendentMoRef(null, "VirtualMachine", vmName);
taskmor = cb.getConnection().getService().powerOffVM_Task(virtualMachine);
boolean result = getTaskInfo(taskmor);
return result;
}
catch(Exception e)
{
System.out.println("Error powering off VirtualMachine [" + vmName + "]. Reason:" + e.getMessage());
return false;
}
}
public boolean deregisterVM(String vmName)
{
try
{
ManagedObjectReference virtualMachine
= cb.getServiceUtil().getDecendentMoRef(null, "VirtualMachine", vmName);
cb.getConnection().getService().unregisterVM(virtualMachine);
return true;
}
catch(InvalidPowerState e)
{
System.out.println("Error deregistering Virtual Machine [" + vmName + "]. Reason: "
+ "[InvalidPowerState] " + e .getMessage());
return false;
}
catch(Exception e)
{
System.out.println("Error deregistering VirtualMachine [" + vmName + "]. Reason:" + e.getMessage());
return false;
}
}
public boolean save(String vmName)
{
// first, create the checkpoint
if(!createCheckpoint(vmName))
{
return false;
}
try
{
ManagedObjectReference taskmor = null;
ManagedObjectReference virtualMachine
= cb.getServiceUtil().getDecendentMoRef(null, "VirtualMachine", vmName);
taskmor = cb.getConnection().getService().suspendVM_Task(virtualMachine);
boolean result = getTaskInfo(taskmor);
return result;
}
catch(Exception e)
{
System.out.println("Error suspending VirtualMachine [" + vmName + "]. Reason:" + e.getMessage());
return false;
}
}
public boolean createCheckpoint(String vmName)
{
try
{
ManagedObjectReference virtualMachine
= cb.getServiceUtil().getDecendentMoRef(null, "VirtualMachine", vmName);
ManagedObjectReference taskMor
= cb.getConnection().getService().createSnapshot_Task(
virtualMachine, vmName + ".checkpoint",
"This checkpoint corresponds to filename = " +
vmName + ".checkpoint", false, false);
String res = cb.getServiceUtil().waitForTask(taskMor);
if(res.equalsIgnoreCase("sucess")) // sic
{
return true;
}
else
{
return false;
}
}
catch(Exception e)
{
System.out.println("Error checkpointing VirtualMachine " + vmName + ". Reason:" + e.getMessage());
return false;
}
}
public boolean restoreCheckpoint(String vmName)
{
try
{
ManagedObjectReference snapmor = null;
ManagedObjectReference virtualMachine
= cb.getServiceUtil().getDecendentMoRef(null, "VirtualMachine", vmName);
ObjectContent[] snaps = cb.getServiceUtil().getObjectProperties(
null, virtualMachine, new String[] { "snapshot" } );
VirtualMachineSnapshotInfo snapInfo = null;
if (snaps != null && snaps.length > 0)
{
ObjectContent snapobj = snaps[0];
DynamicProperty[] snapary = snapobj.getPropSet();
if (snapary != null && snapary.length > 0)
{
snapInfo = ((VirtualMachineSnapshotInfo)(snapary[0]).getVal());
}
}
else
{
throw new Exception("No Snapshots found for VirtualMachine : " + vmName);
}
VirtualMachineSnapshotTree[] snapTree = snapInfo.getRootSnapshotList();
if (snapTree == null)
{
throw new Exception("No Snapshots Tree found for VirtualMachine : " + vmName);
}
snapmor = traverseSnapshotInTree(snapTree, vmName + ".checkpoint");
if (snapmor == null)
{
throw new Exception("No Snapshot named " + vmName + ".checkpoint" +
" found for VirtualMachine : " + vmName);
}
ManagedObjectReference taskMor
= cb.getConnection().getService().revertToSnapshot_Task(snapmor,null);
String res = cb.getServiceUtil().waitForTask(taskMor);
if(!res.equalsIgnoreCase("sucess")) // sic
{
throw new Exception("Unknown problem while creating the snapshot.");
}
return true;
}
catch(Exception e)
{
System.out.println("Error restoring checkpoint of VirtualMachine " + vmName + ". Reason:" + e.getMessage());
return false;
}
}
private ManagedObjectReference traverseSnapshotInTree(
VirtualMachineSnapshotTree[] snapTree,
String checkpointName)
{
ManagedObjectReference snapmor = null;
if (snapTree == null)
{
return snapmor;
}
for (int i = 0; i < snapTree.length && snapmor == null; i++)
{
VirtualMachineSnapshotTree node = snapTree[i];
if ( checkpointName != null && node.getName().equals(checkpointName) )
{
snapmor = node.getSnapshot();
}
else
{
VirtualMachineSnapshotTree[] childTree = node.getChildSnapshotList();
snapmor = traverseSnapshotInTree(childTree, checkpointName);
}
}
return snapmor;
}
public boolean connect()
{
try
{
cb = AppUtil.initialize("OperationsOverVM", null, args);
cb.connect();
return true;
}
catch(Exception e)
{
return false;
}
}
public void disconnect()
{
try
{
cb.disConnect();
}
catch(Exception e){}
}
OperationsOverVM(String[] arguments, String hostName) throws Exception
{
args = new String[arguments.length+2];
for(int i=0;i<arguments.length;i++)
{
args[i] = arguments[i];
}
args[arguments.length] = "--url";
args[arguments.length + 1 ] = "https://" + hostName + ":443/sdk";
datastoreName = System.getProperty("VMWARE_DATASTORE");
datacenterName = System.getProperty("VMWARE_DATACENTER");
}
}

View File

@ -1,174 +0,0 @@
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Parses an XML file containing a VM description created by OpenNebula Core
**/
public class ParseXML
{
private String name = "";
private String cpu = "";
private String[] disk = {""};
private String memory = "";
private String[][] macs;
private String vmID = "";
/**
* Parses the XML file and fills the values
* @param fileName full path of the file to be parsed
**/
ParseXML(String fileName) throws Exception
{
try
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File(fileName));
doc.getDocumentElement().normalize();
NodeList vmNL = doc.getElementsByTagName("TEMPLATE");
if(vmNL.getLength()!=1)
{
throw new Exception("Number of TEMPLATE tags different of 1: [" + vmNL.getLength() + "]");
}
Element vm = (Element)(vmNL.item(0));
// Name
NodeList nameNL = vm.getElementsByTagName("NAME");
if(nameNL.getLength()!=1)
{
throw new Exception("Number of NAME tags different of 1: [" + nameNL.getLength() + "]");
}
name = ((Node)nameNL.item(0)).getFirstChild().getNodeValue().trim();
// VM_ID
NodeList vmIDNL = vm.getElementsByTagName("VMID");
if(vmIDNL.getLength()!=1)
{
throw new Exception("Number of VMID tags different of 1: [" + vmIDNL.getLength() + "]");
}
vmID = ((Node)vmIDNL.item(0)).getFirstChild().getNodeValue().trim();
// CPU
NodeList cpuNL = vm.getElementsByTagName("CPU");
if(cpuNL.getLength()!=1)
{
throw new Exception("Number of CPU tags different of 1: [" + cpuNL.getLength() + "]");
}
cpu = ((Node)cpuNL.item(0)).getFirstChild().getNodeValue().trim();
// Memory
NodeList memoryNL = vm.getElementsByTagName("MEMORY");
if(memoryNL.getLength()!=1)
{
throw new Exception("Number of MEMORY tags different of 1: [" + memoryNL.getLength() + "]");
}
memory = ((Node)memoryNL.item(0)).getFirstChild().getNodeValue().trim();
// DISK
NodeList diskNL = vm.getElementsByTagName("DISK");
if(diskNL.getLength()!=0)
{
disk = new String[diskNL.getLength()];
for(int i=0; i<diskNL.getLength(); i++)
{
NodeList sourceNode = ((Element)diskNL.item(i)).getElementsByTagName("SOURCE");
disk[i] = ((Node)sourceNode.item(0)).getFirstChild().getNodeValue().trim();
}
}
// Network
NodeList nwNL = vm.getElementsByTagName("NIC");
if(nwNL.getLength()!=0)
{
macs = new String[nwNL.getLength()][2];
for(int i=0; i<nwNL.getLength(); i++)
{
NodeList mac = ((Element)nwNL.item(i)).getElementsByTagName("MAC");
macs[i][0] = ((Node)mac.item(0)).getFirstChild().getNodeValue().trim();
NodeList bridge = ((Element)nwNL.item(i)).getElementsByTagName("BRIDGE");
macs[i][1] = ((Node)bridge.item(0)).getFirstChild().getNodeValue().trim();
}
}
}
catch (SAXParseException err)
{
throw new Exception("** Parsing error" + ", line "
+ err.getLineNumber () + ", uri " + err.getSystemId ());
}
}// end ParseXML
/**
* Returns cpu value
* @return cpu number of cpus to be used by the VM
**/
String getCPU()
{
return cpu;
}
/**
* Returns disk value
* @return cpu array with the full local path of disks
**/
String[] getDisk()
{
return disk;
}
/**
* Returns memory value
* @return memory amount of memory in Mb to be used by this VM
**/
String getMemory()
{
return memory;
}
/**
* Returns networks MACs
* @return macs array with the macs of the NICs to be added to this VM
**/
String[][] getNet()
{
return macs;
}
/**
* Returns VM name
* @return name of the VM
**/
String getName()
{
return name;
}
/**
* Returns VM id
* @return ID of the VM
**/
String getVMID()
{
return vmID;
}
}

View File

@ -1,48 +0,0 @@
/*
* Install instructions for VMWare OpenNebula drivers. Please note that these drivers are in an early stage,
* please submit found bugs or doubts to users@opennebula.org mailing list
*/
1. Install OpenNebula in self-contained mode (specifying the -d option in the install.sh)
2. Install the VMWare VI SDK from [1]
3. Configure the VMWare VI SDK following [2]. You should end up with a keystore containing VMWare certificates installed in the <oneadmin> home folder.
4. Install Apache Axis 1.4 [3]
5. Add all jars in $AXISHOME/lib and $SDKHOME/samples/Axis/java/lib/ to <oneadmin> CLASSPATH
6. Go to OpenNebula source code directory and navigate to src/vmm_mad/vmware. Run the install-vmware.sh script.
7. Edit $ONE_LOCATION/etc/oned.conf and enable the tm_dummy TM MAD removing the leading # from each line. Also, add the following two MADs for VMWare:
#-------------------------------------------------------------------------------
# VMWare Information Driver Manager sample configuration
#-------------------------------------------------------------------------------
IM_MAD = [
name = "im_vmware",
executable = "one_im_vmware",
arguments = "--username <esxi_username> --password <esxi_password>",
default = "im_vmware/im_vmware.conf" ]
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# VMWare Virtualization Driver Manager sample configuration
#-------------------------------------------------------------------------------
VM_MAD = [
name = "vmm_vmware",
executable = "one_vmm_vmware",
arguments = "--username <esxi_username> --password <esxi_password>",
default = "vmm_eh/vmm_eh.conf",
type = "xml" ]
#-------------------------------------------------------------------------------
8. Add ESXi hosts using the following drivers:
$ onehost add <esxi_hostname> im_vmware vmm_vmware tm_dummy
9. Create VMWare VM using the VI client. This can be created in an ESXi server and then shared among others using VMFS or (ideally) NFS. Be careful with the name of the datastore where the VMs are residing, at this stage of the VMWare drivers for OpenNebula it only supports "datastore1" for the datastore and "ha-datacenter" for the datacenter. This is hardcoded in the drivers, but also is the default installation for ESXi.
10. Create a VM template using the name used for the VM in the VI client in step 9 as the Name of the OpenNebula VM.
11. Submit using "onevm create"
--
[1] http://www.vmware.com/support/developer/vc-sdk/
[2] http://www.vmware.com/support/developer/vc-sdk/visdk25pubs/visdk25setupguide.pdf
[3] http://ws.apache.org/axis/

View File

@ -1,44 +0,0 @@
#!/bin/bash
if [ -z "${ONE_LOCATION}" ]; then
echo "ONE_LOCATION is not defined. Don't know where to copy, aborting."
exit -1
fi
echo -n "Installing VMWare drivers."
if [ ! -f GetProperty.java ]; then
ln -s ../../im_mad/vmware/GetProperty.java GetProperty.java
fi
javac *.java
cp *class $ONE_LOCATION/lib/mads
cp one_vmm_vmware $ONE_LOCATION/lib/mads
chmod +x $ONE_LOCATION/lib/mads/one_vmm_vmware
echo -n "."
cd ../../im_mad/vmware/
javac *.java
cp *class $ONE_LOCATION/lib/mads
cp one_im_vmware $ONE_LOCATION/lib/mads
chmod +x $ONE_LOCATION/lib/mads/one_im_vmware
cd - &> /dev/null
cd ../../tm_mad/vmware
mkdir -p $ONE_LOCATION/lib/tm_commands/vmware
cp *sh $ONE_LOCATION/lib/tm_commands/vmware
echo -n "."
mkdir -p $ONE_LOCATION/etc/im_vmware
mkdir -p $ONE_LOCATION/etc/vmm_vmware
mkdir -p $ONE_LOCATION/etc/tm_vmware
cp tm_vmware.conf tm_vmwarerc $ONE_LOCATION/etc/tm_vmware
cp ../../vmm_mad/vmware/vmm_vmwarerc $ONE_LOCATION/etc/vmm_vmware
cp ../../im_mad/vmware/im_vmwarerc $ONE_LOCATION/etc/im_vmware
echo "done"

View File

@ -1,60 +0,0 @@
#!/bin/bash
# -------------------------------------------------------------------------- #
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
# 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. #
#--------------------------------------------------------------------------- #
#Setup driver variables
DRIVER_NAME="vmm_vmware"
if [ -z "${ONE_LOCATION}" ]; then
DRIVERRC=/etc/one/${DRIVER_NAME}/${DRIVER_NAME}rc
MADCOMMON=/usr/lib/one/mads/madcommon.sh
VAR_LOCATION=/var/lib/one
else
DRIVERRC=$ONE_LOCATION/etc/${DRIVER_NAME}/${DRIVER_NAME}rc
MADCOMMON=$ONE_LOCATION/lib/mads/madcommon.sh
VAR_LOCATION=$ONE_LOCATION/var
fi
. $MADCOMMON
# Go to VAR_LOCATION
cd $VAR_LOCATION
# Export the vmm_mad specific rc
export_rc_vars $DRIVERRC
LOG_FILE=$DRIVER_NAME
MAD_FILE="OneVmmVmware"
if [ -z "${ONE_LOCATION}" ]; then
MAD_LOG_PATH=/var/log/one/$LOG_FILE.log
else
MAD_LOG_PATH=$ONE_LOCATION/var/$LOG_FILE.log
fi
# Execute the actual MAD
if [ -n "${ONE_MAD_DEBUG}" ]; then
exec nice -n $PRIORITY java -cp $ONE_LOCATION/lib/mads:$CLASSPATH -Ddatastore=$VMWARE_DATASTORE -Ddatacenter=$VMWARE_DATACENTER -Djavax.net.ssl.trustStore=$VMWARE_TRUSTORE -Ddebug=$ONE_MAD_DEBUG -Xmx1024M $MAD_FILE $* 2>> $MAD_LOG_PATH
else
exec nice -n $PRIORITY java -cp $ONE_LOCATION/lib/mads:$CLASSPATH -Ddatastore=$VMWARE_DATASTORE -Ddatacenter=$VMWARE_DATACENTER -Djavax.net.ssl.trustStore=$VMWARE_TRUSTORE -Xmx1024M $MAD_FILE $* 2> /dev/null
fi

View File

@ -1,28 +0,0 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
# 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. #
#--------------------------------------------------------------------------- #
# This must point to a java keystore with appropriate certificates for accessing
# all the ESXi hosts
#VMWARE_TRUSTORE=<path_to_keystore>
# Uncomment the following line to active MAD debug
#ONE_MAD_DEBUG=1
# Datastore name
VMWARE_DATASTORE=datastore1
# Datacenter name
VMWARE_DATACENTER=ha-datacenter