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

Merge branch 'master' into feature-192

This commit is contained in:
Ruben S. Montero 2010-04-07 22:50:40 +02:00
commit e16827443b
26 changed files with 2640 additions and 8 deletions

View File

@ -24,8 +24,8 @@
int HostPool::allocate (
int * oid,
string hostname,
string im_mad_name,
string vmm_mad_name,
string im_mad_name,
string vmm_mad_name,
string tm_mad_name)
{
Host * host;
@ -59,14 +59,14 @@ extern "C"
map<int, string> * discovered_hosts;
string im_mad(values[1]);
int hid;
discovered_hosts = static_cast<map<int, string> *>(_discovered_hosts);
if ( (discovered_hosts == 0) || (num<=0) || (values[0] == 0) )
{
return -1;
}
hid = atoi(values[0]);
im_mad = values[1];
@ -86,13 +86,14 @@ int HostPool::discover(map<int, string> * discovered_hosts)
lock();
sql << "SELECT oid, im_mad FROM "
<< Host::table << " ORDER BY last_mon_time LIMIT 10";
sql << "SELECT oid, im_mad FROM "
<< Host::table << " WHERE state != "
<< Host::DISABLED << " ORDER BY last_mon_time LIMIT 10";
rc = db->exec(sql,discover_cb,(void *) discovered_hosts);
unlock();
return rc;
}

130
src/oca/java/build.sh Executable file
View File

@ -0,0 +1,130 @@
#!/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. #
#--------------------------------------------------------------------------- #
#-------------------------------------------------------------------------------
# DIR DEFINITIONS
#-------------------------------------------------------------------------------
DOC_DIR="./share/doc"
BIN_DIR="./bin"
JAR_DIR="./jar"
LIB_DIR="./lib"
EXA_DIR="./share/examples"
OCA_JAR=$JAR_DIR"/org.opennebula.client.jar"
#-------------------------------------------------------------------------------
# COMMAND LINE PARSING
#-------------------------------------------------------------------------------
usage() {
echo
echo "Usage: build.sh [-d ] [-h] [-s]"
echo
echo "-d: build the documentation"
echo "-s: compile the examples"
echo "-c: clean compilation files"
echo "-h: prints this help"
}
#-------------------------------------------------------------------------------
TEMP_OPT=`getopt -o hsdc -n 'build.sh' -- "$@"`
eval set -- "$TEMP_OPT"
DO_DOC="no"
DO_EXA="no"
DO_CLEAN="no"
while true ; do
case "$1" in
-h) usage; exit 0;;
-d) DO_DOC="yes"; shift ;;
-s) DO_EXA="yes"; shift ;;
-c) DO_CLEAN="yes"; shift ;;
--) shift ; break ;;
*) usage; exit 1 ;;
esac
done
#-------------------------------------------------------------------------------
# BUILD FUNCTIONS
#-------------------------------------------------------------------------------
do_documentation()
{
echo "Generating javadocs..."
rm -rf $DOC_DIR > /dev/null 2>&1
mkdir -p $DOC_DIR
javadoc -quiet -classpath $LIB_DIR"/*" -d $DOC_DIR \
-sourcepath ./src/ \
-subpackages org.opennebula \
-windowtitle 'OpenNebula Cloud API' \
-doctitle 'OpenNebula Cloud API Specification' \
-header '<b>OpenNebula</b><br><font size="-1">Cloud API</font>' \
-bottom 'Visit <a
href="http://opennebula.org/">OpenNebula.org</a><br>Copyright 2002-2010 &copy;
OpenNebula Project Leads (OpenNebula.org).'
}
do_jar()
{
rm -rf $BIN_DIR > /dev/null 2>&1
mkdir -p $BIN_DIR
rm -rf $JAR_DIR > /dev/null 2>&1
mkdir -p $JAR_DIR
echo "Compiling java files into class files..."
javac -d $BIN_DIR -cp $LIB_DIR"/*" `find src -name *.java`
if [ $? -eq 0 ]; then
echo "Packaging class files in a jar..."
jar cf $OCA_JAR -C $BIN_DIR org
fi
}
do_examples()
{
echo "Compiling OpenNebula Cloud API Examples..."
javac -d $EXA_DIR -classpath $OCA_JAR:$LIB_DIR `find share/examples -name *.java`
}
do_clean()
{
rm -rf $BIN_DIR > /dev/null 2>&1
mkdir -p $BIN_DIR
find share/examples -name '*.class' -delete
}
if [ "$DO_CLEAN" = "yes" ] ; then
do_clean
exit 0
fi
do_jar
if [ "$DO_DOC" = "yes" ] ; then
do_documentation
fi
if [ "$DO_EXA" = "yes" ] ; then
do_examples
fi

View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

View File

@ -0,0 +1,5 @@
Apache XML-RPC
Copyright 1999-2009 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,58 @@
/*******************************************************************************
* 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 org.opennebula.client.Client;
public class SessionInit {
public static void main(String[] args)
{
System.out.print("Creating a new OpenNebula session...");
try
{
Client oneClient = new Client();
System.out.println(" ok");
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
System.out.println("Forcing a wrong user/password initialization...");
try
{
// The secret string should be user:password. The url is null, so it
// will be set to default.
Client oneClient = new Client("wrong_password_token",null);
}
catch (Exception e)
{
System.out.println("\t" + e.getMessage());
}
System.out.println("Forcing a wrong url initialization...");
try
{
// The HTTP is misspelled
Client oneClient = new Client(null,"HTP://localhost:2633/RPC2");
}
catch (Exception e)
{
System.out.println("\t" + e.getMessage());
}
}
}

View File

@ -0,0 +1,3 @@
#!/bin/bash
java -cp ../../lib/*:../../jar/*:. SessionInit

View File

@ -0,0 +1,140 @@
/*******************************************************************************
* 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 org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.user.User;
import org.opennebula.client.user.UserPool;
public class UserSample
{
public static void main(String[] args)
{
// Let's try some of the OpenNebula Cloud API functionality.
// First of all, a Client object has to be created.
// Here the client will try to connect to OpenNebula using the default
// options: the auth. file will be assumed to be at $ONE_AUTH, and the
// endpoint will be set to the environment variable $ONE_XMLRPC.
Client oneClient;
try
{
oneClient = new Client();
}
catch (Exception e)
{
System.out.println(e.getMessage());
return;
}
// We will create a user pool and query some information.
// The info method retrieves and saves internally the information
// from OpenNebula.
UserPool userpool = new UserPool(oneClient);
OneResponse rc = userpool.info();
// The response can be an error, in which case we have access to a
// human-readable error message.
if (rc.isError())
{
System.out.println(rc.getErrorMessage());
return;
}
// Let's find out the current state of the users pool
printUserPool(userpool);
// Now we will try to allocate a new user
System.out.println("Allocating new user (javaUser,javaPassword)...");
rc = User.allocate(oneClient, "javaUser", "javaPassword");
if (rc.isError())
{
System.out.println(rc.getErrorMessage());
return;
}
// If the allocation was successful, then the response message contains
// the new user's ID.
int userID = Integer.parseInt( rc.getMessage() );
System.out.println("The allocation request returned this ID: " + userID);
// We can create a representation for the new user, using the returned
// user-ID
User javaUser = new User(userID, oneClient);
// And request its information
rc = javaUser.info();
// Alternatively we could have requested the user's info with the
// static info method:
// rc = User.info(oneClient, userID);
// and processed the xml returned in the message of the OneResponse.
if (rc.isError())
{
System.out.println(rc.getErrorMessage());
return;
}
// This is how the info returned looks like...
System.out.println("Info for " + javaUser.xpath("name") + "...");
System.out.println(rc.getMessage());
// Wait a second... what was that xpath method for?
// Now that we have the user's info loaded, we can use xpath expressions
// without parsing and initializing any xml, as simple as
// String name = javaUser.xpath("name");
// The user pool information is now outdated, so we need to call the
// info method again
userpool.info();
printUserPool(userpool);
// Let's delete this new user, using its ID
System.out.println("Deleting " + javaUser.getName() + "...");
rc = javaUser.delete();
if (rc.isError())
{
System.out.println(rc.getErrorMessage());
return;
}
// Now the pool information is outdated again, it is time to reload it.
userpool.info();
printUserPool(userpool);
}
public static void printUserPool (UserPool up)
{
System.out.println("--------------------------------------------");
System.out.println("Number of users: " + up.getLength());
System.out.println("User ID\t\tName\t\tEnabled");
// You can use the for-each loops with the OpenNebula pools
for( User user : up )
{
String id = user.getId();
String name = user.getName();
String enab = user.xpath("enabled");
System.out.println(id+"\t\t"+name+"\t\t"+enab);
}
System.out.println("--------------------------------------------");
}
}

View File

@ -0,0 +1,3 @@
#!/bin/bash
java -cp ../../lib/*:../../jar/*:. UserSample

View File

@ -0,0 +1,185 @@
/*******************************************************************************
* 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 org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.vm.VirtualMachine;
import org.opennebula.client.vm.VirtualMachinePool;
public class VMachineSample{
public static void main(String[] args)
{
// Let's try some of the OpenNebula Cloud API functionality for VMs.
// First of all, a Client object has to be created.
// Here the client will try to connect to OpenNebula using the default
// options: the auth. file will be assumed to be at $ONE_AUTH, and the
// endpoint will be set to the environment variable $ONE_XMLRPC.
Client oneClient;
try
{
oneClient = new Client();
// We will try to create a new virtual machine. The first thing we
// need is an OpenNebula virtual machine template.
// This VM template is a valid one, but it will probably fail to run
// if we try to deploy it; the path for the image is unlikely to
// exist.
String vmTemplate =
"NAME = vm_from_java CPU = 0.1 MEMORY = 64\n"
+ "DISK = [\n"
+ "\tsource = \"/home/user/vmachines/ttylinux/ttylinux.img\",\n"
+ "\ttarget = \"hda\",\n"
+ "\treadonly = \"no\" ]\n"
+ "# NIC = [ NETWORK = \"Non existing network\" ]\n"
+ "FEATURES = [ acpi=\"no\" ]";
// You can try to uncomment the NIC line, in that case OpenNebula
// won't be able to insert this machine in the database.
System.out.println("Virtual Machine Template:\n" + vmTemplate);
System.out.println();
System.out.print("Trying to allocate the virtual machine... ");
OneResponse rc = VirtualMachine.allocate(oneClient, vmTemplate);
if( rc.isError() )
{
System.out.println( "failed!");
throw new Exception( rc.getErrorMessage() );
}
// The response message is the new VM's ID
int newVMID = Integer.parseInt(rc.getMessage());
System.out.println("ok, ID " + newVMID + ".");
// We can create a representation for the new VM, using the returned
// VM-ID
VirtualMachine vm = new VirtualMachine(newVMID, oneClient);
// Let's hold the VM, so the scheduler won't try to deploy it
System.out.print("Trying to hold the new VM... ");
rc = vm.hold();
if(rc.isError())
{
System.out.println("failed!");
throw new Exception( rc.getErrorMessage() );
}
else
System.out.println("ok.");
// And now we can request its information.
rc = vm.info();
if(rc.isError())
throw new Exception( rc.getErrorMessage() );
System.out.println();
System.out.println(
"This is the information OpenNebula stores for the new VM:");
System.out.println(rc.getMessage() + "\n");
// This VirtualMachine object has some helpers, so we can access its
// attributes easily (remember to load the data first using the info
// method).
System.out.println("The new VM " +
vm.getName() + " has status: " + vm.status());
// And we can also use xpath expressions
System.out.println("The path of the disk is");
System.out.println( "\t" + vm.xpath("template/disk/source") );
// Let's delete the VirtualMachine object.
vm = null;
// The reference is lost, but we can ask OpenNebula about the VM
// again. This time however, we are going to use the VM pool
VirtualMachinePool vmPool = new VirtualMachinePool(oneClient);
// Remember that we have to ask the pool to retrieve the information
// from OpenNebula
rc = vmPool.info();
if(rc.isError())
throw new Exception( rc.getErrorMessage() );
System.out.println(
"\nThese are all the Virtual Machines in the pool:");
for ( VirtualMachine vmachine : vmPool )
{
System.out.println("\tID :" + vmachine.getId() +
", Name :" + vmachine.getName() );
// Check if we have found the VM we are looking for
if ( vmachine.getId().equals( ""+newVMID ) )
{
vm = vmachine;
}
}
// We have also some useful helpers for the actions you can perform
// on a virtual machine, like cancel:
rc = vm.cancel();
System.out.println("\nTrying to cancel the VM " + vm.getId() +
" (should fail)...");
// This is all the information you can get from the OneResponse:
System.out.println("\tOpenNebula response");
System.out.println("\t Error: " + rc.isError());
System.out.println("\t Msg: " + rc.getMessage());
System.out.println("\t ErrMsg: " + rc.getErrorMessage());
rc = vm.finalizeVM();
System.out.println("\nTrying to finalize (delete) the VM " +
vm.getId() + "...");
System.out.println("\tOpenNebula response");
System.out.println("\t Error: " + rc.isError());
System.out.println("\t Msg: " + rc.getMessage());
System.out.println("\t ErrMsg: " + rc.getErrorMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
public static void printVMachinePool (VirtualMachinePool vmPool)
{
System.out.println("--------------------------------------------");
System.out.println("Number of VMs: " + vmPool.getLength());
System.out.println("User ID\t\tName\t\tEnabled");
// You can use the for-each loops with the OpenNebula pools
for( VirtualMachine vm : vmPool )
{
String id = vm.getId();
String name = vm.getName();
String enab = vm.xpath("enabled");
System.out.println(id+"\t\t"+name+"\t\t"+enab);
}
System.out.println("--------------------------------------------");
}
}

View File

@ -0,0 +1,3 @@
#!/bin/bash
java -cp ../../lib/*:../../jar/*:. VMachineSample

View File

@ -0,0 +1,227 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
/**
* This class represents the connection with the core and handles the
* xml-rpc calls.
*
*/
public class Client{
//--------------------------------------------------------------------------
// PUBLIC INTERFACE
//--------------------------------------------------------------------------
/**
* Creates a new xml-rpc client with default options:
* the auth. file will be assumed to be at $ONE_AUTH, and
* the endpoint will be set to $ONE_XMLRPC.
* <br/>
* It is the equivalent of Client(null, null).
*
* @throws Exception if one authorization file cannot be located.
*/
public Client() throws Exception
{
setOneAuth(null);
setOneEndPoint(null);
}
/**
* Creates a new xml-rpc client with specified options.
*
* @param secret A string containing the ONE user:password tuple.
* Can be null
* @param endpoint Where the rpc server is listening, must be something
* like "http://localhost:2633/RPC2". Can be null
* @throws Exception if the authorization options are invalid
*/
public Client(String secret, String endpoint) throws Exception
{
setOneAuth(secret);
setOneEndPoint(endpoint);
}
/**
* Performs an XML-RPC call.
*
* @param action ONE action
* @param args ONE arguments
* @return The server's xml-rpc response encapsulated
*/
public OneResponse call(String action, Object...args)
{
boolean success = false;
String msg = null;
try
{
Object[] params = new Object[args.length + 1];
params[0] = oneAuth;
for(int i=0; i<args.length; i++)
params[i+1] = args[i];
Object[] result = (Object[]) client.execute("one."+action, params);
success = (Boolean) result[0];
// In some cases, the xml-rpc response only has a boolean
// OUT parameter
if(result.length > 1)
{
try
{
msg = (String) result[1];
}
catch (ClassCastException e)
{
// The result may be an Integer
msg = ((Integer) result[1]).toString();
}
}
}
catch (XmlRpcException e)
{
msg = e.getMessage();
}
return new OneResponse(success, msg);
}
//--------------------------------------------------------------------------
// PRIVATE ATTRIBUTES AND METHODS
//--------------------------------------------------------------------------
private String oneAuth;
private String oneEndPoint;
private XmlRpcClient client;
private void setOneAuth(String secret) throws Exception
{
String oneSecret = secret;
try
{
if(oneSecret == null)
{
String oneAuthEnv = System.getenv("ONE_AUTH");
File authFile;
if ( oneAuthEnv != null && oneAuthEnv.length() != 0)
{
authFile = new File(oneAuthEnv);
}
else
{
authFile = new File(System.getenv("HOME")+"/.one/one_auth");
}
oneSecret =
(new BufferedReader(new FileReader(authFile))).readLine();
}
String[] token = oneSecret.split(":");
if(token.length != 2 )
{
throw new Exception("Wrong format for authorization string: "
+ oneSecret + "\nFormat expected is user:password");
}
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] digest = md.digest(token[1].getBytes());
String hash = "";
for(byte aux : digest)
{
int b = aux & 0xff;
if (Integer.toHexString(b).length() == 1)
{
hash += "0";
}
hash += Integer.toHexString(b);
}
oneAuth = token[0] + ":" + hash;
}
catch (FileNotFoundException e)
{
throw new Exception("ONE_AUTH file not present");
}
catch (NoSuchAlgorithmException e)
{
throw new Exception("Error initializing MessageDigest with SHA-1");
}
}
private void setOneEndPoint(String endpoint) throws Exception
{
oneEndPoint = "http://localhost:2633/RPC2";
if(endpoint != null)
{
oneEndPoint = endpoint;
}
else
{
String oneXmlRpcEnv = System.getenv("ONE_XMLRPC");
if ( oneXmlRpcEnv != null && oneXmlRpcEnv.length() != 0 )
{
oneEndPoint = oneXmlRpcEnv;
}
}
XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
try
{
config.setServerURL(new URL(oneEndPoint));
}
catch (MalformedURLException e)
{
throw new Exception("The URL "+oneEndPoint+" is malformed.");
}
client = new XmlRpcClient();
client.setConfig(config);
}
}

View File

@ -0,0 +1,80 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client;
/**
* This class encapsulates OpenNebula's XML-RPC responses. Each response
* carries a boolean indicating if it is an error. It can also contain a
* success message, or an error message.
*/
public class OneResponse{
/**
* Creates a new response.
*
* @param success Indicates if the call was successful, and if
* the message is an error or an information string.
* @param message String containing the response message, or
* the error message.
*/
public OneResponse(boolean success, String message)
{
this.success = success;
this.msg = message;
}
/**
* Returns true if the call resulted in error.
*
* @return True if the call resulted in error.
*/
public boolean isError()
{
return !success;
}
/**
* Returns a string containing the error message, or null
* if the response isn't an error.
*
* @return A string containing the error message, or null
* if the response isn't an error.
*/
public String getErrorMessage()
{
return success ? null : msg;
}
/**
* Returns a string containing the response information, or
* null if the response was an error. Note that the success
* message could be also null.
*
* @return A string containing the response information, or
* null if the response was an error. Note that the success
* message could be also null.
*/
public String getMessage()
{
return success ? msg : null;
}
// ------------------------------------------------------------------------
// PRIVATE ATTRIBUTES
// ------------------------------------------------------------------------
private boolean success;
private String msg;
}

View File

@ -0,0 +1,125 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
/**
* Represents a generic OpenNebula Pool in XML format
* and provides the basic functionality to handle the Pool elements.
*/
public abstract class Pool{
protected Client client;
protected String elementName;
protected NodeList poolElements;
/**
* Sets the Pool attributes.
* @param elementName Name of the PoolElement's xml element
* @param client XML-RPC client which will handle calls
*/
protected Pool(String elementName, Client client)
{
this.elementName = elementName;
this.client = client;
}
/**
* The factory method returns a suitable PoolElement object from
* an XML node. Each Pool must implement the corresponding factory method.
*
* @param node XML Dom node to build the PoolElement from
* @return The corresponding PoolElement
*/
public abstract PoolElement factory(Node node);
/**
* After a *pool.info call, this method builds the internal xml
* representation of the pool.
* @param info The XML-RPC *pool.info response
*/
public void processInfo(OneResponse info)
{
if (info.isError())
{
return;
}
try
{
DocumentBuilder builder;
Document doc;
Element xml;
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse(
new ByteArrayInputStream(info.getMessage().getBytes()));
xml = doc.getDocumentElement();
poolElements = xml.getElementsByTagName(elementName);
}
catch (ParserConfigurationException e) {}
catch (SAXException e) {}
catch (IOException e) {}
}
/**
* Returns the indexth element in the pool. If index is greater than or
* equal to the number of elements in the pool, this returns null.
*
* @param index Index of the element.
* @return The element at the indexth position in the pool, or
* null if that is not a valid index.
*/
public PoolElement item(int index)
{
PoolElement theElement = null;
if (poolElements != null)
{
Node node =poolElements.item(index);
if (node != null)
{
theElement = factory(node);
}
}
return theElement;
}
/**
* The number of elements in the pool.
* @return The number of elements in the pool.
*/
public int getLength()
{
return poolElements == null ? 0 : poolElements.getLength();
}
}

View File

@ -0,0 +1,154 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client;
import java.io.ByteArrayInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
/**
* Represents a generic element of a Pool in
* XML format.
*
*/
public abstract class PoolElement {
protected static XPath xpath;
protected int id;
protected Node xml;
protected Client client;
/**
* Creates a new PoolElement with the specified attributes.
* @param id Id of the element.
* @param client XML-RPC Client.
*/
protected PoolElement(int id, Client client)
{
if(xpath == null)
{
XPathFactory factory = XPathFactory.newInstance();
xpath = factory.newXPath();
}
this.id = id;
this.client = client;
}
/**
* Creates a new PoolElement from the xml provided.
*
* @param client XML-RPC Client.
* @param xmlElement XML representation of the element.
*/
protected PoolElement(Node xmlElement, Client client)
{
if(xpath == null)
{
XPathFactory factory = XPathFactory.newInstance();
xpath = factory.newXPath();
}
this.xml = xmlElement;
this.client = client;
this.id = Integer.parseInt(xpath("id"));
}
/**
* After a *.info call, this method builds the internal xml
* representation of the pool.
* @param info The XML-RPC *.info response
*/
protected void processInfo(OneResponse info)
{
if (info.isError())
{
return;
}
try
{
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(
new ByteArrayInputStream(info.getMessage().getBytes()));
xml = doc.getDocumentElement();
}
catch (Exception e) {}
}
/**
* Returns the element's ID.
* @return the element's ID.
*/
public String getId()
{
return Integer.toString(id);
}
/**
* Returns the element's name.
* @return the element's name.
*/
public String getName()
{
return xpath("name");
}
/**
* Performs an xpath evaluation for the "state" expression.
* @return The value of the STATE element.
*/
public int state()
{
String state = xpath("state");
return state != null ? Integer.parseInt( state ) : -1;
}
/**
* Evaluates an XPath expression and returns the result as a String.
* If the internal xml representation is not built, returns null. The
* subclass method info() must be called before.
*
* @param expression The XPath expression.
* @return The String that is the result of evaluating the
* expression and converting the result to a String. Null if
* the internal xml representation is not built.
*/
public String xpath(String expression)
{
String result = null;
try
{
result = xpath.evaluate(expression.toUpperCase(), xml);
}
catch (XPathExpressionException e) {}
return result;
}
}

View File

@ -0,0 +1,200 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client.host;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.PoolElement;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula host.
* It also offers static XML-RPC call wrappers.
*/
public class Host extends PoolElement{
private static final String METHOD_PREFIX = "host.";
private static final String ALLOCATE = METHOD_PREFIX + "allocate";
private static final String INFO = METHOD_PREFIX + "info";
private static final String DELETE = METHOD_PREFIX + "delete";
private static final String ENABLE = METHOD_PREFIX + "enable";
private static final String[] HOST_STATES =
{"INIT", "MONITORING", "MONITORED", "ERROR", "DISABLED"};
/**
* Creates a new Host representation.
*
* @param id The host id (hid) of the machine.
* @param client XML-RPC Client.
*/
public Host(int id, Client client)
{
super(id, client);
}
/**
* @see PoolElement
*/
protected Host(Node xmlElement, Client client)
{
super(xmlElement, client);
}
// =================================
// Static XML-RPC methods
// =================================
/**
* Allocates a new host in OpenNebula
*
* @param client XML-RPC Client.
* @param hostname Hostname of the machine we want to add
* @param im The name of the information manager (im_mad_name),
* this values are taken from the oned.conf with the tag name IM_MAD (name)
* @param vmm The name of the virtual machine manager mad name
* (vmm_mad_name), this values are taken from the oned.conf with the
* tag name VM_MAD (name)
* @param tm The transfer manager mad name to be used with this host
* @return If successful the message contains the associated
* id generated for this host
*/
public static OneResponse allocate(Client client,
String hostname,
String im,
String vmm,
String tm)
{
return client.call(ALLOCATE, hostname, im, vmm, tm);
}
/**
* Retrieves the information of the given host.
*
* @param client XML-RPC Client.
* @param id The host id (hid) of the target machine.
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public static OneResponse info(Client client, int id)
{
return client.call(INFO, id);
}
/**
* Deletes a host from OpenNebula.
*
* @param client XML-RPC Client.
* @param id The host id (hid) of the target machine.
* @return A encapsulated response.
*/
public static OneResponse delete(Client client, int id)
{
return client.call(DELETE, id);
}
/**
* Enables or disables a given host.
*
* @param client XML-RPC Client.
* @param id The host id (hid) of the target machine.
* @param enable If set true OpenNebula will enable the
* target host, if set false it will disable it.
* @return A encapsulated response.
*/
public static OneResponse enable(Client client, int id, boolean enable)
{
return client.call(ENABLE, id, enable);
}
// =================================
// Instanced object XML-RPC methods
// =================================
/**
* Loads the xml representation of the host.
* The info is also stored internally.
*
* @see Host#info(Client, int)
*/
public OneResponse info()
{
OneResponse response = info(client, id);
super.processInfo(response);
return response;
}
/**
* Deletes the host from OpenNebula.
*
* @see Host#delete(Client, int)
*/
public OneResponse delete()
{
return delete(client, id);
}
/**
* Enables or disables the host.
*
* @see Host#enable(Client, int, boolean)
*/
public OneResponse enable(boolean enable)
{
return enable(client, id, enable);
}
// =================================
// Helpers
// =================================
/**
* Returns the state of the Host.
* <br/>
* The method {@link Host#info()} must be called before.
*
* @return The state of the Host.
*/
public String stateStr()
{
int state = state();
return state != -1 ? HOST_STATES[state()] : null;
}
/**
* Returns the short length string state of the Host.
* <br/>
* The method {@link Host#info()} must be called before.
*
* @return The short length string state of the Host.
*/
public String shortStateStr()
{
String st = stateStr();
if(st == null)
return null;
else if(st.equals("ERROR"))
return "err";
else if (st.equals("DISABLED"))
return "off";
else
return "on";
}
}

View File

@ -0,0 +1,93 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client.host;
import java.util.AbstractList;
import java.util.Iterator;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.Pool;
import org.opennebula.client.PoolElement;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula host pool.
* It also offers static XML-RPC call wrappers.
*/
public class HostPool extends Pool implements Iterable<Host>{
private static final String ELEMENT_NAME = "HOST";
private static final String INFO_METHOD = "hostpool.info";
/**
* Creates a new host pool
* @param client XML-RPC Client.
*/
public HostPool(Client client)
{
super(ELEMENT_NAME, client);
}
@Override
public PoolElement factory(Node node)
{
return new Host(node, client);
}
/**
* Retrieves all the hosts in the pool.
*
* @param client XML-RPC Client.
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public static OneResponse info(Client client)
{
return client.call(INFO_METHOD);
}
/**
* Loads the xml representation of the host pool.
*
* @see HostPool#info(Client)
*/
public OneResponse info()
{
OneResponse response = info(client);
super.processInfo(response);
return response;
}
public Iterator<Host> iterator()
{
AbstractList<Host> ab = new AbstractList<Host>()
{
public int size()
{
return getLength();
}
public Host get(int index)
{
return (Host) item(index);
}
};
return ab.iterator();
}
}

View File

@ -0,0 +1,37 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
</head>
<body bgcolor="white">
<p>
Provides the Java bindings for the OpenNebula Cloud API (OCA).
</p>
<p>
The included classes can be used as simple wrappers for the XML-RPC calls
supported by the OpenNebula core, or as objects that store the information
and provide useful helpers.
</p>
<h2>Requirements</h2>
<p>
Apart from this jar file, you need to add to the project's build-path the
<a href="http://ws.apache.org/xmlrpc/index.html">Apache XML-RPC</a> library.
</p>
<p>
You can download it from Apache's
<a href="http://www.apache.org/dyn/closer.cgi/ws/xmlrpc/">distribution directory</a>.
The jar files you need are xmlrpc-client-*.jar, ws-commons-util-*.jar and xmlrpc-common-*.jar.</p>
<h2>Related Documentation</h2>
<p>
Please visit the <a href="http://opennebula.org">OpenNebula</a> site for general information,
and consult the <a href="http://opennebula.org/doku.php?id=documentation">documentation section</a>
to find up to date references, tutorials, and more.
</p>
<p>
You can learn about the OpenNebula XML-RPC API <a href="http://opennebula.org/doku.php?id=documentation:rel1.4:api">here</a>.
</p>
<!-- Put @see and @since tags down here. -->
</body>
</html>

View File

@ -0,0 +1,128 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client.user;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.PoolElement;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula User.
* It also offers static XML-RPC call wrappers.
*/
public class User extends PoolElement{
private static final String METHOD_PREFIX = "user.";
private static final String ALLOCATE = METHOD_PREFIX + "allocate";
private static final String INFO = METHOD_PREFIX + "info";
private static final String DELETE = METHOD_PREFIX + "delete";
/**
* Creates a new User representation.
*
* @param id The user id (uid).
* @param client XML-RPC Client.
*/
public User(int id, Client client)
{
super(id, client);
}
/**
* @see PoolElement
*/
protected User(Node xmlElement, Client client)
{
super(xmlElement, client);
}
// =================================
// Static XML-RPC methods
// =================================
/**
* Allocates a new user in OpenNebula.
*
* @param client XML-RPC Client.
* @param username Username for the new user.
* @param password Password for the new user
* @return If successful the message contains
* the associated id (int uid) generated for this user.
*/
public static OneResponse allocate(Client client,
String username,
String password)
{
return client.call(ALLOCATE, username, password);
}
/** Retrieves the information of the given user.
*
* @param client XML-RPC Client.
* @param id The user id (uid) for the user to
* retrieve the information from.
* @return if successful the message contains the
* string with the information about the user returned by OpenNebula.
*/
public static OneResponse info(Client client, int id)
{
return client.call(INFO, id);
}
/**
* Deletes a user from OpenNebula.
*
* @param client XML-RPC Client.
* @param id The user id (uid) of the target user we want to delete.
* @return If an error occurs the error message contains the reason.
*/
public static OneResponse delete(Client client, int id)
{
return client.call(DELETE, id);
}
// =================================
// Instanced object XML-RPC methods
// =================================
/**
* Loads the xml representation of the user.
* The info is also stored internally.
*
* @see User#info(Client, int)
*/
public OneResponse info()
{
OneResponse response = info(client, id);
super.processInfo(response);
return response;
}
/**
* Deletes the user from OpenNebula.
*
* @see User#delete(Client, int)
*/
public OneResponse delete()
{
return delete(client, id);
}
}

View File

@ -0,0 +1,81 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client.user;
import java.util.AbstractList;
import java.util.Iterator;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.Pool;
import org.opennebula.client.PoolElement;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula user pool.
* It also offers static XML-RPC call wrappers.
*/
public class UserPool extends Pool implements Iterable<User>{
private static final String ELEMENT_NAME = "USER";
private static final String INFO_METHOD = "userpool.info";
/**
* Creates a new user pool
* @param client XML-RPC Client.
*/
public UserPool(Client client)
{
super(ELEMENT_NAME, client);
}
@Override
public PoolElement factory(Node node)
{
return new User(node, client);
}
/**
* Loads the xml representation of the user pool.
*/
public OneResponse info()
{
OneResponse response = client.call(INFO_METHOD);
super.processInfo(response);
return response;
}
public Iterator<User> iterator()
{
AbstractList<User> ab = new AbstractList<User>()
{
public int size()
{
return getLength();
}
public User get(int index)
{
return (User) item(index);
}
};
return ab.iterator();
}
}

View File

@ -0,0 +1,394 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client.vm;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.PoolElement;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula VM.
* It also offers static XML-RPC call wrappers.
*/
public class VirtualMachine extends PoolElement{
private static final String METHOD_PREFIX = "vm.";
private static final String ALLOCATE = METHOD_PREFIX + "allocate";
private static final String INFO = METHOD_PREFIX + "info";
private static final String DEPLOY = METHOD_PREFIX + "deploy";
private static final String ACTION = METHOD_PREFIX + "action";
private static final String MIGRATE = METHOD_PREFIX + "migrate";
private static final String[] VM_STATES =
{
"INIT",
"PENDING",
"HOLD",
"ACTIVE",
"STOPPED",
"SUSPENDED",
"DONE",
"FAILED" };
private static final String[] SHORT_VM_STATES =
{
"init",
"pend",
"hold",
"actv",
"stop",
"susp",
"done",
"fail" };
private static final String[] LCM_STATE =
{
"LCM_INIT",
"PROLOG",
"BOOT",
"RUNNING",
"MIGRATE",
"SAVE_STOP",
"SAVE_SUSPEND",
"SAVE_MIGRATE",
"PROLOG_MIGRATE",
"PROLOG_RESUME",
"EPILOG_STOP",
"EPILOG",
"SHUTDOWN",
"CANCEL",
"FAILURE",
"DELETE",
"UNKNOWN" };
private static final String[] SHORT_LCM_STATES =
{
null,
"prol",
"boot",
"runn",
"migr",
"save",
"save",
"save",
"migr",
"prol",
"epil",
"epil",
"shut",
"shut",
"fail",
"dele",
"unkn" };
/**
* Creates a new VM representation.
*
* @param id The virtual machine Id (vid).
* @param client XML-RPC Client.
*/
public VirtualMachine(int id, Client client)
{
super(id, client);
}
/**
* @see PoolElement
*/
protected VirtualMachine(Node xmlElement, Client client)
{
super(xmlElement, client);
}
// =================================
// Static XML-RPC methods
// =================================
/**
* Allocates a new VM in OpenNebula.
*
* @param client XML-RPC Client.
* @param description A string containing the template of the vm.
* @return If successful the message contains the associated
* id generated for this VM.
*/
public static OneResponse allocate(Client client, String description)
{
return client.call(ALLOCATE, description);
}
/**
* Retrieves the information of the given VM.
*
* @param client XML-RPC Client.
* @param id The virtual machine id (vid) of the target instance.
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public static OneResponse info(Client client, int id)
{
return client.call(INFO, id);
}
// =================================
// Instanced object XML-RPC methods
// =================================
/**
* Loads the xml representation of the virtual machine.
* The info is also stored internally.
*
* @see VirtualMachine#info(Client, int)
*/
public OneResponse info()
{
OneResponse response = info(client, id);
super.processInfo(response);
return response;
}
/**
* Initiates the instance of the VM on the target host.
*
* @param hostId The host id (hid) of the target host where
* the VM will be instantiated.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse deploy(int hostId)
{
return client.call(DEPLOY, id, hostId);
}
/**
* Submits an action to be performed on the virtual machine.
* <br/>
* It is recommended to use the helper methods instead:
* <ul>
* <li>{@link VirtualMachine#shutdown()}</li>
* <li>{@link VirtualMachine#cancel()}</li>
* <li>{@link VirtualMachine#hold()}</li>
* <li>{@link VirtualMachine#release()}</li>
* <li>{@link VirtualMachine#stop()}</li>
* <li>{@link VirtualMachine#suspend()}</li>
* <li>{@link VirtualMachine#resume()}</li>
* <li>{@link VirtualMachine#finalizeVM()}</li>
* <li>{@link VirtualMachine#restart()}</li>
* </ul>
*
* @param action The action name to be performed, can be:<br/>
* "shutdown", "hold", "release", "stop", "cancel", "suspend",
* "resume", "restart", "finalize".
* @return If an error occurs the error message contains the reason.
*/
protected OneResponse action(String action)
{
return client.call(ACTION, action, id);
}
/**
* Migrates the virtual machine to the target host (hid).
*
* @param hostId The target host id (hid) where we want to migrate
* the vm.
* @param live If true we are indicating that we want livemigration,
* otherwise false.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse migrate(int hostId, boolean live)
{
return client.call(MIGRATE, id, hostId, live);
}
// =================================
// Helpers
// =================================
/**
* Shuts down the already deployed VM.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse shutdown()
{
return action("shutdown");
}
/**
* Cancels the running VM.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse cancel()
{
return action("cancel");
}
/**
* Sets the VM to hold state. The VM will not be scheduled until it is
* released.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse hold()
{
return action("hold");
}
/**
* Releases a virtual machine from hold state.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse release()
{
return action("release");
}
/**
* Stops the virtual machine. The virtual machine state is transferred back
* to OpenNebula for a possible reschedule.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse stop()
{
return action("stop");
}
/**
* Suspends the virtual machine. The virtual machine state is left in the
* cluster node for resuming.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse suspend()
{
return action("suspend");
}
/**
* Resumes the execution of a saved VM.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse resume()
{
return action("resume");
}
/**
* Deletes the VM from the pool and database.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse finalizeVM()
{
return action("finalize");
}
/**
* Resubmits the virtual machine after failure.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse restart()
{
return action("shutdown");
}
/**
* Migrates the virtual machine to the target host (hid).
* <br/>
* It does the same as {@link VirtualMachine#migrate(int, boolean)}
* with live set to false.
*
* @param hostId The target host id (hid) where we want to migrate
* the vm.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse migrate(int hostId)
{
return migrate(hostId, false);
}
/**
* Performs a live migration of the virtual machine to the
* target host (hid).
* <br/>
* It does the same as {@link VirtualMachine#migrate(int, boolean)}
* with live set to true.
*
* @param hostId The target host id (hid) where we want to migrate
* the vm.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse liveMigrate(int hostId)
{
return migrate(hostId, true);
}
public int state()
{
return super.state();
}
/**
* Returns the VM state of the VirtualMachine (string value).
* @return The VM state of the VirtualMachine (string value).
*/
public String stateStr()
{
int state = state();
return state != -1 ? VM_STATES[state()] : null;
}
/**
* Returns the LCM state of the VirtualMachine (numeric value).
* @return The LCM state of the VirtualMachine (numeric value).
*/
public int lcmState()
{
String state = xpath("LCM_STATE");
return state != null ? Integer.parseInt(state) : -1;
}
/**
* Returns the LCM state of the VirtualMachine (string value).
* @return The LCM state of the VirtualMachine (string value).
*/
public String lcmStateStr()
{
int state = lcmState();
return state != -1 ? LCM_STATE[state] : null;
}
/**
* Returns the short status string for the VirtualMachine.
* @return The short status string for the VirtualMachine.
*/
public String status()
{
int state = state();
String shortStateStr = null;
if(state != -1)
{
shortStateStr = SHORT_VM_STATES[state];
if(shortStateStr.equals("actv"))
{
int lcmState = lcmState();
if(lcmState != -1)
shortStateStr = SHORT_LCM_STATES[lcmState];
}
}
return shortStateStr;
}
}

View File

@ -0,0 +1,129 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client.vm;
import java.util.AbstractList;
import java.util.Iterator;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.Pool;
import org.opennebula.client.PoolElement;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula VM pool.
* It also offers static XML-RPC call wrappers.
*/
public class VirtualMachinePool extends Pool implements Iterable<VirtualMachine>{
private static final String ELEMENT_NAME = "VM";
private static final String INFO_METHOD = "vmpool.info";
private int filter;
/**
* Creates a new VM pool with the default filter flag value
* set to 0 (VMs belonging to user with UID 0)
*
* @param client XML-RPC Client.
*
* @see VirtualMachinePool#VirtualMachinePool(Client, int)
*/
public VirtualMachinePool(Client client)
{
super(ELEMENT_NAME, client);
this.filter = 0;
}
/**
* Creates a new VM pool.
*
* @param client XML-RPC Client.
* @param filter Filter flag used by default in the method
* {@link VirtualMachinePool#info()}. Possible values:
* <ul>
* <li><= -2: All VMs</li>
* <li>-1: Connected user's VMs</li>
* <li>>= 0: UID User's VMs</li>
* </ul>
*/
public VirtualMachinePool(Client client, int filter)
{
super(ELEMENT_NAME, client);
this.filter = filter;
}
@Override
public PoolElement factory(Node node)
{
return new VirtualMachine(node, client);
}
/**
* Retrieves all or part of the VMs in the pool.
*
* @param client XML-RPC Client.
* @param filter Filter flag. Possible values:
* <ul>
* <li><= -2: All VMs</li>
* <li>-1: Connected user's VMs</li>
* <li>>= 0: UID User's VMs</li>
* </ul>
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public static OneResponse info(Client client, int filter)
{
return client.call(INFO_METHOD, filter);
}
/**
* Loads the xml representation of all or part of the
* VMs in the pool. The filter used is the one set in
* the constructor.
*
* @see VirtualMachinePool#info(Client, int)
*
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public OneResponse info()
{
OneResponse response = info(client, filter);
super.processInfo(response);
return response;
}
public Iterator<VirtualMachine> iterator()
{
AbstractList<VirtualMachine> ab = new AbstractList<VirtualMachine>()
{
public int size()
{
return getLength();
}
public VirtualMachine get(int index)
{
return (VirtualMachine) item(index);
}
};
return ab.iterator();
}
}

View File

@ -0,0 +1,126 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client.vnet;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.PoolElement;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula virtual network.
* It also offers static XML-RPC call wrappers.
*/
public class VirtualNetwork extends PoolElement{
private static final String METHOD_PREFIX = "vn.";
private static final String ALLOCATE = METHOD_PREFIX + "allocate";
private static final String INFO = METHOD_PREFIX + "info";
private static final String DELETE = METHOD_PREFIX + "delete";
/**
* Creates a new virtual network representation.
*
* @param id The virtual network id (nid) .
* @param client XML-RPC Client.
*/
public VirtualNetwork(int id, Client client)
{
super(id, client);
}
/**
* @see PoolElement
*/
protected VirtualNetwork(Node xmlElement, Client client)
{
super(xmlElement, client);
}
// =================================
// Static XML-RPC methods
// =================================
/**
* Allocates a new virtual network in OpenNebula.
*
* @param client XML-RPC Client.
* @param description A string containing the template
* of the virtual network.
* @return If successful the message contains the associated
* id generated for this virtual network.
*/
public static OneResponse allocate(Client client, String description)
{
return client.call(ALLOCATE, description);
}
/**
* Retrieves the information of the given virtual network
*
* @param client XML-RPC Client.
* @param id the virtual network id (nid) for the network to
* retrieve the information from.
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public static OneResponse info(Client client, int id)
{
return client.call(INFO, id);
}
/**
* Deletes a network from OpenNebula.
*
* @param client XML-RPC Client.
* @param id The virtual network id (nid) of the target network.
* @return A encapsulated response.
*/
public static OneResponse delete(Client client, int id)
{
return client.call(DELETE, id);
}
// =================================
// Instanced object XML-RPC methods
// =================================
/**
* Loads the xml representation of the virtual network.
* The info is also stored internally.
*
* @see VirtualNetwork#info(Client, int)
*/
public OneResponse info()
{
OneResponse response = info(client, id);
super.processInfo(response);
return response;
}
/**
* Deletes the network from OpenNebula.
*
* @return A encapsulated response.
*/
public OneResponse delete()
{
return delete(client, id);
}
}

View File

@ -0,0 +1,128 @@
/*******************************************************************************
* 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.
******************************************************************************/
package org.opennebula.client.vnet;
import java.util.AbstractList;
import java.util.Iterator;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.Pool;
import org.opennebula.client.PoolElement;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula Virtual Network pool.
* It also offers static XML-RPC call wrappers.
*/
public class VirtualNetworkPool extends Pool implements Iterable<VirtualNetwork>{
private static final String ELEMENT_NAME = "VNET";
private static final String INFO_METHOD = "vnpool.info";
private int filter;
/**
* Creates a new VN pool with the default filter flag value
* set to 0 (VNs belonging to user with UID 0)
*
* @param client XML-RPC Client.
*
* @see VirtualNetworkPool#VirtualNetworkPool(Client, int)
*/
public VirtualNetworkPool(Client client)
{
super(ELEMENT_NAME, client);
this.filter = 0;
}
/**
* Creates a new VN pool.
*
* @param client XML-RPC Client.
* @param filter Filter flag used by default in the method
* {@link VirtualNetworkPool#info()}. Possible values:
* <ul>
* <li><= -2: All VNs</li>
* <li>-1: Connected user's VNs</li>
* <li>>= 0: UID User's VNs</li>
* </ul>
*/
public VirtualNetworkPool(Client client, int filter)
{
super(ELEMENT_NAME, client);
this.filter = filter;
}
@Override
public PoolElement factory(Node node)
{
return new VirtualNetwork(node, client);
}
/**
* Retrieves all or part of the VNs in the pool.
*
* @param client XML-RPC Client.
* @param filter Filter flag. Possible values:
* <ul>
* <li><= -2: All VNs</li>
* <li>-1: Connected user's VNs</li>
* <li>>= 0: UID User's VNs</li>
* </ul>
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public static OneResponse info(Client client, int filter)
{
return client.call(INFO_METHOD, filter);
}
/**
* Loads the xml representation of all or part of the
* VNs in the pool. The filter used is the one set in
* the constructor.
*
* @see VirtualNetworkPool#info(Client, int)
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public OneResponse info()
{
OneResponse response = info(client, filter);
super.processInfo(response);
return response;
}
public Iterator<VirtualNetwork> iterator()
{
AbstractList<VirtualNetwork> ab = new AbstractList<VirtualNetwork>()
{
public int size()
{
return getLength();
}
public VirtualNetwork get(int index)
{
return (VirtualNetwork) item(index);
}
};
return ab.iterator();
}
}