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

Merge branch 'one-2.0'

Conflicts:
	install.sh
	src/im_mad/im_sh/one_im_sh
	src/vmm_mad/ssh/one_vmm_ssh
	src/vmm_mad/ssh/vmm_sshrc
This commit is contained in:
Ruben S. Montero 2010-10-22 17:31:31 +02:00
commit 057f18bf80
187 changed files with 4742 additions and 3238 deletions

10
NOTICE
View File

@ -3,16 +3,18 @@ Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)
-----------------------------------------
You can find more information about the project, release notes and
documentation at www.OpenNebula.org
documentation at www.OpenNebula.org
AUTHORS
- Ruben Santiago Montero (rubensm@dacya.ucm.es)
- Ignacio Martín Llorente (llorente@dacya.ucm.es)
- Ignacio Martin Llorente (llorente@dacya.ucm.es)
ACKNOWLEDGEMENTS
The following people have contributed to the development of the technology
- Javier Fontán Muiños (jfontan@fdi.ucm.es)
- Constantino Vázquez Blanco (tinova@fdi.ucm.es)
- Javier Fontan Muiños (jfontan@fdi.ucm.es)
- Constantino Vazquez Blanco (tinova@fdi.ucm.es)
- Jaime Melis Bayo (j.melis@fdi.ucm.es)
- Carlos Martin Sanchez (cmartins@fdi.ucm.es)
- Daniel Molina Aranda (danmolin@pdi.ucm.es)

140
README Normal file
View File

@ -0,0 +1,140 @@
OpenNebula - The OpenSource Toolkit for Cloud Computing
## DESCRIPTION
OpenNebula is an open-source project aimed at building the industry standard
open source cloud computing tool to manage the complexity and heterogeneity of
distributed data center infrastructures.
Complete documentation can be found at
http://opennebula.org/documentation:rel2.0
## INSTALLATION
### REQUISITES
This machine will act as the OpenNebula server and therefore needs to have
installed the following software:
* **ruby** >= 1.8.5
* **sqlite3** >= 3.5.2
* **xmlrpc-c** >= 1.06
* **openssl** >= 0.9
* **ssh**
* **sqlite3-ruby** gem
Additionally, to build OpenNebula from source you need:
* Development versions of the **sqlite3**, **xmlrpc-c** and **openssl**
packages, if your distribution does not install them with the libraries.
* **scons** >= 0.97
* **g++** >= 4
* **flex** >= 2.5 (optional, only needed to rebuild the parsers)
* **bison** >= 2.3 (optional, only needed to rebuild the parsers)
* **libxml2-dev**
### OPTIONAL PACKAGES
These packages are not needed to run or build OpenNebula. They improve the
performance of the user-land libraries and tools of OpenNebula, nor the core
system. You will probably experiment a more responsive CLI.
First install rubygems and ruby development libraries
* **ruby-dev**
* **rubygems**
* **rake**
* **make**
Then install the following packages:
* **ruby xmlparser**, some distributions include a binary package for this
(**libxml-parser-ruby1.8**). If it is not available in your distribution
install expat libraries with its development files and install xmlparser
using gem:
$ sudo gem install xmlparser --no-ri --no-rdoc
Note the extra parameters to gem install. Some versions of xmlparser have
problems building the documentation and we can use it without documentation
installed.
* **ruby nokogiri**, to install this gem you will need **libxml2** and
**libxslt** libraries and their development versions. The we can install
nokogiri library:
$ sudo gem install nokogiri --no-ri --no-rdoc
### BUILDING
Compilation is done using **scons** command:
$ scons [OPTION=VALUE]
The argument expression *[OPTIONAL]* is used to set non-default values for:
OPTION VALUE
sqlite_db path-to-sqlite-install
sqlite no if you don't want to build sqlite support
mysql yes if you want to build mysql support
xmlrpc path-to-xmlrpc-install
parsers yes if you want to rebuild flex/bison files
### INSTALLATION
* OpenNebula can be installed in two modes: system-wide, or in self-contained
directory. In either case, you do not need to run OpenNebula as root. These
options can be specified when running the install script:
$ ./install.sh install_options
where **install_options** can be one or more of:
OPTION VALUE
-u user that will run OpenNebula, defaults to user executing
install.sh
-g group of the user that will run OpenNebula, defaults to user
executing install.sh
-k keep current configuration files, useful when upgrading
-d target installation directory. If defined, it will specified
the path for the self-contained install. If not defined, the
installation will be performed system wide
-r remove Opennebula, only useful if -d was not specified,
otherwise rm -rf $ONE_LOCATION would do the job
-h prints installer help
## CONFIGURATION
Information on how to configure OpenNebula is located at http://opennebula.org/documentation:rel2.0
## CONTACT
OpenNebula web page: http://opennebula.org
Development and issue tracking: http://dev.opennebula.org
Support mailing list: http://opennebula.org/support:support
## LICENSE
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.

View File

@ -81,7 +81,7 @@ main_env.Append(CPPFLAGS=[
])
# Linking flags
main_env.Append(LINKFLAGS=["-g"])
main_env.Append(LINKFLAGS=['-g', '-pthread'])
#######################
# EXTRA CONFIGURATION #

View File

@ -51,7 +51,7 @@ public:
Hook(const string &_name,
const string &_cmd,
const string &_args,
HookType _ht,
int _ht,
bool _remote):
name(_name), cmd(_cmd), args(_args), hook_type(_ht), remote(_remote){};
@ -63,7 +63,7 @@ public:
/**
* Returns the hook_type
*/
HookType type() const
int type() const
{
return hook_type;
}
@ -93,7 +93,7 @@ protected:
/**
* The Hook Type
*/
HookType hook_type;
int hook_type;
/**
* True if the command is to be executed remotely

View File

@ -1,18 +1,18 @@
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* 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. */
/* -------------------------------------------------------------------------- */
/* */
/* 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. */
/* -------------------------------------------------------------------------- */
#ifndef LIBVIRT_DRIVER_H_
#define LIBVIRT_DRIVER_H_
@ -41,9 +41,31 @@ public:
private:
int deployment_description(
const VirtualMachine * vm,
const VirtualMachine * vm,
const string& file_name) const
{
int rc = -1;
if (emulator == "kvm")
{
rc = deployment_description_kvm(vm,file_name);
}
else if (emulator == "vmware")
{
rc = deployment_description_vmware(vm,file_name);
}
return rc;
}
int deployment_description_kvm(
const VirtualMachine * vm,
const string& file_name) const;
int deployment_description_vmware(
const VirtualMachine * vm,
const string& file_name) const;
const string emulator;
};

View File

@ -68,11 +68,12 @@ protected:
{
string str;
const char * cstr;
size_t retval;
str = os.str();
cstr = str.c_str();
::write(nebula_mad_pipe, cstr, str.size());
retval = ::write(nebula_mad_pipe, cstr, str.size());
};
/**

View File

@ -203,7 +203,7 @@ public:
static string version()
{
return "OpenNebula 1.9.80";
return "OpenNebula 2.0.0";
};
void start();

View File

@ -983,6 +983,27 @@ private:
/* ---------------------------------------------------------------------- */
class UserInfo: public xmlrpc_c::method
{
public:
UserInfo(UserPool * _upool):upool(_upool)
{
_signature="A:si";
_help="Returns the information for a user";
};
~UserInfo(){};
void execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retvalP);
private:
UserPool * upool;
};
/* ---------------------------------------------------------------------- */
class UserPoolInfo: public xmlrpc_c::method
{
public:

View File

@ -68,7 +68,7 @@ protected:
const string& cmd,
const string& args,
bool remote):
Hook(name, cmd, args, Hook::UPDATE, remote){};
Hook(name, cmd, args, Hook::UPDATE | Hook::ALLOCATE, remote){};
virtual ~VirtualMachineStateMapHook(){};

View File

@ -36,6 +36,8 @@
#include "PoolSQL.h"
#include "Nebula.h"
#include "test/one_test_common.h"
// Use this macro in sub-classes to add all the tests defined here
#define ALL_POOLTEST_CPPUNIT_TESTS() \
CPPUNIT_TEST (oid_assignment); \
@ -339,6 +341,9 @@ public:
NebulaLog::log("Test", Log::INFO, "Test started");
CppUnit::TextUi::TestRunner runner;
SETUP_XML_WRITER(runner, "output.xml")
runner.addTest( suite );
if (sqlite_flag)
@ -356,6 +361,8 @@ public:
runner.run();
END_XML_WRITER
if (!log_flag)
remove("test.log");

View File

@ -0,0 +1,12 @@
#include <cppunit/XmlOutputter.h>
#define SETUP_XML_WRITER(runner, output) \
ofstream outputFile(output); \
CppUnit::XmlOutputter* outputter = \
new CppUnit::XmlOutputter(&runner.result(), outputFile); \
\
runner.setOutputter(outputter);
#define END_XML_WRITER outputFile.close();

View File

@ -100,11 +100,13 @@ if [ -z "$ROOT" ] ; then
LOCK_LOCATION="/var/lock/one"
INCLUDE_LOCATION="/usr/include"
SHARE_LOCATION="/usr/share/one"
MAN_LOCATION="/usr/share/man/man8"
if [ "$CLIENT" = "no" ]; then
MAKE_DIRS="$BIN_LOCATION $LIB_LOCATION $ETC_LOCATION $VAR_LOCATION \
$INCLUDE_LOCATION $SHARE_LOCATION \
$LOG_LOCATION $RUN_LOCATION $LOCK_LOCATION $IMAGES_LOCATION"
$LOG_LOCATION $RUN_LOCATION $LOCK_LOCATION \
$IMAGES_LOCATION $MAN_LOCATION"
DELETE_DIRS="$LIB_LOCATION $ETC_LOCATION $LOG_LOCATION $VAR_LOCATION \
$RUN_LOCATION $SHARE_DIRS"
@ -126,10 +128,12 @@ else
IMAGES_LOCATION="$VAR_LOCATION/images"
INCLUDE_LOCATION="$ROOT/include"
SHARE_LOCATION="$ROOT/share"
MAN_LOCATION="$ROOT/share/man/man8"
if [ "$CLIENT" = "no" ]; then
MAKE_DIRS="$BIN_LOCATION $LIB_LOCATION $ETC_LOCATION $VAR_LOCATION \
$INCLUDE_LOCATION $SHARE_LOCATION $IMAGES_LOCATION"
$INCLUDE_LOCATION $SHARE_LOCATION $IMAGES_LOCATION \
$MAN_LOCATION"
DELETE_DIRS="$MAKE_DIRS"
@ -151,6 +155,7 @@ ETC_DIRS="$ETC_LOCATION/im_kvm \
$ETC_LOCATION/im_xen \
$ETC_LOCATION/im_ec2 \
$ETC_LOCATION/vmm_ec2 \
$ETC_LOCATION/vmm_ssh \
$ETC_LOCATION/vmm_sh \
$ETC_LOCATION/tm_nfs \
$ETC_LOCATION/tm_ssh \
@ -163,7 +168,6 @@ ETC_DIRS="$ETC_LOCATION/im_kvm \
LIB_DIRS="$LIB_LOCATION/remotes \
$LIB_LOCATION/remotes/im \
$LIB_LOCATION/remotes/im/common.d \
$LIB_LOCATION/remotes/im/kvm.d \
$LIB_LOCATION/remotes/im/xen.d \
$LIB_LOCATION/remotes/vmm/xen \
@ -211,24 +215,24 @@ INSTALL_FILES[3]="RUBY_LIB_FILES:$LIB_LOCATION/ruby"
INSTALL_FILES[4]="RUBY_OPENNEBULA_LIB_FILES:$LIB_LOCATION/ruby/OpenNebula"
INSTALL_FILES[5]="MADS_LIB_FILES:$LIB_LOCATION/mads"
INSTALL_FILES[6]="IM_PROBES_FILES:$LIB_LOCATION/remotes/im"
INSTALL_FILES[7]="IM_PROBES_COMMON_FILES:$LIB_LOCATION/remotes/im/common.d"
INSTALL_FILES[8]="IM_PROBES_KVM_FILES:$LIB_LOCATION/remotes/im/kvm.d"
INSTALL_FILES[9]="IM_PROBES_XEN_FILES:$LIB_LOCATION/remotes/im/xen.d"
INSTALL_FILES[10]="VMM_SH_KVM_SCRIPTS:$LIB_LOCATION/remotes/vmm/kvm"
INSTALL_FILES[11]="VMM_SH_XEN_SCRIPTS:$LIB_LOCATION/remotes/vmm/xen"
INSTALL_FILES[12]="NFS_TM_COMMANDS_LIB_FILES:$LIB_LOCATION/tm_commands/nfs"
INSTALL_FILES[13]="SSH_TM_COMMANDS_LIB_FILES:$LIB_LOCATION/tm_commands/ssh"
INSTALL_FILES[14]="DUMMY_TM_COMMANDS_LIB_FILES:$LIB_LOCATION/tm_commands/dummy"
INSTALL_FILES[15]="LVM_TM_COMMANDS_LIB_FILES:$LIB_LOCATION/tm_commands/lvm"
INSTALL_FILES[16]="EXAMPLE_SHARE_FILES:$SHARE_LOCATION/examples"
INSTALL_FILES[17]="TM_EXAMPLE_SHARE_FILES:$SHARE_LOCATION/examples/tm"
INSTALL_FILES[18]="HOOK_SHARE_FILES:$SHARE_LOCATION/hooks"
INSTALL_FILES[19]="COMMON_CLOUD_LIB_FILES:$LIB_LOCATION/ruby/cloud"
INSTALL_FILES[20]="ECO_LIB_FILES:$LIB_LOCATION/ruby/cloud/econe"
INSTALL_FILES[21]="ECO_LIB_VIEW_FILES:$LIB_LOCATION/ruby/cloud/econe/views"
INSTALL_FILES[22]="ECO_BIN_FILES:$BIN_LOCATION"
INSTALL_FILES[23]="OCCI_LIB_FILES:$LIB_LOCATION/ruby/cloud/occi"
INSTALL_FILES[24]="OCCI_BIN_FILES:$BIN_LOCATION"
INSTALL_FILES[7]="IM_PROBES_KVM_FILES:$LIB_LOCATION/remotes/im/kvm.d"
INSTALL_FILES[8]="IM_PROBES_XEN_FILES:$LIB_LOCATION/remotes/im/xen.d"
INSTALL_FILES[9]="VMM_SSH_KVM_SCRIPTS:$LIB_LOCATION/remotes/vmm/kvm"
INSTALL_FILES[10]="VMM_SSH_XEN_SCRIPTS:$LIB_LOCATION/remotes/vmm/xen"
INSTALL_FILES[11]="NFS_TM_COMMANDS_LIB_FILES:$LIB_LOCATION/tm_commands/nfs"
INSTALL_FILES[12]="SSH_TM_COMMANDS_LIB_FILES:$LIB_LOCATION/tm_commands/ssh"
INSTALL_FILES[13]="DUMMY_TM_COMMANDS_LIB_FILES:$LIB_LOCATION/tm_commands/dummy"
INSTALL_FILES[14]="LVM_TM_COMMANDS_LIB_FILES:$LIB_LOCATION/tm_commands/lvm"
INSTALL_FILES[15]="EXAMPLE_SHARE_FILES:$SHARE_LOCATION/examples"
INSTALL_FILES[16]="TM_EXAMPLE_SHARE_FILES:$SHARE_LOCATION/examples/tm"
INSTALL_FILES[17]="HOOK_SHARE_FILES:$SHARE_LOCATION/hooks"
INSTALL_FILES[18]="COMMON_CLOUD_LIB_FILES:$LIB_LOCATION/ruby/cloud"
INSTALL_FILES[19]="ECO_LIB_FILES:$LIB_LOCATION/ruby/cloud/econe"
INSTALL_FILES[20]="ECO_LIB_VIEW_FILES:$LIB_LOCATION/ruby/cloud/econe/views"
INSTALL_FILES[21]="ECO_BIN_FILES:$BIN_LOCATION"
INSTALL_FILES[22]="OCCI_LIB_FILES:$LIB_LOCATION/ruby/cloud/occi"
INSTALL_FILES[23]="OCCI_BIN_FILES:$BIN_LOCATION"
INSTALL_FILES[24]="MAN_FILES:$MAN_LOCATION"
INSTALL_ECO_CLIENT_FILES[0]="COMMON_CLOUD_CLIENT_LIB_FILES:$LIB_LOCATION/ruby/cloud"
INSTALL_ECO_CLIENT_FILES[1]="ECO_LIB_CLIENT_FILES:$LIB_LOCATION/ruby/cloud/econe"
@ -240,18 +244,19 @@ INSTALL_OCCI_CLIENT_FILES[2]="OCCI_BIN_CLIENT_FILES:$BIN_LOCATION"
INSTALL_ETC_FILES[0]="ETC_FILES:$ETC_LOCATION"
INSTALL_ETC_FILES[1]="VMM_EC2_ETC_FILES:$ETC_LOCATION/vmm_ec2"
INSTALL_ETC_FILES[2]="VMM_SH_ETC_FILES:$ETC_LOCATION/vmm_sh"
INSTALL_ETC_FILES[3]="IM_EC2_ETC_FILES:$ETC_LOCATION/im_ec2"
INSTALL_ETC_FILES[4]="TM_NFS_ETC_FILES:$ETC_LOCATION/tm_nfs"
INSTALL_ETC_FILES[5]="TM_SSH_ETC_FILES:$ETC_LOCATION/tm_ssh"
INSTALL_ETC_FILES[6]="TM_DUMMY_ETC_FILES:$ETC_LOCATION/tm_dummy"
INSTALL_ETC_FILES[7]="TM_LVM_ETC_FILES:$ETC_LOCATION/tm_lvm"
INSTALL_ETC_FILES[8]="HM_ETC_FILES:$ETC_LOCATION/hm"
INSTALL_ETC_FILES[9]="AUTH_ETC_FILES:$ETC_LOCATION/auth"
INSTALL_ETC_FILES[10]="ECO_ETC_FILES:$ETC_LOCATION"
INSTALL_ETC_FILES[11]="ECO_ETC_TEMPLATE_FILES:$ETC_LOCATION/ec2query_templates"
INSTALL_ETC_FILES[12]="OCCI_ETC_FILES:$ETC_LOCATION"
INSTALL_ETC_FILES[13]="OCCI_ETC_TEMPLATE_FILES:$ETC_LOCATION/occi_templates"
INSTALL_ETC_FILES[2]="VMM_SSH_ETC_FILES:$ETC_LOCATION/vmm_ssh"
INSTALL_ETC_FILES[3]="VMM_SH_ETC_FILES:$ETC_LOCATION/vmm_sh"
INSTALL_ETC_FILES[4]="IM_EC2_ETC_FILES:$ETC_LOCATION/im_ec2"
INSTALL_ETC_FILES[5]="TM_NFS_ETC_FILES:$ETC_LOCATION/tm_nfs"
INSTALL_ETC_FILES[6]="TM_SSH_ETC_FILES:$ETC_LOCATION/tm_ssh"
INSTALL_ETC_FILES[7]="TM_DUMMY_ETC_FILES:$ETC_LOCATION/tm_dummy"
INSTALL_ETC_FILES[8]="TM_LVM_ETC_FILES:$ETC_LOCATION/tm_lvm"
INSTALL_ETC_FILES[9]="HM_ETC_FILES:$ETC_LOCATION/hm"
INSTALL_ETC_FILES[10]="AUTH_ETC_FILES:$ETC_LOCATION/auth"
INSTALL_ETC_FILES[11]="ECO_ETC_FILES:$ETC_LOCATION"
INSTALL_ETC_FILES[12]="ECO_ETC_TEMPLATE_FILES:$ETC_LOCATION/ec2query_templates"
INSTALL_ETC_FILES[13]="OCCI_ETC_FILES:$ETC_LOCATION"
INSTALL_ETC_FILES[14]="OCCI_ETC_TEMPLATE_FILES:$ETC_LOCATION/occi_templates"
#-------------------------------------------------------------------------------
# Binary files, to be installed under $BIN_LOCATION
@ -317,6 +322,8 @@ RUBY_OPENNEBULA_LIB_FILES="src/oca/ruby/OpenNebula/Host.rb \
MADS_LIB_FILES="src/mad/sh/madcommon.sh \
src/tm_mad/tm_common.sh \
src/vmm_mad/ssh/one_vmm_ssh.rb \
src/vmm_mad/ssh/one_vmm_ssh \
src/vmm_mad/sh/one_vmm_sh.rb \
src/vmm_mad/sh/one_vmm_sh \
src/vmm_mad/ec2/one_vmm_ec2.rb \
@ -325,6 +332,8 @@ MADS_LIB_FILES="src/mad/sh/madcommon.sh \
src/vmm_mad/dummy/one_vmm_dummy \
src/im_mad/im_ssh/one_im_ssh.rb \
src/im_mad/im_ssh/one_im_ssh \
src/im_mad/im_sh/one_im_sh.rb \
src/im_mad/im_sh/one_im_sh \
src/im_mad/ec2/one_im_ec2.rb \
src/im_mad/ec2/one_im_ec2 \
src/im_mad/dummy/one_im_dummy.rb \
@ -340,7 +349,7 @@ MADS_LIB_FILES="src/mad/sh/madcommon.sh \
# VMM SH Driver KVM scripts, to be installed under $REMOTES_LOCATION/vmm/kvm
#-------------------------------------------------------------------------------
VMM_SH_KVM_SCRIPTS="src/vmm_mad/remotes/kvm/cancel \
VMM_SSH_KVM_SCRIPTS="src/vmm_mad/remotes/kvm/cancel \
src/vmm_mad/remotes/kvm/deploy \
src/vmm_mad/remotes/kvm/kvmrc \
src/vmm_mad/remotes/kvm/migrate \
@ -353,7 +362,7 @@ VMM_SH_KVM_SCRIPTS="src/vmm_mad/remotes/kvm/cancel \
# VMM SH Driver Xen scripts, to be installed under $REMOTES_LOCATION/vmm/xen
#-------------------------------------------------------------------------------
VMM_SH_XEN_SCRIPTS="src/vmm_mad/remotes/xen/cancel \
VMM_SSH_XEN_SCRIPTS="src/vmm_mad/remotes/xen/cancel \
src/vmm_mad/remotes/xen/deploy \
src/vmm_mad/remotes/xen/xenrc \
src/vmm_mad/remotes/xen/migrate \
@ -368,13 +377,15 @@ VMM_SH_XEN_SCRIPTS="src/vmm_mad/remotes/xen/cancel \
IM_PROBES_FILES="src/im_mad/remotes/run_probes"
IM_PROBES_COMMON_FILES="src/im_mad/remotes/common.d/architecture.sh \
src/im_mad/remotes/common.d/cpu.sh \
src/im_mad/remotes/common.d/name.sh"
IM_PROBES_XEN_FILES="src/im_mad/remotes/xen.d/xen.rb \
src/im_mad/remotes/xen.d/architecture.sh \
src/im_mad/remotes/xen.d/cpu.sh \
src/im_mad/remotes/xen.d/name.sh"
IM_PROBES_XEN_FILES="src/im_mad/remotes/xen.d/xen.rb"
IM_PROBES_KVM_FILES="src/im_mad/remotes/kvm.d/kvm.rb"
IM_PROBES_KVM_FILES="src/im_mad/remotes/kvm.d/kvm.rb \
src/im_mad/remotes/kvm.d/architecture.sh \
src/im_mad/remotes/kvm.d/cpu.sh \
src/im_mad/remotes/kvm.d/name.sh"
#-------------------------------------------------------------------------------
@ -422,14 +433,17 @@ ETC_FILES="share/etc/oned.conf \
# Virtualization drivers config. files, to be installed under $ETC_LOCATION
# - ec2, $ETC_LOCATION/vmm_ec2
# - sh, $ETC_LOCATION/vmm_sh
# - ssh, $ETC_LOCATION/vmm_ssh
#-------------------------------------------------------------------------------
VMM_EC2_ETC_FILES="src/vmm_mad/ec2/vmm_ec2rc \
src/vmm_mad/ec2/vmm_ec2.conf"
VMM_SH_ETC_FILES="src/vmm_mad/sh/vmm_shrc \
src/vmm_mad/sh/vmm_sh_kvm.conf \
src/vmm_mad/sh/vmm_sh_xen.conf"
VMM_SSH_ETC_FILES="src/vmm_mad/ssh/vmm_sshrc \
src/vmm_mad/ssh/vmm_ssh_kvm.conf \
src/vmm_mad/ssh/vmm_ssh_xen.conf"
VMM_SH_ETC_FILES="src/vmm_mad/sh/vmm_shrc"
#-------------------------------------------------------------------------------
# Information drivers config. files, to be installed under $ETC_LOCATION
@ -578,6 +592,27 @@ OCCI_ETC_TEMPLATE_FILES="src/cloud/occi/etc/templates/small.erb \
src/cloud/occi/etc/templates/medium.erb \
src/cloud/occi/etc/templates/large.erb"
#-----------------------------------------------------------------------------
# MAN files
#-----------------------------------------------------------------------------
MAN_FILES="share/man/oneauth.8.gz \
share/man/onecluster.8.gz \
share/man/onehost.8.gz \
share/man/oneimage.8.gz \
share/man/oneuser.8.gz \
share/man/onevm.8.gz \
share/man/onevnet.8.gz \
share/man/econe-describe-images.8.gz \
share/man/econe-describe-instances.8.gz \
share/man/econe-register.8.gz \
share/man/econe-run-instances.8.gz \
share/man/econe-terminate-instances.8.gz \
share/man/econe-upload.8.gz \
share/man/occi-compute.8.gz \
share/man/occi-network.8.gz \
share/man/occi-storage.8.gz"
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# INSTALL.SH SCRIPT
@ -653,8 +688,8 @@ if [ "$UNINSTALL" = "no" ] ; then
# --- Set correct permissions for Image Repository ---
if [ -d "$IMAGES_LOCATION" ]; then
chmod 3770 $IMAGES_LOCATION
if [ -d "$DESTDIR$IMAGES_LOCATION" ]; then
chmod 3770 $DESTDIR$IMAGES_LOCATION
fi
else
for d in `echo $DELETE_DIRS | awk '{for (i=NF;i>=1;i--) printf $i" "}'`; do

View File

@ -35,6 +35,8 @@ VM_POLLING_INTERVAL = 600
#VM_DIR=/srv/cloud/one/var
SCRIPTS_REMOTE_DIR=/var/tmp/one
PORT=2633
DB = [ backend = "sqlite" ]
@ -46,7 +48,7 @@ DB = [ backend = "sqlite" ]
# passwd = "oneadmin",
# db_name = "opennebula" ]
VNC_BASE_PORT = 5000
VNC_BASE_PORT = 5900
DEBUG_LEVEL=3
@ -162,9 +164,9 @@ IM_MAD = [
#-------------------------------------------------------------------------------
VM_MAD = [
name = "vmm_kvm",
executable = "one_vmm_sh",
executable = "one_vmm_ssh",
arguments = "kvm",
default = "vmm_sh/vmm_sh_kvm.conf",
default = "vmm_ssh/vmm_ssh_kvm.conf",
type = "kvm" ]
#-------------------------------------------------------------------------------
@ -173,9 +175,9 @@ VM_MAD = [
#-------------------------------------------------------------------------------
#VM_MAD = [
# name = "vmm_xen",
# executable = "one_vmm_sh",
# executable = "one_vmm_ssh",
# arguments = "xen",
# default = "vmm_sh/vmm_sh_xen.conf",
# default = "vmm_ssh/vmm_ssh_xen.conf",
# type = "xen" ]
#-------------------------------------------------------------------------------

View File

@ -36,7 +36,13 @@ if !(vm_id=ARGV[0])
end
client = Client.new()
begin
client = Client.new()
rescue Exception => e
puts "Error: #{e}"
exit(-1)
end
img_repo = ImageRepository.new
vm = VirtualMachine.new(

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
share/man/econe-upload.8.gz Normal file

Binary file not shown.

BIN
share/man/occi-compute.8.gz Normal file

Binary file not shown.

BIN
share/man/occi-network.8.gz Normal file

Binary file not shown.

BIN
share/man/occi-storage.8.gz Normal file

Binary file not shown.

BIN
share/man/oneauth.8.gz Normal file

Binary file not shown.

BIN
share/man/onecluster.8.gz Normal file

Binary file not shown.

BIN
share/man/onehost.8.gz Normal file

Binary file not shown.

BIN
share/man/oneimage.8.gz Normal file

Binary file not shown.

BIN
share/man/oneuser.8.gz Normal file

Binary file not shown.

BIN
share/man/onevm.8.gz Normal file

Binary file not shown.

BIN
share/man/onevnet.8.gz Normal file

Binary file not shown.

View File

@ -34,6 +34,8 @@
#include <openssl/evp.h>
#include <openssl/bio.h>
#include "test/one_test_common.h"
using namespace std;
@ -291,10 +293,14 @@ int main(int argc, char ** argv)
NebulaLog::init_log_system(NebulaLog::FILE, Log::DEBUG,"test.log");
NebulaLog::log("Test", Log::INFO, "Test started");
SETUP_XML_WRITER(runner, "AuthManagerTest.xml");
runner.addTest(AuthManagerTest::suite());
runner.run();
END_XML_WRITER
NebulaLog::finalize_log_system();
return 0;

View File

@ -84,7 +84,12 @@ class AuthorizationManager < OpenNebulaDriver
end
def action_authorize(request_id, user_id, *tokens)
auth=@permissions.auth(user_id, tokens.flatten)
begin
auth=@permissions.auth(user_id, tokens.flatten)
rescue Exception => e
auth="Error: #{e}"
end
if auth==true
send_message('AUTHORIZE', RESULT[:success],
request_id, 'success')
@ -95,7 +100,12 @@ class AuthorizationManager < OpenNebulaDriver
end
end
begin
am=AuthorizationManager.new
rescue Exception => e
puts "Error: #{e}"
exit(-1)
end
am=AuthorizationManager.new
am.start_driver

View File

@ -38,12 +38,19 @@ require 'sequel'
require 'quota'
require 'ssh_auth'
require 'client_utilities'
require 'command_parse'
COMMANDS_HELP=<<-EOT
Usage:
oneauth <command> [<parameters>]
Description:
This command contains a set of utilities to manage authorization module.
Commands:
* quota set (sets quota for a user)
@ -91,7 +98,13 @@ when "quota"
when 'set'
check_parameters("quota set", 3)
Dir.chdir VAR_LOCATION
add_quota(*ARGV[1..3])
begin
add_quota(*ARGV[1..3])
rescue Exception => e
puts "Error starting server: #{e}"
exit(-1)
end
else
#default
end
@ -123,6 +136,9 @@ when "help"
print_help
exit 0
when "--version"
puts CommandParse::ONE_VERSION
else
print_help
exit -1

View File

@ -31,8 +31,12 @@ Options:
EOT
ONE_VERSION=<<-EOT
OpenNebula 1.9.80
OpenNebula 2.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
EOT
def initialize(standard_options=nil)

View File

@ -88,6 +88,14 @@ end
class OneUPParse < CommandParse
COMMANDS_HELP=<<-EOT
Description:
This command enables the OpenNebula administrator to manage clusters. The
administrator can create, delete, as well as add and remove hosts from them.
Any user can list available clusters.
Commands:
* create (Creates a new user)

View File

@ -166,6 +166,14 @@ end
class OnehostParse < CommandParse
COMMANDS_HELP=<<-EOT
Description:
This command enables the user to manage hosts in the Open Nebula server. It
provides functionality to allocate, get information and delete a particular
host or to list all the available hosts.
Commands:
* create (Adds a new machine to the pool)
@ -191,6 +199,20 @@ Commands:
* sync (synchronizes probes with remote hosts)
onehost sync
Information Columns:
* HID Host ID
* NAME Host name
* RVM Number of running VMs
* TCPU Total CPU (percentage)
* FCPU Free CPU (percentage)
* ACPU Available CPU (not allocated by VMs)
* TMEM Total memory
* FMEM Free memory
* STAT Host status
EOT

View File

@ -199,6 +199,12 @@ end
class OneImageParse < CommandParse
COMMANDS_HELP=<<-EOT
Description:
This command enables the user to manage images.
Commands:
* register (Registers an image, copying it to the repository if it applies)
@ -206,6 +212,9 @@ Commands:
template is a file name where the Image description is located
* addattr (Add a new image attribute)
oneimage addattr <image_id> <attribute_name> <attribute_value>
* update (Modifies an image attribute)
oneimage update <image_id> <attribute_name> <attribute_value>
@ -234,11 +243,11 @@ Commands:
oneimage list <filter_flag>
where filter_flag can be
a, all --> all the known Images (admin users)
m, mine --> the Images belonging to the user in ONE_AUTH
and all the Public Images
uid --> Images of the user identified by this uid (admin users)
user --> Images of the user identified by the username (admin users)
a, all --> all the known Images
m, mine --> the Images belonging to the user in ONE_AUTH
and all the Public Images
uid --> Images of the user identified by this uid
user --> Images of the user identified by the username
* top (Lists Images continuously)
onevm top
@ -263,12 +272,6 @@ EOT
table=ShowTable.new(ShowTableImage)
table.print_help
end
def special_options(opts, options)
opts.on_tail("-n", "--no-cp", "Do not copy the source") do |o|
options[:no_cp]=true
end
end
end
@ -327,13 +330,13 @@ when "register", "create", "add"
image = OpenNebula::Image.new(OpenNebula::Image.build_xml, get_one_client)
result = img_repo.create(image, template, !ops[:no_cp])
result = img_repo.create(image, template)
if is_successful?(result)
puts "ID: " + image.id.to_s if ops[:verbose]
end
when "update"
when "update", "addattr"
check_parameters("update", 3)
image_id=get_image_id(ARGV[0])
@ -473,7 +476,11 @@ when "show"
else
public_str = "No"
end
puts str % ["PUBLIC", public_str]
puts str % ["PUBLIC", public_str]
persistent_str=(image["PERSISTENT"].to_i==1 ? "Yes" : "No")
puts str % ["PERSISTENT", persistent_str]
puts str % ["SOURCE", image['SOURCE']]
puts str % ["STATE", image.short_state_str]
puts str % ["RUNNING_VMS", image['RUNNING_VMS']]

View File

@ -92,6 +92,16 @@ end
class OneUPParse < CommandParse
COMMANDS_HELP=<<-EOT
Description:
This command enables the OpenNebula administrator to manage users, adding,
listing and deleting them.
The create and passwd commands accept the [-r, read-file] option. Use this
option to store the contents of a file (without hashing it) as the password.
Commands:
* create (Creates a new user)
@ -106,6 +116,15 @@ Commands:
* passwd (Changes the given user's password)
oneuser passwd <id> password
Information Columns:
* UID User ID
* NAME Name of the user
* PASSWORD SHA1 encrypted password
* ENABLE Whether the user is enabled or not
EOT
def text_commands
@ -148,7 +167,7 @@ when "create"
if ops[:read_file]
begin
password = File.read(ARGV[1])
password = File.read(ARGV[1]).split("\n").first
rescue
puts "Can not read file: #{ARGV[1]}"
exit -1
@ -218,7 +237,7 @@ when "passwd"
if ops[:read_file]
begin
password = File.read(ARGV[1])
password = File.read(ARGV[1]).split("\n").first
rescue
puts "Can not read file: #{ARGV[1]}"
exit -1

View File

@ -307,6 +307,14 @@ end
class OnevmParse < CommandParse
COMMANDS_HELP=<<-EOT
Description:
This command enables the user to manage virtual machines in the ONE server.
The user can allocate, deploy, migrate, suspend, resume and shutdown a virtual
machine with the functionality present in onevm.
Commands:
* create (Submits a new virtual machine, adding it to the ONE VM pool)
@ -363,7 +371,7 @@ Commands:
a, all --> all the known VMs
m, mine --> the VMs belonging to the user in ONE_AUTH
uid --> VMs of the user identified by this uid
user--> VMs of the user identified by the username
user --> VMs of the user identified by the username
* show (Gets information about a specific VM)
onevm show <vm_id>
@ -376,6 +384,35 @@ Commands:
if no vm_id is provided it will list history for all known VMs
Information Columns:
* ID ONE VM identifier
* USER Username of the VM owner
* NAME Name of the ONE
* STAT Status of the VM
* CPU CPU percentage used by the VM
* MEM Memory used by the VM
* HOSTNAME Host where the VM is being or was run
* TIME Time since the submission of the VM (days hours:minutes:seconds)
VM States:
* pend pending
* hold VM on hold (not runnable)
* stop stopped
* susp suspended
* done finished
* prol prolog
* boot booting
* runn running
* migr migrating
* save saving the VM to disk
* epil epilog
* shut shutting down
* fail failed
EOT
def text_commands
@ -707,7 +744,13 @@ when "saveas"
else
image_id = vm["TEMPLATE/DISK[DISK_ID=\"#{disk_id}\"]/IMAGE_ID"]
if (image_id != nil)
if (image_id != nil)
if vm["TEMPLATE/DISK[DISK_ID=\"#{disk_id}\"]/SAVE_AS"]
puts "Error: The disk #{disk_id} is already" <<
" suppossed to be saved"
exit -1
end
# Get the image type
image = OpenNebula::Image.new(
OpenNebula::Image.build_xml(image_id),
@ -718,7 +761,7 @@ when "saveas"
puts result.message
exit -1
end
image_type = image.type_str
end
end
@ -733,13 +776,19 @@ when "saveas"
get_one_client)
result = image.allocate(template)
if !is_successful?(result)
puts result.message
exit -1
end
result = vm.save_as(disk_id.to_i, image.id)
if is_successful?(result)
puts "VM disk with ID #{disk_id} is prepared to be" <<
" saved" if ops[:verbose]
else
image.delete
end
when "show"
check_parameters("get_info", 1)

View File

@ -137,6 +137,14 @@ end
class OneVNParse < CommandParse
COMMANDS_HELP=<<-EOT
Description:
This command enables the user to manage virtual networks in the OpenNebula
server. It provides functionality to create, get information and delete a
particular network or to list available and used IP's.
Commands:
* create (Creates a new virtual network)
@ -159,10 +167,21 @@ Commands:
* list (Lists virtual networks in the pool)
onevnet list <filter_flag>
where filter_flag can be
a, all --> all the known VNs
m, mine --> the VNs belonging to the user in ONE_AUTH
uid --> VNs of the user identified by this uid
user --> VNs of the user identified by the username
a, all : all the known VNs
m, mine : the VNs belonging to the user in ONE_AUTH
and all the Public VNs
uid : VNs of the user identified by this uid
user : VNs of the user identified by the username
Information columns:
* NID Network ID
* NAME Name of the virtual network
* TYPE Type of virtual network (0=ranged, 1=fixed)
* BRIDGE Bridge associated to the virtual network
* LEASES Number of leases used from this virtual network
EOT
def text_commands
@ -238,9 +257,6 @@ when "show"
else
puts vn.to_xml(true)
end
else
puts "Error: "+result.message
break
end
end

View File

@ -135,4 +135,15 @@ module CloudCLI
def cmd_name
File.basename($0)
end
def version_text
version=<<EOT
OpenNebula 2.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
EOT
end
end

View File

@ -44,6 +44,10 @@ class CloudServer
@config = Configuration.new(config_file)
if @config[:vm_type] == nil
raise "No VM_TYPE defined."
end
@instance_types = Hash.new
if @config[:vm_type].kind_of?(Array)
@ -56,8 +60,9 @@ class CloudServer
# --- Start an OpenNebula Session ---
@one_client = Client.new()
@one_client = Client.new(nil,@config[:one_xmlrpc])
@user_pool = UserPool.new(@one_client)
@img_repo = OpenNebula::ImageRepository.new
end
@ -123,7 +128,7 @@ class CloudServer
rc = @img_repo.create(image, template)
file[:tempfile].unlink
if OpenNebula.is_error?(rc)
return rc
end
@ -133,8 +138,8 @@ class CloudServer
# Finds out if a port is available on ip
# ip:: _String_ IP address where the port to check is
# port:: _String_ port to find out whether is open
# [return] _Boolean_ Newly created image object
# port:: _String_ port to find out whether is open
# [return] _Boolean_ Newly created image object
def self.is_port_open?(ip, port)
begin
Timeout::timeout(2) do

View File

@ -28,30 +28,28 @@ $: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cloud"
COMMANDS_HELP=<<-EOT
** Synopsis
-----------
econe-describe-images
econe-describe-images
List and describe previously uploaded images of a user to be
used with an OpenNebula Cloud.
List and describe previously uploaded images of a user to be
used with an OpenNebula Cloud.
** Usage
--------
Usage:
econe-describe-images [OPTIONS]
--help, -h:
Options:
--help, -h
Show help
--access-key <id>, -K <id>:
--access-key <id>, -K <id>
The username of the user
--secret-key <key>, -S <key>:
--secret-key <key>, -S <key>
The password of the user
--url <url>, -U <url>:
--url <url>, -U <url>
Set url as the web service url to use
--headers, -H:
--headers, -H
Display column headers
EOT
@ -65,6 +63,7 @@ include CloudCLI
opts = GetoptLong.new(
['--help', '-h',GetoptLong::NO_ARGUMENT],
['--version', '-v',GetoptLong::NO_ARGUMENT],
['--access-key', '-K',GetoptLong::REQUIRED_ARGUMENT],
['--secret-key', '-S',GetoptLong::REQUIRED_ARGUMENT],
['--url', '-U',GetoptLong::REQUIRED_ARGUMENT],
@ -83,6 +82,9 @@ begin
when '--help'
puts COMMANDS_HELP
return
when '--version'
puts CloudCLI.version_text
exit 0
when '--access-key'
access = arg
when '--secret-key'

View File

@ -27,29 +27,28 @@ $: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cloud"
COMMANDS_HELP=<<-EOT
** Synopsis
-----------
econe-describe-instances
List and describe running instances
econe-describe-instances
** Usage
--------
List and describe running instances
Usage:
econe-describe-instances [OPTIONS]
Options:
--help, -h:
--help, -h
Show help
--access-key <id>, -K <id>:
--access-key <id>, -K <id>
The username of the user
--secret-key <key>, -S <key>:
--secret-key <key>, -S <key>
The password of the user
--url <url>, -U <url>:
--url <url>, -U <url>
Set url as the web service url to use
--headers, -H:
--headers, -H
Display column headers
EOT
@ -62,6 +61,7 @@ include CloudCLI
opts = GetoptLong.new(
['--help', '-h',GetoptLong::NO_ARGUMENT],
['--version', '-v',GetoptLong::NO_ARGUMENT],
['--access-key', '-K',GetoptLong::REQUIRED_ARGUMENT],
['--secret-key', '-S',GetoptLong::REQUIRED_ARGUMENT],
['--url', '-U',GetoptLong::REQUIRED_ARGUMENT],
@ -80,6 +80,9 @@ begin
when '--help'
puts COMMANDS_HELP
return
when '--version'
puts CloudCLI.version_text
exit 0
when '--access-key'
access = arg
when '--secret-key'

View File

@ -27,34 +27,33 @@ $: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cloud"
COMMANDS_HELP=<<-EOT
** Synopsis
-----------
econe-register
Register a previously uploaded image for use with an
OpenNebula Cloud.
econe-register
** Usage
--------
Register a previously uploaded image for use with an
OpenNebula Cloud.
Usage:
econe-register [OPTIONS] IMAGE-ID
--help, -h:
Options:
--help, -h
Show help
--access-key <id>, -K <id>:
--access-key <id>, -K <id>
The username of the user
--secret-key <key>, -S <key>:
--secret-key <key>, -S <key>
The password of the user
--url <url>, -U <url>:
--url <url>, -U <url>
Set url as the web service url to use
--headers, -H:
--headers, -H
Display column headers
IMAGE-ID: The image identification as returned by
the econe-upload command
IMAGE-ID: The image identification as returned by
the econe-upload command
EOT
@ -66,6 +65,7 @@ include CloudCLI
opts = GetoptLong.new(
['--help', '-h',GetoptLong::NO_ARGUMENT],
['--version', '-v',GetoptLong::NO_ARGUMENT],
['--access-key', '-K',GetoptLong::REQUIRED_ARGUMENT],
['--secret-key', '-S',GetoptLong::REQUIRED_ARGUMENT],
['--url', '-U',GetoptLong::REQUIRED_ARGUMENT],
@ -84,6 +84,9 @@ begin
when '--help'
puts COMMANDS_HELP
return
when '--version'
puts CloudCLI.version_text
exit 0
when '--access-key'
access = arg
when '--secret-key'

View File

@ -28,40 +28,39 @@ $: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cloud"
COMMANDS_HELP=<<-EOT
** Synopsis
-----------
econe-run-instances
Runs an instance of a particular image
econe-run-instances
** Usage
--------
Runs an instance of a particular image
Usage:
econe-run-instances [OPTIONS] IMAGE-ID
--help, -h:
Options:
--help, -h
Show help
--access-key <id>, -K <id>:
--access-key <id>, -K <id>
The username of the user
--secret-key <key>, -S <key>:
--secret-key <key>, -S <key>
The password of the user
--url <url>, -U <url>:
--url <url>, -U <url>
Set url as the web service url to use
--type <type>, -t <type>:
--type <type>, -t <type>
OpenNebula template in which is based this instance
-user-data, -d:
--user-data, -d
Specifies Base64-encoded MIME user data to be made
available to the instance
--headers, -H:
--headers, -H
Display column headers
IMAGE-ID: The image identification as returned by
the econe-upload command
IMAGE-ID: The image identification as returned by
the econe-upload command
EOT
@ -73,6 +72,7 @@ include CloudCLI
opts = GetoptLong.new(
['--help', '-h',GetoptLong::NO_ARGUMENT],
['--version', '-v',GetoptLong::NO_ARGUMENT],
['--access-key', '-K',GetoptLong::REQUIRED_ARGUMENT],
['--secret-key', '-S',GetoptLong::REQUIRED_ARGUMENT],
['--url', '-U',GetoptLong::REQUIRED_ARGUMENT],
@ -95,6 +95,9 @@ begin
when '--help'
puts COMMANDS_HELP
return
when '--version'
puts CloudCLI.version_text
exit 0
when '--access-key'
access = arg
when '--secret-key'

View File

@ -28,30 +28,29 @@ $: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cloud"
COMMANDS_HELP=<<-EOT
** Synopsis
-----------
econe-terminate-instances
Terminate the selected running instance
econe-terminate-instances
** Usage
--------
Terminate the selected running instance
Usage:
econe-register [OPTIONS] INSTANCE-ID
--help, -h:
Options:
--help, -h
Show help
--access-key <id>, -K <id>:
--access-key <id>, -K <id>
The username of the user
--secret-key <key>, -S <key>:
--secret-key <key>, -S <key>
The password of the user
--url <url>, -U <url>:
--url <url>, -U <url>
Set url as the web service url to use
INSTANCE-ID: The instance identification as returned by
the econe-run-instances command
INSTANCE-ID: The instance identification as returned by
the econe-run-instances command
EOT
@ -63,6 +62,7 @@ include CloudCLI
opts = GetoptLong.new(
['--help', '-h',GetoptLong::NO_ARGUMENT],
['--version', '-v',GetoptLong::NO_ARGUMENT],
['--access-key', '-K',GetoptLong::REQUIRED_ARGUMENT],
['--secret-key', '-S',GetoptLong::REQUIRED_ARGUMENT],
['--url', '-U',GetoptLong::REQUIRED_ARGUMENT]
@ -79,6 +79,9 @@ begin
when '--help'
puts COMMANDS_HELP
return
when '--version'
puts CloudCLI.version_text
exit 0
when '--access-key'
access = arg
when '--secret-key'

View File

@ -27,33 +27,32 @@ $: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cloud"
COMMANDS_HELP=<<-EOT
** Synopsis
-----------
econe-upload
Uploads an image for use with an OpenNebula Cloud. This image should
be later register with econe-register using the returned ImageId
econe-upload
** Usage
--------
Uploads an image for use with an OpenNebula Cloud. This image should
be later register with econe-register using the returned ImageId
Usage:
econe-upload [OPTIONS] IMAGE-PATH
--help, -h:
Options:
--help, -h
Show help
--access-key <id>, -K <id>:
--access-key <id>, -K <id>
The username of the user
--secret-key <key>, -S <key>:
--secret-key <key>, -S <key>
The password of the user
--url <url>, -U <url>:
--url <url>, -U <url>
Set url as the web service url to use
--multipart, -M:
--multipart, -M
Use 'multipart-post' library instead of Curb/Curl
IMAGE-PATH: Path to the image to upload
IMAGE-PATH: Path to the image to upload
EOT
@ -65,6 +64,7 @@ include CloudCLI
opts = GetoptLong.new(
['--help', '-h',GetoptLong::NO_ARGUMENT],
['--version', '-v',GetoptLong::NO_ARGUMENT],
['--access-key', '-K',GetoptLong::REQUIRED_ARGUMENT],
['--secret-key', '-S',GetoptLong::REQUIRED_ARGUMENT],
['--url', '-U',GetoptLong::REQUIRED_ARGUMENT],
@ -83,6 +83,9 @@ begin
when '--help'
puts COMMANDS_HELP
return
when '--version'
puts CloudCLI.version_text
exit 0
when '--access-key'
access = arg
when '--secret-key'

View File

@ -45,8 +45,13 @@ require 'EC2QueryServer'
include OpenNebula
$econe_server = EC2QueryServer.new(CONFIGURATION_FILE,
TEMPLATE_LOCATION, VIEWS_LOCATION)
begin
$econe_server = EC2QueryServer.new(CONFIGURATION_FILE,
TEMPLATE_LOCATION, VIEWS_LOCATION)
rescue Exception => e
puts "Error starting server: #{e}"
exit(-1)
end
if CloudServer.is_port_open?($econe_server.config[:server],
$econe_server.config[:port])

View File

@ -29,51 +29,48 @@ $: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cloud"
COMMANDS_HELP=<<-EOT
** Synopsis
occi-compute
occi-compute - Manages compute resources
Manages compute resources
Usage:
occi-compute <COMMAND> [OPTIONS] [ARGUMENTS]
** Usage
occi-compute <COMMAND> [OPTIONS] [ARGUMENTS]
Commands:
COMMANDS
create <occi xml file>
* create <occi xml file>
creates a new compute resource described by the provided
<occi xml file>
list
* list
lists available compute resources
show <compute id>
* show <compute id>
retrieves the OCCI XML representation of the compute resource
identified by <compute id>
update <occi xml file>
* update <occi xml file>
updates the representation of the compute resource represented by the
provided <occi xml file>
delete <compute id>
* delete <compute id>
deletes the compute resource idenfitied by <compute id>
OPTIONS
Options:
--help, -h:
--help, -h
Show help
--username <id>, -U <id>:
--username <id>, -U <id>
The username of the user
--password <key>, -P <key>:
--password <key>, -P <key>
The password of the user
--url <url>, -R <url>:
--url <url>, -R <url>
Set url as the web service url to use
--timeout <seconds>, -T <seconds>
Sets a timeout for the http connection
Sets a timeout for the http connection
--debug, -D
Enables verbosity
@ -88,6 +85,7 @@ include CloudCLI
opts = GetoptLong.new(
['--help', '-h',GetoptLong::NO_ARGUMENT],
['--version', '-v',GetoptLong::NO_ARGUMENT],
['--username', '-U',GetoptLong::REQUIRED_ARGUMENT],
['--password', '-P',GetoptLong::REQUIRED_ARGUMENT],
['--url', '-R',GetoptLong::REQUIRED_ARGUMENT],
@ -108,6 +106,9 @@ begin
when '--help'
puts COMMANDS_HELP
return
when '--version'
puts CloudCLI.version_text
exit 0
when '--username'
username = arg
when '--password'

View File

@ -29,15 +29,12 @@ $: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cloud"
COMMANDS_HELP=<<-EOT
** Synopsis
occi-network
occi-network - Manages virtual networks
Manages virtual networks
Usage:
occi-network <COMMAND> [OPTIONS] [ARGUMENTS]
** Usage
occi-network <COMMAND> [OPTIONS] [ARGUMENTS]
COMMANDS
Commands:
create <occi xml file>
creates a new virtual network described by the provided
@ -55,18 +52,18 @@ delete <network id>
OPTIONS
Options:
--help, -h:
--help, -h
Show help
--username <id>, -U <id>:
--username <id>, -U <id>
The username of the user
--password <key>, -P <key>:
--password <key>, -P <key>
The password of the user
--url <url>, -R <url>:
--url <url>, -R <url>
Set url as the web service url to use
--timeout <seconds>, -T <seconds>
@ -75,7 +72,7 @@ OPTIONS
--debug, -D
Enables verbosity
--multipart, -M:
--multipart, -M
Use 'multipart-post' library instead of Curb/Curl
EOT
@ -89,6 +86,7 @@ include CloudCLI
opts = GetoptLong.new(
['--help', '-h',GetoptLong::NO_ARGUMENT],
['--version', '-v',GetoptLong::NO_ARGUMENT],
['--username', '-U',GetoptLong::REQUIRED_ARGUMENT],
['--password', '-P',GetoptLong::REQUIRED_ARGUMENT],
['--url', '-R',GetoptLong::REQUIRED_ARGUMENT],
@ -109,6 +107,9 @@ begin
when '--help'
puts COMMANDS_HELP
return
when '--version'
puts CloudCLI.version_text
exit 0
when '--username'
username = arg
when '--password'

View File

@ -29,15 +29,12 @@ $: << RUBY_LIB_LOCATION
$: << RUBY_LIB_LOCATION+"/cloud"
COMMANDS_HELP=<<-EOT
** Synopsis
occi-storage
occi-storage - Manages OCCI storage resource
Manages OCCI storage resource
Usage:
occi-storage <COMMAND> [OPTIONS] [PARAMETERS]
** Usage
occi-storage <COMMAND> [OPTIONS] [PARAMETERS]
COMMANDS
Commands:
create <occi xml file>
creates a new storage resource described by the provided
@ -54,17 +51,18 @@ delete <storage id>
deletes the storage resource idenfitied by <storage id>
OPTIONS
--help, -h:
Options:
--help, -h
Show help
--username <id>, -U <id>:
--username <id>, -U <id>
The username of the user
--password <key>, -P <key>:
--password <key>, -P <key>
The password of the user
--url <url>, -R <url>:
--url <url>, -R <url>
Set url as the web service url to use
--timeout <seconds>, -T <seconds>
@ -73,7 +71,7 @@ OPTIONS
--debug, -D
Enables verbosity
--multipart, -M:
--multipart, -M
Use 'multipart-post' library instead of Curb/Curl
EOT
@ -87,6 +85,7 @@ include CloudCLI
opts = GetoptLong.new(
['--help', '-h',GetoptLong::NO_ARGUMENT],
['--version', '-v',GetoptLong::NO_ARGUMENT],
['--username', '-U',GetoptLong::REQUIRED_ARGUMENT],
['--password', '-P',GetoptLong::REQUIRED_ARGUMENT],
['--url', '-R',GetoptLong::REQUIRED_ARGUMENT],
@ -109,6 +108,9 @@ begin
when '--help'
puts COMMANDS_HELP
return
when '--version'
puts CloudCLI.version_text
exit 0
when '--username'
username = arg
when '--password'

View File

@ -0,0 +1,42 @@
#
# This template is processed by the OCCI Server to include specific data for the
# instance, you should not need to modify the <% ... %> compounds.
# You can add common attributes for your cloud templates (e.g. OS)
#
NAME = "<%= @vm_info['NAME'] %>"
<% @vm_info.each('DISK') do |disk| %>
<% if disk.attr('STORAGE','href') %>
DISK = [ IMAGE_ID = <%= disk.attr('STORAGE','href').split('/').last %>
]
<% end %>
<% end %>
<% @vm_info.each('NIC') do |nic| %>
<% if nic.attr('NETWORK','href') %>
NIC = [ NETWORK_ID = <%= nic.attr('NETWORK','href').split('/').last %>
<% if nic['IP'] %>
,IP = <%= nic['IP'] %>
<% end %>
]
<% end %>
<% end %>
<% if @vm_info.has_elements?('CONTEXT') %>
CONTEXT = [
<% first = true %>
<% @vm_info.each('CONTEXT/*') do |cont| %>
<% if cont.text %>
<% if first %>
<%= cont.name %> = "<%= cont.text %>"
<% first = false %>
<% else %>
,<%= cont.name %> = "<%= cont.text %>"
<% end %>
<% end %>
<% end %>
]
<% end %>
INSTANCE_TYPE = <%= @vm_info['INSTANCE_TYPE']%>

View File

@ -1,34 +1,8 @@
#
# Virtual Machine Template generated for large instance types. Adjust this
# by setting the desired capacity (CPU,MEMORY) or adding specific
# attributes for your cloud (e.g. OS). You should not need to change the DISK
# and NIC sections
# attributes for your cloud (e.g. OS).
#
CPU = 8
MEMORY = 8192
NAME = "<%= @vm_info['NAME'] %>"
<% if @vm_info['DISK'] %>
<% @vm_info.each('DISK') do |disk| %>
<% if disk['STORAGE'] && disk.attr('STORAGE','href') %>
DISK = [ IMAGE_ID = <%= disk.attr('STORAGE','href').split('/').last %>
]
<% end %>
<% end %>
<% end %>
<% if @vm_info['NIC'] %>
<% @vm_info.each('NIC') do |nic| %>
<% if nic['NETWORK'] && nic.attr('NETWORK','href') %>
NIC = [ NETWORK_ID = <%= nic.attr('NETWORK','href').split('/').last %>
<% if nic['IP'] %>
,IP = <%= nic['IP'] %>
<% end %>
]
<% end %>
<% end %>
<% end %>
INSTANCE_TYPE = <%= @vm_info['INSTANCE_TYPE']%>

View File

@ -1,35 +1,9 @@
#
# Virtual Machine Template generated for medium instance types. Adjust this
# by setting the desired capacity (CPU,MEMORY) or adding specific
# attributes for your cloud (e.g. OS). You should not need to change the DISK
# and NIC sections
# attributes for your cloud (e.g. OS).
#
CPU = 4
MEMORY = 4096
NAME = "<%= @vm_info['NAME'] %>"
<% if @vm_info['DISK'] %>
<% @vm_info.each('DISK') do |disk| %>
<% if disk['STORAGE'] && disk.attr('STORAGE','href') %>
DISK = [ IMAGE_ID = <%= disk.attr('STORAGE','href').split('/').last %>
]
<% end %>
<% end %>
<% end %>
<% if @vm_info['NIC'] %>
<% @vm_info.each('NIC') do |nic| %>
<% if nic['NETWORK'] && nic.attr('NETWORK','href') %>
NIC = [ NETWORK_ID = <%= nic.attr('NETWORK','href').split('/').last %>
<% if nic['IP'] %>
,IP = <%= nic['IP'] %>
<% end %>
]
<% end %>
<% end %>
<% end %>
INSTANCE_TYPE = <%= @vm_info['INSTANCE_TYPE']%>

View File

@ -1,35 +1,9 @@
#
# Virtual Machine Template generated for small instance types. Adjust this
# by setting the desired capacity (CPU,MEMORY) or adding specific
# attributes for your cloud (e.g. OS). You should not need to change the DISK
# and NIC sections
# attributes for your cloud (e.g. OS).
#
CPU = 1
MEMORY = 1024
NAME = "<%= @vm_info['NAME'] %>"
<% if @vm_info['DISK'] %>
<% @vm_info.each('DISK') do |disk| %>
<% if disk['STORAGE'] && disk.attr('STORAGE','href') %>
DISK = [ IMAGE_ID = <%= disk.attr('STORAGE','href').split('/').last %>
]
<% end %>
<% end %>
<% end %>
<% if @vm_info['NIC'] %>
<% @vm_info.each('NIC') do |nic| %>
<% if nic['NETWORK'] && nic.attr('NETWORK','href') %>
NIC = [ NETWORK_ID = <%= nic.attr('NETWORK','href').split('/').last %>
<% if nic['IP'] %>
,IP = <%= nic['IP'] %>
<% end %>
]
<% end %>
<% end %>
<% end %>
INSTANCE_TYPE = <%= @vm_info['INSTANCE_TYPE']%>

View File

@ -27,17 +27,14 @@ class VirtualMachineOCCI < VirtualMachine
<INSTANCE_TYPE><%= self['TEMPLATE/INSTANCE_TYPE'] %></INSTANCE_TYPE>
<% end %>
<STATE><%= self.state_str %></STATE>
<% if self['TEMPLATE/DISK'] %>
<% self.each('TEMPLATE/DISK') do |disk| %>
<% self.each('TEMPLATE/DISK') do |disk| %>
<DISK>
<STORAGE href="<%= base_url %>/storage/<%= disk['IMAGE_ID'] %>" name="<%= disk['IMAGE'] %>"/>
<TYPE><%= disk['TYPE'] %></TYPE>
<TARGET><%= disk['TARGET'] %></TARGET>
</DISK>
<% end %>
<% end %>
<% if self['TEMPLATE/NIC'] %>
<% self.each('TEMPLATE/NIC') do |nic| %>
<% self.each('TEMPLATE/NIC') do |nic| %>
<NIC>
<NETWORK href="<%= base_url %>/network/<%= nic['NETWORK_ID'] %>" name="<%= nic['NETWORK'] %>"/>
<% if nic['IP'] %>
@ -47,32 +44,41 @@ class VirtualMachineOCCI < VirtualMachine
<MAC><%= nic['MAC'] %></MAC>
<% end %>
</NIC>
<% end %>
<% if self['TEMPLATE/CONTEXT'] %>
<CONTEXT>
<% self.each('TEMPLATE/CONTEXT/*') do |cont| %>
<% if cont.text %>
<<%= cont.name %>><%= cont.text %></<%= cont.name %>>
<% end %>
<% end %>
</CONTEXT>
<% end %>
</COMPUTE>
}
# Class constructor
def initialize(xml, client, xml_info = nil, types=nil, base=nil)
def initialize(xml, client, xml_info=nil, types=nil, base=nil)
super(xml, client)
@vm_info = nil
@template = nil
@common_template = base + '/common.erb' if base
if xml_info != nil
xmldoc = XMLElement.build_xml(xml_info, 'COMPUTE')
@vm_info = XMLElement.new(xmldoc) if xmldoc != nil
end
if @vm_info != nil
itype = @vm_info['INSTANCE_TYPE']
if itype != nil and types[itype] != nil
@template = base + "/#{types[itype]['TEMPLATE']}"
end
end
end
def mk_action(action_str)
case action_str.downcase
when "stopped"
@ -92,31 +98,31 @@ class VirtualMachineOCCI < VirtualMachine
error = OpenNebula::Error.new(error_msg)
return error
end
return rc
end
def to_one_template()
if @vm_info == nil
error_msg = "Missing COMPUTE section in the XML body"
return OpenNebula::Error.new(error_msg), 400
end
if @template == nil
return OpenNebula::Error.new("Bad instance type"), 500
end
begin
template = ERB.new(File.read(@template))
template_text = template.result(binding)
template = ERB.new(File.read(@common_template)).result(binding)
template << ERB.new(File.read(@template)).result(binding)
rescue Exception => e
error = OpenNebula::Error.new(e.message)
return error
end
return template_text
return template
end
# Creates the VMI representation of a Virtual Machine
def to_occi(base_url)
begin
@ -127,6 +133,7 @@ class VirtualMachineOCCI < VirtualMachine
return error
end
return occi_vm_text.gsub(/\n\s*/,'')
end
end

View File

@ -49,7 +49,12 @@ require 'OpenNebula'
include OpenNebula
$occi_server = OCCIServer.new(CONFIGURATION_FILE, TEMPLATE_LOCATION)
begin
$occi_server = OCCIServer.new(CONFIGURATION_FILE, TEMPLATE_LOCATION)
rescue Exception => e
puts "Error starting server: #{e}"
exit(-1)
end
if CloudServer.is_port_open?($occi_server.config[:server],
$occi_server.config[:port])

View File

@ -10,6 +10,8 @@
#include <TestCaller.h>
#include <ui/text/TestRunner.h>
#include "test/one_test_common.h"
using namespace std;
extern "C" void * addsub_loop(void *arg);
@ -175,9 +177,13 @@ int main(int argc, char ** argv)
{
CppUnit::TextUi::TestRunner tr;
SETUP_XML_WRITER(tr, "action_manager.xml");
tr.addTest(ActionManagerTest::suite());
tr.run();
END_XML_WRITER
return 0;
}

View File

@ -27,6 +27,8 @@ extern "C"
#include <TestCaller.h>
#include <ui/text/TestRunner.h>
#include "test/one_test_common.h"
using namespace std;
class MemCollectorTest : public CppUnit::TestFixture
@ -110,8 +112,12 @@ int main(int argc, char ** argv)
{
CppUnit::TextUi::TestRunner tr;
SETUP_XML_WRITER(tr, "mem_collector.xml");
tr.addTest(MemCollectorTest::suite());
tr.run();
END_XML_WRITER
return 0;
}

View File

@ -9,6 +9,8 @@
#include <TestCaller.h>
#include <ui/text/TestRunner.h>
#include "test/one_test_common.h"
using namespace std;
class SingleAttributeTest : public CppUnit::TestFixture
@ -123,9 +125,13 @@ public:
int main(int argc, char ** argv)
{
CppUnit::TextUi::TestRunner tr;
SETUP_XML_WRITER(tr, "single_attribute.xml");
tr.addTest(SingleAttributeTest::suite());
tr.run();
END_XML_WRITER
return 0;
}

View File

@ -10,6 +10,8 @@
#include <TestCaller.h>
#include <ui/text/TestRunner.h>
#include "test/one_test_common.h"
using namespace std;
class VectorAttributeTest : public CppUnit::TestFixture
@ -156,9 +158,13 @@ int main(int argc, char ** argv)
{
CppUnit::TextUi::TestRunner tr;
SETUP_XML_WRITER(tr, "vector_attribute.xml");
tr.addTest(VectorAttributeTest::suite());
tr.run();
END_XML_WRITER
return 0;
}

View File

@ -16,16 +16,17 @@
# limitations under the License. #
#--------------------------------------------------------------------------- #
#Setup driver variables
DRIVER_NAME="im_vmware"
DRIVER_NAME=`basename $0 | cut -d. -f1`
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
@ -34,22 +35,10 @@ fi
export_rc_vars $DRIVERRC
# Go to var directory ONE_LOCATION/var or /var/lib/one
cd $VAR_LOCATION
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
execute_mad $*

87
src/im_mad/im_sh/one_im_sh.rb Executable file
View File

@ -0,0 +1,87 @@
#!/usr/bin/env ruby
# -------------------------------------------------------------------------- #
# 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. #
#--------------------------------------------------------------------------- #
ONE_LOCATION=ENV["ONE_LOCATION"]
if !ONE_LOCATION
RUBY_LIB_LOCATION="/usr/lib/one/ruby"
ETC_LOCATION="/etc/one/"
PROBE_LOCATION="/usr/lib/one/im_probes/"
REMOTES_LOCATION="/usr/lib/one/remotes"
else
RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby"
ETC_LOCATION=ONE_LOCATION+"/etc/"
PROBE_LOCATION=ONE_LOCATION+"/lib/im_probes/"
REMOTES_LOCATION=ONE_LOCATION+"/lib/remotes/"
end
$: << RUBY_LIB_LOCATION
require 'OpenNebulaDriver'
require 'CommandManager'
#-------------------------------------------------------------------------------
# The Local Information Manager Driver
#-------------------------------------------------------------------------------
class InformationManager < OpenNebulaDriver
#---------------------------------------------------------------------------
# Init the driver
#---------------------------------------------------------------------------
def initialize(hypervisor, num)
super(num, true)
@config = read_configuration
@hypervisor = hypervisor
@cmd_path = "#{ENV['ONE_LOCATION']}/lib/remotes/im"
# register actions
register_action(:MONITOR, method("action_monitor"))
end
#---------------------------------------------------------------------------
# Execute the run_probes in the remote host
#---------------------------------------------------------------------------
def action_monitor(number, host, unused)
log_lambda=lambda do |message|
log(number, message)
end
cmd_string = "#{@cmd_path}/run_probes #{@hypervisor} #{host}"
monitor_exe = LocalCommand.run(cmd_string, host, log_method(id))
if monitor_exe.code == 0
send_message("MONITOR", RESULT[:success], number, monitor_exe.stdout)
else
send_message("MONITOR", RESULT[:failure], number,
"Could not monitor host #{host}.")
end
end
end
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Information Manager main program
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
hypervisor = ARGV[0]
im = InformationManager.new(hypervisor, 15)
im.start_driver

View File

@ -26,7 +26,7 @@ done
shift $(($OPTIND - 1))
#Setup driver variables
DRIVER_NAME=`basename $1 | cut -d. -f1`
DRIVER_NAME=`basename $0 | cut -d. -f1`
if [ -z "${ONE_LOCATION}" ]; then
DRIVERRC=/etc/one/${DRIVER_NAME}/${DRIVER_NAME}rc

View File

@ -43,11 +43,13 @@ class InformationManager < OpenNebulaDriver
#---------------------------------------------------------------------------
# Init the driver
#---------------------------------------------------------------------------
def initialize(remote_dir, hypervisor, num)
def initialize(hypervisor, num)
super(num, true)
@config = read_configuration
@hypervisor = hypervisor
@remote_dir = remote_dir
@remote_dir = @config['SCRIPTS_REMOTE_DIR'] || '/tmp/one'
# register actions
register_action(:MONITOR, method("action_monitor"))
@ -57,18 +59,21 @@ class InformationManager < OpenNebulaDriver
# Execute the run_probes in the remote host
#---------------------------------------------------------------------------
def action_monitor(number, host, do_update)
log_lambda=lambda do |message|
log(number, message)
end
if do_update == "1"
# Use SCP to sync:
sync_cmd = "scp -r #{REMOTES_LOCATION}/. #{host}:#{@remote_dir}"
# Use rsync to sync:
# sync_cmd = "rsync -Laz #{REMOTES_LOCATION} #{host}:#{@remote_dir}"
LocalCommand.run(sync_cmd)
else
LocalCommand.run(sync_cmd, log_lambda)
end
cmd = SSHCommand.run("#{@remote_dir}/im/run_probes #{@hypervisor}",
host)
cmd_string = "#{@remote_dir}/im/run_probes #{@hypervisor} #{host}"
cmd = SSHCommand.run(cmd_string, host, log_lambda)
if cmd.code == 0
send_message("MONITOR", RESULT[:success], number, cmd.stdout)
@ -86,9 +91,6 @@ end
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
remote_dir = ENV["IM_REMOTE_DIR"]
remote_dir = "/tmp/one" if !remote_dir
hypervisor = ARGV[0]||''
im = InformationManager.new(remote_dir, hypervisor, 15)
im = InformationManager.new(hypervisor, 15)
im.start_driver

View File

@ -16,15 +16,21 @@
# limitations under the License. #
#--------------------------------------------------------------------------- #
def print_info(name, value)
value = "0" if value.nil? or value.to_s.strip.empty?
puts "#{name}=#{value}"
end
######
# First, get all the posible info out of virsh
# TODO : use virsh freecell when available
######
nodeinfo_text = `virsh -c qemu:///system nodeinfo`
exit(-1) if $?!=0
nodeinfo_text.split(/\n/).each{|line|
if line.match('^CPU\(s\)')
if line.match('^CPU\(s\)')
$total_cpu = line.split(":")[1].strip.to_i * 100
elsif line.match('^CPU frequency')
$cpu_speed = line.split(":")[1].strip.split(" ")[0]
@ -40,10 +46,12 @@ nodeinfo_text.split(/\n/).each{|line|
NETINTERFACE = "eth1"
top_text=`top -bin2`
exit(-1) if $?!=0
top_text.gsub!(/^top.*^top.*?$/m, "") # Strip first top output
top_text.split(/\n/).each{|line|
if line.match('^Mem')
if line.match('^Mem')
line[4..-1].split(",").each{|elemento|
temp = elemento.strip.split("k ")
if temp[1] == "used"
@ -55,9 +63,9 @@ top_text.split(/\n/).each{|line|
line[7..-1].split(",").each{|elemento|
temp = elemento.strip.split("%")
if temp[1]=="id"
idle = temp[0]
$free_cpu = idle.to_f * $total_cpu.to_f / 100
$used_cpu = $total_cpu.to_f - $free_cpu
idle = temp[0]
$free_cpu = idle.to_f * $total_cpu.to_f / 100
$used_cpu = $total_cpu.to_f - $free_cpu
break
end
@ -68,6 +76,7 @@ top_text.split(/\n/).each{|line|
$free_memory=`free -k|grep "buffers\/cache"|awk '{print $4}'`
net_text=`cat /proc/net/dev`
exit(-1) if $?!=0
net_text.split(/\n/).each{|line|
if line.match("^ *#{NETINTERFACE}")
@ -78,18 +87,18 @@ net_text.split(/\n/).each{|line|
end
}
puts "HYPERVISOR=kvm"
print_info("HYPERVISOR","kvm")
puts "TOTALCPU=#{$total_cpu}"
puts "CPUSPEED=#{$cpu_speed}"
print_info("TOTALCPU",$total_cpu)
print_info("CPUSPEED",$cpu_speed)
puts "TOTALMEMORY=#{$total_memory}"
puts "USEDMEMORY=#{$used_memory}"
puts "FREEMEMORY=#{$free_memory}"
print_info("TOTALMEMORY",$total_memory)
print_info("USEDMEMORY",$used_memory)
print_info("FREEMEMORY",$free_memory)
puts "FREECPU=#{$free_cpu}"
puts "USEDCPU=#{$used_cpu}"
print_info("FREECPU",$free_cpu)
print_info("USEDCPU",$used_cpu)
puts "NETRX=#{$netrx}"
puts "NETTX=#{$nettx}"
print_info("NETRX",$netrx)
print_info("NETTX",$nettx)

View File

@ -17,28 +17,37 @@
#--------------------------------------------------------------------------- #
HYPERVISOR_DIR=$1.d
ARGUMENTS=$*
SCRIPTS_DIR=`dirname $0`
cd $SCRIPTS_DIR
function run_dir {
(
DIR=$1
cd $DIR
cd $1
for i in `ls *`;do
if [ -x "$i" ]; then
./$i
./$i $ARGUMENTS
EXIT_CODE=$?
if [ "x$EXIT_CODE" != "x0" ]; then
echo "Error executing $i" 1>&2
exit $EXIT_CODE
fi
fi
done
)
}
data=$(
run_dir 'common.d'
if [ -d "$HYPERVISOR_DIR" ]; then
run_dir $HYPERVISOR_DIR
run_dir "$HYPERVISOR_DIR"
fi
)
EXIT_CODE=$?
echo $data | tr '\n' ' '
if [ "x$EXIT_CODE" != "x0" ]; then
exit $EXIT_CODE
fi

View File

@ -1,3 +1,5 @@
#!/bin/sh
# -------------------------------------------------------------------------- #
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
@ -14,8 +16,4 @@
# 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
echo ARCH=`uname -m`

View File

@ -1,3 +1,5 @@
#!/bin/sh
# -------------------------------------------------------------------------- #
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
@ -14,10 +16,10 @@
# 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>
if [ -f /proc/cpuinfo ]; then
# Uncomment the following line to active MAD debug
#ONE_MAD_DEBUG=1
echo -n "MODELNAME=\""
grep -m 1 "model name" /proc/cpuinfo | cut -d: -f2 | sed -e 's/^ *//' | sed -e 's/$/"/'
fi

View File

@ -1,3 +1,5 @@
#!/bin/sh
# -------------------------------------------------------------------------- #
# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) #
# #
@ -14,15 +16,6 @@
# 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>
echo HOSTNAME=`uname -n`
# Uncomment the following line to active MAD debug
#ONE_MAD_DEBUG=1
# Datastore name
VMWARE_DATASTORE=datastore1
# Datacenter name
VMWARE_DATACENTER=ha-datacenter

View File

@ -21,8 +21,16 @@ require "pp"
XENTOP_PATH="/usr/sbin/xentop"
XM_PATH="/usr/sbin/xm"
def print_info(name, value)
value = "0" if value.nil? or value.to_s.strip.empty?
puts "#{name}=#{value}"
end
xentop_text=`sudo #{XENTOP_PATH} -bi2`
exit(-1) if $?!=0
xm_text=`sudo #{XM_PATH} info`
exit(-1) if $?!=0
xentop_text.gsub!(/^xentop.*^xentop.*?$/m, "") # Strip first top output
xentop_text.gsub!("no limit", "no_limit")
@ -85,13 +93,13 @@ domains_info.each {|line|
# WRITE INFO
puts "HYPERVISOR=xen"
puts "TOTALCPU=" + cpu_info[:total].round.to_s
puts "CPUSPEED=" + cpu_info[:speed]
puts "TOTALMEMORY=" + memory_info[:total].to_s
puts "FREEMEMORY=" + memory_info[:free].to_s
puts "USEDMEMORY=" + memory_info[:used].to_s
puts "USEDCPU=" + vm_info[:cpu].round.to_s
puts "FREECPU=" + (cpu_info[:total]-vm_info[:cpu]).round.to_s
puts "NETTX=" + vm_info[:nettx].to_s
puts "NETRX=" + vm_info[:netrx].to_s
print_info("HYPERVISOR","xen")
print_info("TOTALCPU",cpu_info[:total].round.to_s)
print_info("CPUSPEED",cpu_info[:speed])
print_info("TOTALMEMORY",memory_info[:total].to_s)
print_info("FREEMEMORY",memory_info[:free].to_s)
print_info("USEDMEMORY",memory_info[:used].to_s)
print_info("USEDCPU",vm_info[:cpu].round.to_s)
print_info("FREECPU",(cpu_info[:total]-vm_info[:cpu]).round.to_s)
print_info("NETTX",vm_info[:nettx].to_s)
print_info("NETRX",vm_info[:netrx].to_s)

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

@ -156,9 +156,6 @@ int Image::insert(SqlDB *db, string& error_str)
string persistent_attr;
string dev_prefix;
ostringstream tmp_hashstream;
ostringstream tmp_sourcestream;
// ---------------------------------------------------------------------
// Check default image attributes
// ---------------------------------------------------------------------
@ -230,13 +227,20 @@ int Image::insert(SqlDB *db, string& error_str)
// ------------ SOURCE (path to store the image)--------------------
tmp_hashstream << uid << ":" << name;
get_template_attribute("SOURCE", source);
tmp_sourcestream << ImagePool::source_prefix() << "/";
tmp_sourcestream << sha1_digest(tmp_hashstream.str());
if (source.empty())
{
ostringstream tmp_hashstream;
ostringstream tmp_sourcestream;
source = tmp_sourcestream.str();
tmp_hashstream << uid << ":" << name;
tmp_sourcestream << ImagePool::source_prefix() << "/";
tmp_sourcestream << sha1_digest(tmp_hashstream.str());
source = tmp_sourcestream.str();
}
state = DISABLED;

View File

@ -39,6 +39,7 @@ Mad::~Mad()
char buf[]="FINALIZE\n";
int status;
pid_t rp;
size_t retval;
if ( pid==-1)
{
@ -46,7 +47,7 @@ Mad::~Mad()
}
// Finish the driver
::write(nebula_mad_pipe, buf, strlen(buf));
retval = ::write(nebula_mad_pipe, buf, strlen(buf));
close(mad_nebula_pipe);
close(nebula_mad_pipe);
@ -67,6 +68,7 @@ int Mad::start()
{
int ne_mad_pipe[2];
int mad_ne_pipe[2];
size_t retval;
map<string,string>::iterator it;
@ -189,7 +191,7 @@ int Mad::start()
fcntl(nebula_mad_pipe, F_SETFD, FD_CLOEXEC);
fcntl(mad_nebula_pipe, F_SETFD, FD_CLOEXEC);
::write(nebula_mad_pipe, buf, strlen(buf));
retval = ::write(nebula_mad_pipe, buf, strlen(buf));
do
{
@ -289,10 +291,11 @@ int Mad::reload()
int status;
int rc;
pid_t rp;
size_t retval;
// Finish the driver
::write(nebula_mad_pipe, buf, strlen(buf));
retval = ::write(nebula_mad_pipe, buf, strlen(buf));
close(nebula_mad_pipe);
close(mad_nebula_pipe);

View File

@ -147,6 +147,7 @@ int MadManager::add(Mad *mad)
{
char buf = 'A';
int rc;
size_t retval;
if ( mad == 0 )
{
@ -166,7 +167,7 @@ int MadManager::add(Mad *mad)
mads.push_back(mad);
write(pipe_w, &buf, sizeof(char));
retval = write(pipe_w, &buf, sizeof(char));
unlock();
@ -215,6 +216,7 @@ void MadManager::listener()
int greater;
unsigned int i,j;
int rc,mrc;
size_t retval;
char c;
@ -262,7 +264,7 @@ void MadManager::listener()
{
if ( fd == pipe_r ) // Driver added, update the fd vector
{
read(fd, (void *) &c, sizeof(char));
retval = read(fd, (void *) &c, sizeof(char));
lock();

View File

@ -177,6 +177,40 @@ class ActionManager
private
def read_configuration
one_config=nil
if ENV['ONE_LOCATION']
one_config=ENV['ONE_LOCATION']+'/var/config'
else
one_config='/var/log/one/config'
end
config=Hash.new
cfg=''
begin
open(one_config) do |file|
cfg=file.read
end
cfg.split(/\n/).each do |line|
m=line.match(/^([^=]+)=(.*)$/)
if m
name=m[1].strip.upcase
value=m[2].strip
config[name]=value
end
end
rescue Exception => e
STDERR.puts "Error reading config: #{e.inspect}"
STDERR.flush
end
config
end
def delete_running_action(action_id)
@action_running.delete(action_id)
end

View File

@ -118,6 +118,21 @@ class VirtualMachineDriver < OpenNebulaDriver
send_message(ACTION[action],RESULT[result],id)
end
# -------------------------------------------------------------------------
# Execute a command associated to an action and id on localhost
# -------------------------------------------------------------------------
def local_action(command, id, action)
command_exe = LocalCommand.run(command)
if command_exe.code == 0
result = :success
else
result = :failure
end
send_message(ACTION[action],RESULT[result],id)
end
# -------------------------------------------------------------------------
# Virtual Machine Manager Protocol Actions (generic implementation
@ -168,11 +183,16 @@ private
end
def get_first_runable
action_index=@action_queue.index do |action|
if action[:args][HOST_ARG]
!@hosts.include? action[:args][HOST_ARG]
action_index=nil
@action_queue.each_with_index do |action, index|
if action[:args][HOST_ARG]
if !@hosts.include?(action[:args][HOST_ARG])
action_index=index
break
end
else
true
action_index=index
break
end
end

View File

@ -64,7 +64,7 @@ void Nebula::start()
throw runtime_error("Could not load nebula configuration file.");
}
string config_fname = log_location + "config";
string config_fname = var_location + "config";
ofstream config_file(config_fname.c_str(), ios_base::trunc & ios_base::out);
if (config_file.fail() == false)
@ -267,7 +267,7 @@ void Nebula::start()
// Close stds, we no longer need them
// -----------------------------------------------------------
fd = open("/dev/null", O_RDWR|O_CREAT);
fd = open("/dev/null", O_RDWR);
dup2(fd,0);
dup2(fd,1);

View File

@ -25,36 +25,41 @@ BIN_DIR="./bin"
JAR_DIR="./jar"
LIB_DIR="./lib"
EXA_DIR="./share/examples"
TEST_DIR="./test"
OCA_JAR=$JAR_DIR"/org.opennebula.client.jar"
JUNIT_JAR="/usr/share/java/junit4.jar"
#-------------------------------------------------------------------------------
# COMMAND LINE PARSING
#-------------------------------------------------------------------------------
usage() {
echo
echo "Usage: build.sh [-d ] [-h] [-s]"
echo "Usage: build.sh [-d ] [-h] [-s] [-t]"
echo
echo "-d: build the documentation"
echo "-s: compile the examples"
echo "-c: clean compilation files"
echo "-t: build the tests"
echo "-h: prints this help"
}
#-------------------------------------------------------------------------------
TEMP_OPT=`getopt -o hsdc -n 'build.sh' -- "$@"`
TEMP_OPT=`getopt -o hsdct -n 'build.sh' -- "$@"`
eval set -- "$TEMP_OPT"
DO_DOC="no"
DO_EXA="no"
DO_CLEAN="no"
DO_TESTS="no"
while true ; do
case "$1" in
-h) usage; exit 0;;
-d) DO_DOC="yes"; shift ;;
-s) DO_EXA="yes"; shift ;;
-t) DO_TESTS="yes"; shift ;;
-c) DO_CLEAN="yes"; shift ;;
--) shift ; break ;;
*) usage; exit 1 ;;
@ -105,12 +110,19 @@ do_examples()
javac -d $EXA_DIR -classpath $OCA_JAR:$LIB_DIR `find share/examples -name *.java`
}
do_tests()
{
echo "Compiling OpenNebula Cloud API Tests..."
javac -d $TEST_DIR -classpath $OCA_JAR:$LIB_DIR:$JUNIT_JAR `find $TEST_DIR -name *.java`
}
do_clean()
{
rm -rf $BIN_DIR > /dev/null 2>&1
mkdir -p $BIN_DIR
find share/examples -name '*.class' -delete
find test/ -name '*.class' -delete
}
if [ "$DO_CLEAN" = "yes" ] ; then
@ -128,3 +140,7 @@ if [ "$DO_EXA" = "yes" ] ; then
do_examples
fi
if [ "$DO_TESTS" = "yes" ] ; then
do_tests
fi

View File

@ -23,8 +23,6 @@ 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;

View File

@ -73,7 +73,7 @@ public abstract class PoolElement {
this.xml = xmlElement;
this.client = client;
this.id = Integer.parseInt(xpath("id"));
this.id = Integer.parseInt(xpath("ID"));
}
/**
@ -109,13 +109,18 @@ public abstract class PoolElement {
return Integer.toString(id);
}
public int id()
{
return id;
}
/**
* Returns the element's name.
* @return the element's name.
*/
public String getName()
{
return xpath("name");
return xpath("NAME");
}
/**
@ -124,7 +129,7 @@ public abstract class PoolElement {
*/
public int state()
{
String state = xpath("state");
String state = xpath("STATE");
return state != null ? Integer.parseInt( state ) : -1;
}
@ -145,7 +150,7 @@ public abstract class PoolElement {
try
{
result = xpath.evaluate(expression.toUpperCase(), xml);
result = xpath.evaluate(expression, xml);
}
catch (XPathExpressionException e) {}

View File

@ -0,0 +1,198 @@
/*******************************************************************************
* 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.cluster;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.PoolElement;
import org.opennebula.client.host.Host;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula cluster.
* It also offers static XML-RPC call wrappers.
*/
public class Cluster extends PoolElement
{
private static final String METHOD_PREFIX = "cluster.";
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 ADD = METHOD_PREFIX + "add";
private static final String REMOVE = METHOD_PREFIX + "remove";
/**
* Creates a new Image representation.
* @param id The image id.
* @param client XML-RPC Client.
*/
public Cluster(int id, Client client)
{
super(id, client);
}
/**
* @see PoolElement
*/
protected Cluster(Node xmlElement, Client client)
{
super(xmlElement, client);
}
// =================================
// Static XML-RPC methods
// =================================
/**
* Allocates a new Cluster in OpenNebula.
*
* @param client XML-RPC Client.
* @param name Name for the cluster we want to add.
* @return If successful the message contains the associated
* id generated for this Cluster.
*/
public static OneResponse allocate(Client client, String name)
{
return client.call(ALLOCATE, name);
}
/**
* Retrieves the information of the given Cluster.
*
* @param client XML-RPC Client.
* @param id The cluster id for the cluster 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 cluster from OpenNebula.
*
* @param client XML-RPC Client.
* @param id The cluster id of the target cluster we want to delete.
* @return A encapsulated response.
*/
public static OneResponse delete(Client client, int id)
{
return client.call(DELETE, id);
}
/**
* Adds a host to a cluster.
*
* @param client XML-RPC Client.
* @param id The cluster id of the cluster where the host will be assigned.
* @param hid The host id (hid) of the host.
* @return If an error occurs the error message contains the reason.
*/
public static OneResponse add(Client client, int id, int hid)
{
return client.call(ADD, hid, id);
}
/**
* Removes a host from its cluster.
*
* @param client XML-RPC Client.
* @param hid The host id (hid) of the host.
* @return If an error occurs the error message contains the reason.
*/
public static OneResponse remove(Client client, int hid)
{
return client.call(REMOVE, hid);
}
// =================================
// Instanced object XML-RPC methods
// =================================
/**
* Retrieves the information of the Cluster.
*
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public OneResponse info()
{
OneResponse response = info(client, id);
super.processInfo(response);
return response;
}
/**
* Deletes the cluster from OpenNebula.
*
* @return A encapsulated response.
*/
public OneResponse delete()
{
return delete(client, id);
}
/**
* Adds a host to the cluster.
*
* @param hid The host id (hid) of the host.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse add(int hid)
{
return add(client, id, hid);
}
/**
* Adds a host to the cluster.
*
* @param host The Host to add.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse add(Host host)
{
return add(client, id, host.id());
}
/**
* Removes a host from its cluster.
*
* @param hid The host id (hid) of the host.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse remove(int hid)
{
return remove(client, hid);
}
/**
* Removes a host from its cluster.
*
* @param host The Host to remove.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse remove(Host host)
{
return remove(client, host.id());
}
}

View File

@ -0,0 +1,96 @@
/*******************************************************************************
* 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.cluster;
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 Cluster pool.
* It also offers static XML-RPC call wrappers.
*/
public class ClusterPool extends Pool implements Iterable<Cluster>
{
private static final String ELEMENT_NAME = "CLUSTER";
private static final String INFO_METHOD = "clusterpool.info";
/**
* Creates a new Image pool
*
* @param client XML-RPC Client.
*/
public ClusterPool(Client client)
{
super(ELEMENT_NAME, client);
}
/* (non-Javadoc)
* @see org.opennebula.client.Pool#factory(org.w3c.dom.Node)
*/
@Override
public PoolElement factory(Node node)
{
return new Cluster(node, client);
}
/**
* Returns the Cluster pool information.
*
* @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 Cluster pool.
*
* @see ClusterPool#info(Client)
*/
public OneResponse info()
{
OneResponse response = info(client);
super.processInfo(response);
return response;
}
public Iterator<Cluster> iterator()
{
AbstractList<Cluster> ab = new AbstractList<Cluster>()
{
public int size()
{
return getLength();
}
public Cluster get(int index)
{
return (Cluster) item(index);
}
};
return ab.iterator();
}
}

View File

@ -161,6 +161,26 @@ public class Host extends PoolElement{
return enable(client, id, enable);
}
/**
* Enables the host.
*
* @return A encapsulated response.
*/
public OneResponse enable()
{
return enable(true);
}
/**
* Disables the host
*
* @return A encapsulated response.
*/
public OneResponse disable()
{
return enable(false);
}
// =================================
// Helpers
// =================================
@ -197,4 +217,24 @@ public class Host extends PoolElement{
else
return "on";
}
/**
* Returns true if the host is enabled.
*
* @return True if the host is enabled.
*/
public boolean isEnabled()
{
return state() != 4;
}
/**
* Returns the name of the cluster this host is assigned to.
*
* @return The name of the cluster this host is assigned to.
*/
public String getCluster()
{
return xpath("CLUSTER");
}
}

View File

@ -0,0 +1,362 @@
/*******************************************************************************
* 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.image;
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 image.
* It also offers static XML-RPC call wrappers.
*/
public class Image extends PoolElement
{
private static final String METHOD_PREFIX = "image.";
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 UPDATE = METHOD_PREFIX + "update";
private static final String RMATTR = METHOD_PREFIX + "rmattr";
private static final String ENABLE = METHOD_PREFIX + "enable";
private static final String PUBLISH = METHOD_PREFIX + "publish";
private static final String[] IMAGE_STATES =
{"INIT", "READY", "USED", "DISABLED"};
private static final String[] SHORT_IMAGE_STATES =
{"init", "rdy", "used", "disa"};
private static final String[] IMAGE_TYPES =
{"OS", "CDROM", "DATABLOCK"};
private static final String[] SHORT_IMAGE_TYPES =
{"OS", "CD", "DB"};
/**
* Creates a new Image representation.
* @param id The image id.
* @param client XML-RPC Client.
*/
public Image(int id, Client client)
{
super(id, client);
}
/**
* @see PoolElement
*/
protected Image(Node xmlElement, Client client)
{
super(xmlElement, client);
}
// =================================
// Static XML-RPC methods
// =================================
/**
* Allocates a new Image in OpenNebula.
*
* @param client XML-RPC Client.
* @param description A string containing the template of the image.
* @return If successful the message contains the associated
* id generated for this Image.
*/
public static OneResponse allocate(Client client, String description)
{
return client.call(ALLOCATE, description);
}
/**
* Retrieves the information of the given Image.
*
* @param client XML-RPC Client.
* @param id The image id for the image 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 an image from OpenNebula.
*
* @param client XML-RPC Client.
* @param id The image id of the target image we want to delete.
* @return A encapsulated response.
*/
public static OneResponse delete(Client client, int id)
{
return client.call(DELETE, id);
}
/**
* Modifies an image attribute.
*
* @param client XML-RPC Client.
* @param id The image id of the target image we want to modify.
* @param att_name The name of the attribute to update.
* @param att_val The new value for the attribute.
* @return If successful the message contains the image id.
*/
public static OneResponse update(Client client, int id,
String att_name, String att_val)
{
return client.call(UPDATE, id, att_name, att_val);
}
/**
* Removes an image attribute.
*
* @param client XML-RPC Client.
* @param id The image id of the target image we want to modify.
* @param att_name The name of the attribute to remove.
* @return If successful the message contains the image id.
*/
public static OneResponse rmattr(Client client, int id, String att_name)
{
return client.call(RMATTR, id, att_name);
}
/**
* Enables or disables an image.
*
* @param client XML-RPC Client.
* @param id The image id of the target image we want to modify.
* @param enable True for enabling, false for disabling.
* @return If successful the message contains the image id.
*/
public static OneResponse enable(Client client, int id, boolean enable)
{
return client.call(ENABLE, id, enable);
}
/**
* Publishes or unpublishes an image.
*
* @param client XML-RPC Client.
* @param id The image id of the target image we want to modify.
* @param publish True for publishing, false for unpublishing.
* @return If successful the message contains the image id.
*/
public static OneResponse publish(Client client, int id, boolean publish)
{
return client.call(PUBLISH, id, publish);
}
// =================================
// Instanced object XML-RPC methods
// =================================
/**
* Retrieves the information of the Image.
*
* @return If successful the message contains the string
* with the information returned by OpenNebula.
*/
public OneResponse info()
{
OneResponse response = info(client, id);
super.processInfo(response);
return response;
}
/**
* Deletes the image from OpenNebula.
*
* @return A encapsulated response.
*/
public OneResponse delete()
{
return delete(client, id);
}
/**
* Modifies an image attribute.
*
* @param att_name The name of the attribute to update.
* @param att_val The new value for the attribute.
* @return If successful the message contains the image id.
*/
public OneResponse update(String att_name, String att_val)
{
return update(client, id, att_name, att_val);
}
/**
* Removes an image attribute.
*
* @param att_name The name of the attribute to remove.
* @return If successful the message contains the image id.
*/
public OneResponse rmattr(String att_name)
{
return rmattr(client, id, att_name);
}
/**
* Enables or disables the image.
*
* @param enable True for enabling, false for disabling.
* @return If successful the message contains the image id.
*/
public OneResponse enable(boolean enable)
{
return enable(client, id, enable);
}
/**
* Enables the image.
*
* @return If successful the message contains the image id.
*/
public OneResponse enable()
{
return enable(true);
}
/**
* Disables the image.
*
* @return If successful the message contains the image id.
*/
public OneResponse disable()
{
return enable(false);
}
/**
* Publishes or unpublishes the image.
*
* @param publish True for publishing, false for unpublishing.
* @return If successful the message contains the image id.
*/
public OneResponse publish(boolean publish)
{
return publish(client, id, publish);
}
/**
* Publishes the image.
*
* @return If successful the message contains the image id.
*/
public OneResponse publish()
{
return publish(true);
}
/**
* Unpublishes the image.
*
* @return If successful the message contains the image id.
*/
public OneResponse unpublish()
{
return publish(false);
}
// =================================
// Helpers
// =================================
/**
* Returns the state of the Image.
* <br/>
* The method {@link Image#info()} must be called before.
*
* @return The state of the Image.
*/
public String stateString()
{
int state = state();
return state != -1 ? IMAGE_STATES[state] : null;
}
/**
* Returns the short length string state of the Image.
* <br/>
* The method {@link Image#info()} must be called before.
*
* @return The short length string state of the Image.
*/
public String shortStateStr()
{
int state = state();
return state != -1 ? SHORT_IMAGE_STATES[state] : null;
}
/**
* Returns the type of the Image.
*
* @return The type of the Image.
*/
public int type()
{
String state = xpath("TYPE");
return state != null ? Integer.parseInt( state ) : -1;
}
/**
* Returns the type of the Image as a String.
*
* @return The type of the Image as a String.
*/
public String typeStr()
{
int type = type();
return type != -1 ? IMAGE_TYPES[type] : null;
}
/**
* Returns the type of the Image as a short String.
*
* @return The type of the Image as a short String.
*/
public String shortTypeStr()
{
int type = type();
return type != -1 ? SHORT_IMAGE_TYPES[type] : null;
}
/**
* Returns true if the image is enabled.
*
* @return True if the image is enabled.
*/
public boolean isEnabled()
{
return state() != 3;
}
/**
* Returns true if the image is public.
*
* @return True if the image is public.
*/
public boolean isPublic()
{
String isPub = xpath("PUBLIC");
return isPub != null && isPub.equals("1");
}
}

View File

@ -0,0 +1,133 @@
/*******************************************************************************
* 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.image;
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.opennebula.client.vm.VirtualMachinePool;
import org.w3c.dom.Node;
/**
* This class represents an OpenNebula Image pool.
* It also offers static XML-RPC call wrappers.
*/
public class ImagePool extends Pool implements Iterable<Image>
{
private static final String ELEMENT_NAME = "IMAGE";
private static final String INFO_METHOD = "imagepool.info";
private int filter;
/**
* Creates a new Image pool with the default filter flag value
* set to 0 (Images belonging to user with UID 0)
*
* @param client XML-RPC Client.
*
* @see VirtualMachinePool#VirtualMachinePool(Client, int)
*/
public ImagePool(Client client)
{
super(ELEMENT_NAME, client);
this.filter = 0;
}
/**
* Creates a new Image pool.
*
* @param client XML-RPC Client.
* @param filter Filter flag used by default in the method
* {@link ImagePool#info()}. Possible values:
* <ul>
* <li><= -2: All Images</li>
* <li>-1: Connected user's Images</li>
* <li>>= 0: UID User's VMs</li>
* </ul>
*/
public ImagePool(Client client, int filter)
{
super(ELEMENT_NAME, client);
this.filter = filter;
}
/* (non-Javadoc)
* @see org.opennebula.client.Pool#factory(org.w3c.dom.Node)
*/
@Override
public PoolElement factory(Node node)
{
return new Image(node, client);
}
/**
* Retrieves all or part of the images in the pool.
*
* @param client XML-RPC Client.
* @param filter Filter flag used by default in the method
* {@link ImagePool#info()}. Possible values:
* <ul>
* <li><= -2: All Images</li>
* <li>-1: Connected user's Images</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
* Images in the pool. The filter used is the one set in
* the constructor.
*
* @see ImagePool#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<Image> iterator()
{
AbstractList<Image> ab = new AbstractList<Image>()
{
public int size()
{
return getLength();
}
public Image get(int index)
{
return (Image) item(index);
}
};
return ab.iterator();
}
}

View File

@ -31,6 +31,7 @@ public class User extends PoolElement{
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 PASSWD = METHOD_PREFIX + "passwd";
/**
* Creates a new User representation.
@ -76,15 +77,15 @@ public class User extends PoolElement{
*
* @param client XML-RPC Client.
* @param id The user id (uid) for the user to
* retrieve the information from.
* retrieve the information from.
* @return if successful the message contains the
* string with the information about the user returned by OpenNebula.
* 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.
*
@ -97,10 +98,23 @@ public class User extends PoolElement{
return client.call(DELETE, id);
}
/**
* Changes the password for the given user.
*
* @param client XML-RPC Client.
* @param id The user id (uid) of the target user we want to modify.
* @param password The new password.
* @return If an error occurs the error message contains the reason.
*/
public static OneResponse passwd(Client client, int id, String password)
{
return client.call(PASSWD, id, password);
}
// =================================
// Instanced object XML-RPC methods
// =================================
/**
* Loads the xml representation of the user.
* The info is also stored internally.
@ -110,7 +124,6 @@ public class User extends PoolElement{
public OneResponse info()
{
OneResponse response = info(client, id);
super.processInfo(response);
return response;
@ -125,4 +138,30 @@ public class User extends PoolElement{
{
return delete(client, id);
}
/**
* Changes the password for the user.
*
* @param password The new password.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse passwd(String password)
{
return passwd(client, id, password);
}
// =================================
// Helpers
// =================================
/**
* Returns true if the user is enabled.
*
* @return True if the user is enabled.
*/
public boolean isEnabled()
{
String enabled = xpath("ENABLED");
return enabled != null && enabled.equals("1");
}
}

View File

@ -33,6 +33,7 @@ public class VirtualMachine extends PoolElement{
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 SAVEDISK = METHOD_PREFIX + "savedisk";
private static final String[] VM_STATES =
{
@ -216,6 +217,18 @@ public class VirtualMachine extends PoolElement{
return client.call(MIGRATE, id, hostId, live);
}
/**
* Sets the specified vm's disk to be saved in a new image when the
* VirtualMachine shutdowns.
*
* @param diskId ID of the disk to be saved.
* @param imageId ID of the image where the disk will be saved.
* @return If an error occurs the error message contains the reason.
*/
public OneResponse savedisk(int diskId, int imageId)
{
return client.call(SAVEDISK, diskId, imageId);
}
// =================================
// Helpers
@ -391,4 +404,5 @@ public class VirtualMachine extends PoolElement{
}
return shortStateStr;
}
}

View File

@ -31,6 +31,7 @@ public class VirtualNetwork extends PoolElement{
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 PUBLISH = METHOD_PREFIX + "publish";
/**
@ -96,6 +97,18 @@ public class VirtualNetwork extends PoolElement{
return client.call(DELETE, id);
}
/**
* Publishes or unpublishes a virtual network.
*
* @param client XML-RPC Client.
* @param id The virtual network id (nid) of the target network.
* @param publish True for publishing, false for unpublishing.
* @return If successful the message contains the image id.
*/
public static OneResponse publish(Client client, int id, boolean publish)
{
return client.call(PUBLISH, id, publish);
}
// =================================
// Instanced object XML-RPC methods
@ -123,4 +136,50 @@ public class VirtualNetwork extends PoolElement{
{
return delete(client, id);
}
/**
* Publishes or unpublishes the virtual network.
*
* @param publish True for publishing, false for unpublishing.
* @return If successful the message contains the image id.
*/
public OneResponse publish(boolean publish)
{
return publish(client, id, publish);
}
/**
* Publishes the virtual network.
*
* @return If successful the message contains the image id.
*/
public OneResponse publish()
{
return publish(true);
}
/**
* Unpublishes the virtual network.
*
* @return If successful the message contains the image id.
*/
public OneResponse unpublish()
{
return publish(false);
}
// =================================
// Helpers
// =================================
/**
* Returns true if the Virtual Network is public.
*
* @return True if the Virtual Network is public.
*/
public boolean isPublic()
{
String isPub = xpath("PUBLIC");
return isPub != null && isPub.equals("1");
}
}

View File

@ -0,0 +1,166 @@
/*******************************************************************************
* 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 static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.cluster.Cluster;
import org.opennebula.client.cluster.ClusterPool;
import org.opennebula.client.host.Host;
public class ClusterTest
{
private static Cluster cluster;
private static ClusterPool clusterPool;
private static Host host;
private static Client client;
private static OneResponse res;
private static String name = "new_test_cluster";
private static int hid = -1;
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
client = new Client();
clusterPool = new ClusterPool(client);
res = Host.allocate(client, "new_test_host",
"im_dummy", "vmm_dummy", "tm_dummy");
try{
hid = Integer.parseInt( res.getMessage() );
}catch(NumberFormatException e)
{
System.err.println("Test initilization failed (setUpBeforeClass).");
}
host = new Host(hid, client);
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
res = Cluster.allocate(client, name);
int clid = Integer.parseInt(res.getMessage());
cluster = new Cluster(clid, client);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
cluster.delete();
}
@Test
public void allocate()
{
String allocate_name = "allocation_test";
res = Cluster.allocate(client, allocate_name);
assertTrue( !res.isError() );
clusterPool.info();
boolean found = false;
for(Cluster c : clusterPool)
{
found = found || c.getName().equals(allocate_name);
}
assertTrue( found );
}
@Test
public void update()
{
res = cluster.info();
assertTrue( !res.isError() );
// assertTrue( cluster.getId().equals("1") );
// assertTrue( cluster.id() == 1 );
assertTrue( cluster.getName().equals(name) );
}
@Test
public void addHost()
{
res = cluster.add(hid);
assertTrue( !res.isError() );
res = host.info();
assertTrue( !res.isError() );
assertTrue( host.getCluster().equals(name) );
}
@Test
public void removeHost()
{
assertTrue( hid > -1 );
res = cluster.remove(hid);
assertTrue( !res.isError() );
res = host.info();
assertTrue( !res.isError() );
assertTrue( host.getCluster().equals("default") );
}
@Test
public void attributes()
{
res = cluster.info();
assertTrue( !res.isError() );
// assertTrue( cluster.xpath("ID").equals("1") );
assertTrue( cluster.xpath("NAME").equals(name) );
}
@Test
public void delete()
{
res = cluster.delete();
assertTrue( !res.isError() );
res = cluster.info();
assertTrue( res.isError() );
}
}

View File

@ -0,0 +1,192 @@
/*******************************************************************************
* 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 static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.host.Host;
import org.opennebula.client.host.HostPool;
import org.w3c.dom.Node;
public class HostTest
{
class HostXML extends Host
{
public HostXML(Node node, Client client){ super(node, client); }
}
private static Host host;
private static HostPool hostPool;
private static Client client;
private OneResponse res;
private static String name = "new_test_host";
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
client = new Client();
hostPool = new HostPool(client);
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
res = Host.allocate(client, name, "im_dummy", "vmm_dummy", "tm_dummy");
int hid = !res.isError() ? Integer.parseInt(res.getMessage()) : -1;
host = new Host(hid, client);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
host.delete();
}
@Test
public void allocate()
{
String name = "allocate_test";
res = Host.allocate(client, name, "im_dummy", "vmm_dummy", "tm_dummy");
assertTrue( !res.isError() );
// assertTrue( res.getMessage().equals("0") );
hostPool.info();
boolean found = false;
for(Host h : hostPool)
{
found = found || h.getName().equals(name);
}
assertTrue( found );
}
@Test
public void update()
{
res = host.info();
assertTrue( !res.isError() );
// assertTrue( host.getId().equals("0") );
assertTrue( host.id() >= 0 );
assertTrue( host.shortStateStr().equals("on") );
}
@Test
public void enable()
{
res = host.enable();
assertTrue( !res.isError() );
host.info();
assertTrue( host.isEnabled() );
}
@Test
public void disable()
{
res = host.disable();
assertTrue( !res.isError() );
host.info();
assertTrue( !host.isEnabled() );
}
@Test
public void delete()
{
String name = host.getName();
res = host.delete();
assertTrue( !res.isError() );
res = host.info();
assertTrue( res.isError() );
res = hostPool.info();
assertTrue( !res.isError() );
boolean found = false;
for(Host h : hostPool)
{
found = found || h.getName().equals(name);
}
assertTrue( !found );
}
/*
@Test
public void attributes()
{
DocumentBuilder builder;
Document doc;
Element xml;
try
{
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse( new File("./fixtures/host.xml") );
xml = doc.getDocumentElement();
host = new HostXML(xml, client);
assertTrue( host.xpath("ID").equals("7") );
assertTrue( host.xpath("NAME").equals("dummyhost") );
assertTrue( host.xpath("STATE").equals("2") );
assertTrue( host.xpath("IM_MAD").equals("im_dummy") );
assertTrue( host.xpath("LAST_MON_TIME").equals("1277733596") );
assertTrue( host.xpath("HOST_SHARE/MEM_USAGE").equals("1572864") );
assertTrue( host.xpath("HOST_SHARE/CPU_USAGE").equals("300") );
assertTrue( host.xpath("HOST_SHARE/FREE_CPU").equals("800") );
assertTrue( host.xpath("HOST_SHARE/RUNNING_VMS").equals("3") );
assertTrue( host.xpath("TEMPLATE/CPUSPEED").equals("2.2GHz") );
assertTrue( host.xpath("TEMPLATE/HYPERVISOR").equals("dummy") );
assertTrue( host.xpath("TEMPLATE/TOTALMEMORY").equals("16777216") );
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
}

View File

@ -0,0 +1,209 @@
/*******************************************************************************
* 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 static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.image.*;
public class ImageTest
{
private static Image image;
private static ImagePool imagePool;
private static Client client;
private static OneResponse res;
private static String name = "new_test_img";
private static String template =
"NAME = \"" + name + "\"\n" +
"ATT1 = \"val1\"";
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
client = new Client();
imagePool = new ImagePool(client);
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
res = Image.allocate(client, template);
int imgid = res.isError() ? -1 : Integer.parseInt(res.getMessage());
image = new Image(imgid, client);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
image.delete();
}
@Test
public void allocate()
{
image.delete();
res = Image.allocate(client, template);
assertTrue( !res.isError() );
int imgid = res.isError() ? -1 : Integer.parseInt(res.getMessage());
image = new Image(imgid, client);
imagePool.info();
boolean found = false;
for(Image img : imagePool)
{
found = found || img.getName().equals(name);
}
assertTrue( found );
}
@Test
public void info()
{
res = image.info();
assertTrue( !res.isError() );
// assertTrue( image.getId().equals("0") );
// assertTrue( image.id() == 0 );
assertTrue( image.getName().equals(name) );
}
@Test
public void update()
{
// Update an existing att.
res = image.update("ATT1", "new_val_1");
assertTrue( !res.isError() );
res = image.info();
assertTrue( !res.isError() );
assertTrue( image.xpath("TEMPLATE/ATT1").equals("new_val_1") );
// Create a new att.
res = image.update("ATT2", "new_val_2");
assertTrue( !res.isError() );
res = image.info();
assertTrue( !res.isError() );
assertTrue( image.xpath("TEMPLATE/ATT2").equals("new_val_2") );
}
@Test
public void rmattr()
{
res = image.rmattr("ATT1");
assertTrue( !res.isError() );
res = image.info();
assertTrue( !res.isError() );
assertTrue( image.xpath("ATT1").equals("") );
}
@Test
public void enable()
{
res = image.enable();
assertTrue( !res.isError() );
image.info();
assertTrue( image.isEnabled() );
}
@Test
public void disable()
{
res = image.disable();
assertTrue( !res.isError() );
image.info();
assertTrue( !image.isEnabled() );
}
@Test
public void publish()
{
res = image.publish();
assertTrue( !res.isError() );
image.info();
assertTrue( image.isPublic() );
}
@Test
public void unpublish()
{
res = image.unpublish();
assertTrue( !res.isError() );
image.info();
assertTrue( !image.isPublic() );
}
@Test
public void attributes()
{
res = image.info();
assertTrue( !res.isError() );
// assertTrue( image.xpath("ID").equals("0") );
assertTrue( image.xpath("NAME").equals(name) );
}
// @Test
public void delete()
{
res = image.delete();
assertTrue( !res.isError() );
res = image.info();
assertTrue( res.isError() );
}
}

View File

@ -0,0 +1,75 @@
/*******************************************************************************
* 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 static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.opennebula.client.Client;
public class SessionTest {
@Test
public void createSession()
{
Client oneClient = null;
try
{
oneClient = new Client();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
assertNotNull(oneClient);
}
@Test
public void wrong_token()
{
Client oneClient = null;
try
{
// The secret string should be user:password. The url is null, so it
// will be set to default.
oneClient = new Client("wrong_password_token",null);
}
catch (Exception e)
{
// System.out.println(e.getMessage());
}
assertNull("Client should complain about the wrong token", oneClient);
}
@Test
public void wrong_url()
{
Client oneClient = null;
try
{
// The HTTP is misspelled
oneClient = new Client(null,"HTP://localhost:2633/RPC2");
}
catch (Exception e)
{
// System.out.println(e.getMessage());
}
assertNull("Client should complain about misspelled url", oneClient);
}
}

View File

@ -0,0 +1,127 @@
/*******************************************************************************
* 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 static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.user.User;
import org.opennebula.client.user.UserPool;
public class UserTest
{
private static User user;
private static UserPool userPool;
private static Client client;
private static OneResponse res;
private static String name = "new_test_user";
private static String password = "new_test_password";
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
client = new Client();
userPool = new UserPool(client);
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
res = User.allocate(client, name, password);
int uid = res.isError() ? -1 : Integer.parseInt(res.getMessage());
user = new User(uid, client);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
user.delete();
}
@Test
public void allocate()
{
userPool.info();
boolean found = false;
for(User u : userPool)
{
found = found || u.getName().equals(name);
}
assertTrue( found );
}
@Test
public void update()
{
res = user.info();
assertTrue( res.getErrorMessage(), !res.isError() );
assertTrue( user.id() >= 0 );
assertTrue( user.getName().equals(name) );
}
@Test
public void attributes()
{
res = user.info();
assertTrue( res.getErrorMessage(), !res.isError() );
assertTrue( user.xpath("NAME").equals(name) );
assertTrue( user.xpath("ENABLED").equals("1") );
}
@Test
public void delete()
{
res = user.info();
assertTrue( res.getErrorMessage(), !res.isError() );
assertTrue( user.isEnabled() );
res = user.delete();
assertTrue( res.getErrorMessage(), !res.isError() );
res = user.info();
assertTrue( res.getErrorMessage(), res.isError() );
}
}

View File

@ -0,0 +1,248 @@
/*******************************************************************************
* 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 static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.host.Host;
import org.opennebula.client.vm.VirtualMachine;
import org.opennebula.client.vm.VirtualMachinePool;
public class VirtualMachineTest
{
private static VirtualMachine vm;
private static VirtualMachinePool vmPool;
private static Client client;
private static int hid_A, hid_B;
private static OneResponse res;
private static String name = "new_test_machine";
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
client = new Client();
vmPool = new VirtualMachinePool(client);
res = Host.allocate(client, "host_A",
"im_dummy", "vmm_dummy", "tm_dummy");
hid_A = Integer.parseInt( res.getMessage() );
res = Host.allocate(client, "host_B",
"im_dummy", "vmm_dummy", "tm_dummy");
hid_B = Integer.parseInt( res.getMessage() );
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
String template = "NAME = " + name + "\n"+
"MEMORY = 512\n" +
"CONTEXT = [DNS = 192.169.1.4]";
res = VirtualMachine.allocate(client, template);
int vmid = !res.isError() ? Integer.parseInt(res.getMessage()) : -1;
vm = new VirtualMachine(vmid, client);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
vm.finalizeVM();
}
@Test
public void allocate()
{
// String template = "NAME = " + name + "\n"+
// "MEMORY = 512\n" +
// "CONTEXT = [DNS = 192.169.1.4]";
//
// res = VirtualMachine.allocate(client, template);
// assertTrue( !res.isError() );
// assertTrue( res.getMessage().equals("0") );
vmPool.info();
boolean found = false;
for(VirtualMachine vm : vmPool)
{
found = found || vm.getName().equals(name);
}
assertTrue( found );
}
@Test
public void update()
{
res = vm.info();
assertTrue( !res.isError() );
// assertTrue( vm.getId().equals("0") );
// assertTrue( vm.id() == 0 );
assertTrue( vm.getName().equals(name) );
}
@Test
public void hold()
{
res = vm.hold();
assertTrue( !res.isError() );
}
@Test
public void release()
{
vm.hold();
res = vm.release();
assertTrue( !res.isError() );
}
@Test
public void deploy()
{
res = vm.deploy(hid_A);
assertTrue( !res.isError() );
}
@Test
public void migrate()
{
vm.deploy(hid_A);
try{ Thread.sleep(5000); } catch (Exception e){}
res = vm.migrate(hid_B);
assertTrue( !res.isError() );
}
@Test
public void liveMigrate()
{
vm.deploy(hid_A);
try{ Thread.sleep(5000); } catch (Exception e){}
res = vm.liveMigrate(hid_B);
assertTrue( !res.isError() );
}
@Test
public void shutdown()
{
vm.deploy(hid_A);
try{ Thread.sleep(5000); } catch (Exception e){}
res = vm.shutdown();
assertTrue( !res.isError() );
}
@Test
public void cancel()
{
vm.deploy(hid_A);
try{ Thread.sleep(5000); } catch (Exception e){}
res = vm.cancel();
assertTrue( !res.isError() );
}
@Test
public void stop()
{
vm.deploy(hid_A);
try{ Thread.sleep(5000); } catch (Exception e){}
res = vm.stop();
assertTrue( !res.isError() );
}
@Test
public void suspend()
{
vm.deploy(hid_A);
try{ Thread.sleep(5000); } catch (Exception e){}
res = vm.suspend();
assertTrue( !res.isError() );
}
@Test
public void resume()
{
vm.deploy(hid_A);
try{ Thread.sleep(5000); } catch (Exception e){}
vm.suspend();
try{ Thread.sleep(5000); } catch (Exception e){}
res = vm.resume();
assertTrue( !res.isError() );
}
@Test
public void finalize()
{
res = vm.finalizeVM();
assertTrue( !res.isError() );
}
@Test
public void restart()
{
// TODO
}
@Test
public void attributes()
{
res = vm.info();
assertTrue( !res.isError() );
assertTrue( vm.xpath("NAME").equals(name) );
assertTrue( vm.xpath("TEMPLATE/MEMORY").equals("512") );
// assertTrue( vm.xpath("ID").equals("0") );
assertTrue( vm.xpath("TEMPLATE/MEMORY").equals("512") );
assertTrue( vm.xpath("TEMPLATE/CONTEXT/DNS").equals("192.169.1.4") );
}
}

Some files were not shown because too many files have changed in this diff Show More