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

Merge branch 'master' of git.opennebula.org:one

This commit is contained in:
Tino Vázquez 2011-05-05 15:07:48 +02:00
commit 795dc66059
135 changed files with 7066 additions and 1786 deletions

View File

@ -63,6 +63,7 @@ main_env.Append(LIBPATH=[
cwd+'/src/pool',
cwd+'/src/template',
cwd+'/src/vm',
cwd+'/src/vm_template',
cwd+'/src/vmm',
cwd+'/src/lcm',
cwd+'/src/tm',
@ -190,6 +191,7 @@ build_scripts=[
'src/nebula/SConstruct',
'src/pool/SConstruct',
'src/vm/SConstruct',
'src/vm_template/SConstruct',
'src/vmm/SConstruct',
'src/lcm/SConstruct',
'src/rm/SConstruct',
@ -240,6 +242,7 @@ if testing=='yes':
'src/vm/test/SConstruct',
'src/vnm/test/SConstruct',
'src/xml/test/SConstruct',
'src/vm_template/test/SConstruct',
])
else:
main_env.Append(testing='no')

View File

@ -82,8 +82,12 @@ public:
*/
virtual AttributeType type() = 0;
private:
/**
* Clones the current attribute
*/
virtual Attribute* clone() const = 0;
protected:
/**
* The attribute name.
*/
@ -107,6 +111,11 @@ public:
SingleAttribute(const string& name, const string& value):
Attribute(name),attribute_value(value){};
SingleAttribute(const SingleAttribute& sa):Attribute(sa.attribute_name)
{
attribute_value = sa.attribute_value;
};
~SingleAttribute(){};
/**
@ -173,6 +182,14 @@ public:
return SIMPLE;
};
/**
* Clones the current attribute
*/
Attribute* clone() const
{
return new SingleAttribute(*this);
};
private:
string attribute_value;
@ -195,6 +212,11 @@ public:
VectorAttribute(const string& name,const map<string,string>& value):
Attribute(name),attribute_value(value){};
VectorAttribute(const VectorAttribute& va):Attribute(va.attribute_name)
{
attribute_value = va.attribute_value;
};
~VectorAttribute(){};
/**
@ -256,6 +278,14 @@ public:
return VECTOR;
};
/**
* Clones the current attribute
*/
Attribute* clone() const
{
return new VectorAttribute(*this);
};
private:
static const char * magic_sep;

View File

@ -276,11 +276,12 @@ public:
*/
enum Operation
{
CREATE, /** Authorization to create an object (host, vm, net, image)*/
DELETE, /** Authorization to delete an object */
USE, /** Authorization to use an object */
MANAGE, /** Authorization to manage an object */
INFO /** Authorization to view an object */
CREATE, /** Authorization to create an object */
DELETE, /** Authorization to delete an object */
USE, /** Authorization to use an object */
MANAGE, /** Authorization to manage an object */
INFO, /** Authorization to view an object */
INSTANTIATE /** Authorization to instantiate a VM from a TEMPLATE */
};
/**
@ -293,7 +294,8 @@ public:
NET,
IMAGE,
USER,
CLUSTER
CLUSTER,
TEMPLATE
};
/**

View File

@ -26,6 +26,8 @@
#include <unistd.h>
#include "Log.h"
using namespace std;
/**
@ -68,12 +70,11 @@ protected:
{
string str;
const char * cstr;
size_t retval;
str = os.str();
cstr = str.c_str();
retval = ::write(nebula_mad_pipe, cstr, str.size());
::write(nebula_mad_pipe, cstr, str.size());
};
/**
@ -89,6 +90,32 @@ protected:
write(os);
};
/**
* Sets the log message type as specify by the driver.
* @param first character of the type string
* @return the message type
*/
Log::MessageType log_type(const char r)
{
Log::MessageType lt;
switch (r)
{
case 'E':
lt = Log::ERROR;
break;
case 'I':
lt = Log::INFO;
break;
case 'D':
lt = Log::DEBUG;
break;
default:
lt = Log::INFO;
}
return lt;
}
private:
friend class MadManager;
@ -141,7 +168,7 @@ private:
* @return 0 on success
*/
int reload();
/**
* Implements the driver specific protocol, this function should trigger
* actions on the associated manager.

View File

@ -25,6 +25,7 @@
#include "VirtualNetworkPool.h"
#include "HostPool.h"
#include "UserPool.h"
#include "VMTemplatePool.h"
#include "VirtualMachineManager.h"
#include "LifeCycleManager.h"
@ -81,6 +82,11 @@ public:
return cpool;
};
VMTemplatePool * get_tpool()
{
return tpool;
};
// --------------------------------------------------------------
// Manager Accessors
// --------------------------------------------------------------
@ -233,9 +239,9 @@ private:
//Constructors and = are private to only access the class through instance
// -----------------------------------------------------------------------
Nebula():nebula_configuration(0),db(0),vmpool(0),hpool(0),vnpool(0),upool(0),
ipool(0),cpool(0),lcm(0),vmm(0),im(0),tm(0),dm(0),rm(0),hm(0),authm(0),
imagem(0)
Nebula():nebula_configuration(0),db(0),vmpool(0),hpool(0),vnpool(0),
upool(0),ipool(0),cpool(0),tpool(0),lcm(0),vmm(0),im(0),tm(0),dm(0),
rm(0),hm(0),authm(0),imagem(0)
{
const char * nl = getenv("ONE_LOCATION");
@ -300,6 +306,11 @@ private:
delete cpool;
}
if ( tpool != 0)
{
delete tpool;
}
if ( vmm != 0)
{
delete vmm;
@ -392,6 +403,7 @@ private:
UserPool * upool;
ImagePool * ipool;
ClusterPool * cpool;
VMTemplatePool * tpool;
// ---------------------------------------------------------------
// Nebula Managers

View File

@ -217,6 +217,13 @@ public:
return obj_template->erase(name);
}
/**
* Sets an error message for the VM in the template
* @param message
* @return 0 on success
*/
void set_template_error_message(const string& message);
protected:
/**
@ -318,6 +325,11 @@ private:
* Pointer to the SQL table for the PoolObjectSQL
*/
const char * table;
/**
* Name for the error messages attribute
*/
static const char * error_attribute_name;
};
#endif /*POOL_OBJECT_SQL_H_*/

View File

@ -24,6 +24,7 @@
#include "VirtualNetworkPool.h"
#include "ImagePool.h"
#include "ClusterPool.h"
#include "VMTemplatePool.h"
#include <xmlrpc-c/base.hpp>
#include <xmlrpc-c/registry.hpp>
@ -46,10 +47,11 @@ public:
UserPool * _upool,
ImagePool * _ipool,
ClusterPool * _cpool,
VMTemplatePool * _tpool,
int _port,
string _xml_log_file)
:vmpool(_vmpool),hpool(_hpool),vnpool(_vnpool),upool(_upool),
ipool(_ipool),cpool(_cpool),port(_port),socket_fd(-1),
ipool(_ipool),cpool(_cpool),tpool(_tpool),port(_port),socket_fd(-1),
xml_log_file(_xml_log_file)
{
am.addListener(this);
@ -130,10 +132,15 @@ private:
ImagePool * ipool;
/**
* Pointer to the Image Pool, to access images
* Pointer to the Cluster Pool, to access clusters
*/
ClusterPool * cpool;
/**
* Pointer to the Template Pool, to access templates
*/
VMTemplatePool * tpool;
/**
* Port number where the connection will be open
*/
@ -314,10 +321,12 @@ private:
VirtualMachinePool * _vmpool,
VirtualNetworkPool * _vnpool,
ImagePool * _ipool,
VMTemplatePool * _tpool,
UserPool * _upool):
vmpool(_vmpool),
vnpool(_vnpool),
ipool(_ipool),
tpool(_tpool),
upool(_upool)
{
_signature="A:ss";
@ -333,6 +342,7 @@ private:
VirtualMachinePool * vmpool;
VirtualNetworkPool * vnpool;
ImagePool * ipool;
VMTemplatePool * tpool;
UserPool * upool;
};
@ -502,6 +512,185 @@ private:
UserPool * upool;
};
/* ---------------------------------------------------------------------- */
/* Template Interface */
/* ---------------------------------------------------------------------- */
class TemplateAllocate: public xmlrpc_c::method
{
public:
TemplateAllocate(
VMTemplatePool * _tpool,
UserPool * _upool):
tpool(_tpool),
upool(_upool)
{
_signature="A:ss";
_help="Allocates a template in the pool";
};
~TemplateAllocate(){};
void execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retvalP);
private:
VMTemplatePool * tpool;
UserPool * upool;
};
/* ---------------------------------------------------------------------- */
class TemplateDelete: public xmlrpc_c::method
{
public:
TemplateDelete(VMTemplatePool * _tpool,
UserPool * _upool):
tpool(_tpool),
upool(_upool)
{
_signature="A:si";
_help="Deletes a Template";
};
~TemplateDelete(){};
void execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retvalP);
private:
VMTemplatePool * tpool;
UserPool * upool;
};
/* ---------------------------------------------------------------------- */
class TemplateInfo: public xmlrpc_c::method
{
public:
TemplateInfo(VMTemplatePool * _tpool,
UserPool * _upool):
tpool(_tpool),
upool(_upool)
{
_signature="A:si";
_help="Returns information for a Template";
};
~TemplateInfo(){};
void execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retvalP);
private:
VMTemplatePool * tpool;
UserPool * upool;
};
/* ---------------------------------------------------------------------- */
class TemplateUpdate: public xmlrpc_c::method
{
public:
TemplateUpdate(VMTemplatePool * _tpool,
UserPool * _upool):
tpool(_tpool),
upool(_upool)
{
_signature="A:siss";
_help="Modifies Template attribute";
};
~TemplateUpdate(){};
void execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retvalP);
private:
VMTemplatePool * tpool;
UserPool * upool;
};
/* ---------------------------------------------------------------------- */
class TemplateRemoveAttribute: public xmlrpc_c::method
{
public:
TemplateRemoveAttribute(VMTemplatePool * _tpool,
UserPool * _upool):
tpool(_tpool),
upool(_upool)
{
_signature="A:sis";
_help="Removes Template attribute";
};
~TemplateRemoveAttribute(){};
void execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retvalP);
private:
VMTemplatePool * tpool;
UserPool * upool;
};
/* ---------------------------------------------------------------------- */
class TemplatePublish: public xmlrpc_c::method
{
public:
TemplatePublish(VMTemplatePool * _tpool,
UserPool * _upool):
tpool(_tpool),
upool(_upool)
{
_signature="A:sib";
_help="Publish/Unpublish the Template";
};
~TemplatePublish(){};
void execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retvalP);
private:
VMTemplatePool * tpool;
UserPool * upool;
};
/* ---------------------------------------------------------------------- */
class TemplatePoolInfo: public xmlrpc_c::method
{
public:
TemplatePoolInfo(
VMTemplatePool * _tpool,
UserPool * _upool):
tpool(_tpool),
upool(_upool)
{
_signature="A:sii";
_help="Returns the template pool";
};
~TemplatePoolInfo(){};
void execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retvalP);
private:
VMTemplatePool * tpool;
UserPool * upool;
};
/* ---------------------------------------------------------------------- */
/* Host Interface */
/* ---------------------------------------------------------------------- */

View File

@ -47,6 +47,20 @@ public:
separator(_separator),
xml_root(_xml_root){};
Template(const Template& t)
{
multimap<string,Attribute *>::const_iterator it;
replace_mode = t.replace_mode;
separator = t.separator;
xml_root = t.xml_root;
for (it = t.attributes.begin() ; it != t.attributes.end() ; it++)
{
attributes.insert(make_pair(it->first,(it->second)->clone()));
}
}
/**
* The class destructor frees all the attributes conforming the template
*/
@ -161,8 +175,10 @@ public:
* @param name the attribute name.
* @param value the attribute value, an int, 0 if the attribute is not
* defined or not Single
*
* @returns True if the Single attribute was found
*/
virtual void get(
virtual bool get(
string& name,
int& value) const;

View File

@ -134,15 +134,6 @@ private:
*/
int insert_replace(SqlDB *db, bool replace);
/**
* Callback function to unmarshall a User object (User::select)
* @param num the number of columns read from the DB
* @param names the column names
* @param vaues the column values
* @return 0 on success
*/
int select_cb(void *nil, int num, char **values, char **names);
/**
* Bootstraps the database table(s) associated to the User
*/

190
include/VMTemplate.h Normal file
View File

@ -0,0 +1,190 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, 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. */
/* -------------------------------------------------------------------------- */
#ifndef VMTEMPLATE_H_
#define VMTEMPLATE_H_
#include "PoolObjectSQL.h"
#include "VirtualMachineTemplate.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/**
* The VMTemplate class.
*/
class VMTemplate : public PoolObjectSQL
{
public:
/**
* Function to write a VMTemplate on an output stream
*/
friend ostream& operator<<(ostream& os, VMTemplate& u);
/**
* Function to print the VMTemplate object into a string in XML format
* @param xml the resulting XML string
* @return a reference to the generated string
*/
string& to_xml(string& xml) const;
/**
* Returns true if the object is public
* @return true if the Virtual Network is public
*/
bool isPublic()
{
return (public_template == 1);
};
/**
* Publish or unpublish an object
* @param pub true to publish the object
* @return 0 on success
*/
bool publish(bool pub)
{
if (pub == true)
{
public_template = 1;
}
else
{
public_template = 0;
}
return true;
};
// ------------------------------------------------------------------------
// Template Contents
// ------------------------------------------------------------------------
/**
* Returns a copy of the VirtualMachineTemplate
* @return A copy of the VirtualMachineTemplate
*/
VirtualMachineTemplate * clone_template() const
{
return new VirtualMachineTemplate(
*(static_cast<VirtualMachineTemplate *>(obj_template)));
// TODO: Check if there is a more efficient way to do this copy.
/*string xml_str;
VirtualMachineTemplate * new_template = new VirtualMachineTemplate();
obj_template->to_xml(xml_str);
new_template->from_xml(xml_str);
return new_template;*/
};
private:
// -------------------------------------------------------------------------
// Friends
// -------------------------------------------------------------------------
friend class VMTemplatePool;
// -------------------------------------------------------------------------
// VMTemplate Attributes
// -------------------------------------------------------------------------
/**
* Owner's name
*/
string user_name;
/**
* Public scope of the VMTemplate
*/
int public_template;
/**
* Registration time
*/
time_t regtime;
// *************************************************************************
// DataBase implementation (Private)
// *************************************************************************
/**
* Execute an INSERT or REPLACE Sql query.
* @param db The SQL DB
* @param replace Execute an INSERT or a REPLACE
* @return 0 one success
*/
int insert_replace(SqlDB *db, bool replace);
/**
* Bootstraps the database table(s) associated to the VMTemplate
*/
static void bootstrap(SqlDB * db)
{
ostringstream oss(VMTemplate::db_bootstrap);
db->exec(oss);
};
/**
* Rebuilds the object from an xml formatted string
* @param xml_str The xml-formatted string
*
* @return 0 on success, -1 otherwise
*/
int from_xml(const string &xml_str);
protected:
// *************************************************************************
// Constructor
// *************************************************************************
VMTemplate(int id, int uid, string _user_name,
VirtualMachineTemplate * _template_contents);
~VMTemplate();
// *************************************************************************
// DataBase implementation
// *************************************************************************
static const char * db_names;
static const char * db_bootstrap;
static const char * table;
/**
* Writes the VMTemplate in the database.
* @param db pointer to the db
* @return 0 on success
*/
int insert(SqlDB *db, string& error_str);
/**
* Writes/updates the VMTemplate data fields in the database.
* @param db pointer to the db
* @return 0 on success
*/
int update(SqlDB *db)
{
return insert_replace(db, true);
};
};
#endif /*VMTEMPLATE_H_*/

146
include/VMTemplatePool.h Normal file
View File

@ -0,0 +1,146 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, 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. */
/* -------------------------------------------------------------------------- */
#ifndef VMTEMPLATE_POOL_H_
#define VMTEMPLATE_POOL_H_
#include "PoolSQL.h"
#include "VMTemplate.h"
/**
* The VMTemplate Pool class.
*/
class VMTemplatePool : public PoolSQL
{
public:
VMTemplatePool(SqlDB * db) : PoolSQL(db, VMTemplate::table){};
~VMTemplatePool(){};
/**
* Allocates a new object, writting it in the pool database. No memory is
* allocated for the object.
* @param uid user id (the owner of the Template)
* @param user_name Owner's user name
* @param template_contents a VM Template object
* @param oid the id assigned to the Template
* @param error_str Returns the error reason, if any
*
* @return the oid assigned to the object, -1 in case of failure
*/
int allocate(int uid,
string user_name,
VirtualMachineTemplate * template_contents,
int * oid,
string& error_str);
/**
* Gets an object from the pool (if needed the object is loaded from the
* database).
* @param oid the object unique identifier
* @param lock locks the object if true
*
* @return a pointer to the object, 0 in case of failure
*/
VMTemplate * get(int oid, bool lock)
{
return static_cast<VMTemplate *>(PoolSQL::get(oid,lock));
};
/**
* Gets an object from the pool (if needed the object is loaded from the
* database).
* @param name of the object
* @param uid id of owner
* @param lock locks the object if true
*
* @return a pointer to the object, 0 in case of failure
*/
VMTemplate * get(const string& name, int uid, bool lock)
{
return static_cast<VMTemplate *>(PoolSQL::get(name,uid,lock));
};
/**
* Updates the object's data in the data base. The object mutex SHOULD be
* locked.
* @param objsql a pointer to the object
*
* @return 0 on success.
*/
int update(VMTemplate * vm_template)
{
return vm_template->update(db);
};
/**
* Drops the object's data in the data base. The object mutex SHOULD be
* locked.
* @param objsql a pointer to the object
* @return 0 on success.
*/
int drop(VMTemplate * vm_template)
{
return PoolSQL::drop(vm_template);
};
/**
* Dumps the pool in XML format. A filter can be also added to the
* query
* @param oss the output stream to dump the pool contents
* @param where filter for the objects, defaults to all
*
* @return 0 on success
*/
int dump(ostringstream& oss, const string& where)
{
return PoolSQL::dump(oss, "VMTEMPLATE_POOL",VMTemplate::table,where);
};
/**
* Bootstraps the database table(s) associated to the pool
*/
static void bootstrap(SqlDB *_db)
{
VMTemplate::bootstrap(_db);
};
private:
//--------------------------------------------------------------------------
// Configuration Attributes for Images
// -------------------------------------------------------------------------
// TODO
//--------------------------------------------------------------------------
// Pool Attributes
// -------------------------------------------------------------------------
// TODO
/**
* Factory method to produce Image objects
* @return a pointer to the new Image
*/
PoolObjectSQL * create()
{
return new VMTemplate(-1,-1,"", 0);
};
};
#endif /*VMTEMPLATE_POOL_H_*/

View File

@ -544,7 +544,6 @@ public:
// ------------------------------------------------------------------------
// States
// ------------------------------------------------------------------------
/**
* Returns the VM state (Dispatch Manager)
* @return the VM state
@ -819,7 +818,6 @@ private:
return -1;
};
// -------------------------------------------------------------------------
// Attribute Parser
// -------------------------------------------------------------------------

View File

@ -41,8 +41,10 @@ public:
/**
* Function to allocate a new VM object
* @param uid user id (the owner of the VM)
* @param user_name Owner's user name
* @param vm_template a VM Template object describing the VM
* @param oid the id assigned to the VM (output)
* @param error_str Returns the error reason, if any
* @param on_hold flag to submit on hold
* @return oid on success, -1 error inserting in DB or -2 error parsing
* the template

View File

@ -19,6 +19,8 @@
#include "Template.h"
#include <string.h>
using namespace std;
/**
@ -32,6 +34,8 @@ public:
~VirtualMachineTemplate(){};
VirtualMachineTemplate(VirtualMachineTemplate& vmt):Template(vmt){};
private:
friend class VirtualMachine;
};

View File

@ -26,6 +26,7 @@
#include "HostPool.h"
#include "UserPool.h"
#include "ClusterPool.h"
#include "VMTemplatePool.h"
#include "VirtualMachineManager.h"
#include "LifeCycleManager.h"
@ -43,7 +44,8 @@ protected:
NebulaTest():mysql(false), need_host_pool(false), need_vm_pool(false),
need_vnet_pool(false), need_image_pool(false),
need_user_pool(false), need_cluster_pool(false),need_vmm(false),
need_user_pool(false), need_cluster_pool(false),
need_template_pool(false),need_vmm(false),
need_im(false), need_tm(false),
need_lcm(false), need_dm(false),
need_rm(false), need_hm(false),
@ -63,6 +65,7 @@ public:
bool need_image_pool;
bool need_user_pool;
bool need_cluster_pool;
bool need_template_pool;
bool need_vmm;
bool need_im;
@ -100,6 +103,8 @@ public:
virtual ClusterPool* create_cpool(SqlDB* db);
virtual VMTemplatePool* create_tpool(SqlDB* db);
// ------------------------------------------------------------------------
// Managers
// ------------------------------------------------------------------------
@ -129,6 +134,7 @@ public:
UserPool * upool,
ImagePool * ipool,
ClusterPool * cpool,
VMTemplatePool * tpool,
string log_file);
virtual HookManager* create_hm(VirtualMachinePool * vmpool);

View File

@ -195,7 +195,8 @@ LIB_DIRS="$LIB_LOCATION/ruby \
$LIB_LOCATION/remotes/vmm/xen \
$LIB_LOCATION/remotes/vmm/kvm \
$LIB_LOCATION/remotes/image \
$LIB_LOCATION/remotes/image/fs"
$LIB_LOCATION/remotes/image/fs \
$LIB_LOCATION/sh"
VAR_DIRS="$VAR_LOCATION/remotes \
$VAR_LOCATION/remotes/im \
@ -257,6 +258,9 @@ INSTALL_FILES=(
LIB_FILES:$LIB_LOCATION
RUBY_LIB_FILES:$LIB_LOCATION/ruby
RUBY_OPENNEBULA_LIB_FILES:$LIB_LOCATION/ruby/OpenNebula
MAD_SH_LIB_FILES:$LIB_LOCATION/sh
MAD_SH_LIB_FILES:$LIB_LOCATION/remotes
MAD_SH_LIB_FILES:$VAR_LOCATION/remotes
MADS_LIB_FILES:$LIB_LOCATION/mads
IM_PROBES_FILES:$VAR_LOCATION/remotes/im
IM_PROBES_KVM_FILES:$VAR_LOCATION/remotes/im/kvm.d
@ -360,6 +364,7 @@ BIN_FILES="src/nebula/oned \
src/cli/oneuser \
src/cli/oneimage \
src/cli/onecluster \
src/cli/onetemplate \
share/scripts/one \
src/authm_mad/oneauth"
@ -404,8 +409,18 @@ RUBY_OPENNEBULA_LIB_FILES="src/oca/ruby/OpenNebula/Host.rb \
src/oca/ruby/OpenNebula/ImagePool.rb \
src/oca/ruby/OpenNebula/Cluster.rb \
src/oca/ruby/OpenNebula/ClusterPool.rb \
src/oca/ruby/OpenNebula/Template.rb \
src/oca/ruby/OpenNebula/TemplatePool.rb \
src/oca/ruby/OpenNebula/XMLUtils.rb"
#-----------------------------------------------------------------------------
# MAD ShellScript library files, to be installed under $LIB_LOCATION/sh
# and remotes directory
#-----------------------------------------------------------------------------
MAD_SH_LIB_FILES="src/mad/sh/scripts_common.sh"
#-------------------------------------------------------------------------------
# Driver executable files, to be installed under $LIB_LOCATION/mads
#-------------------------------------------------------------------------------
@ -716,7 +731,8 @@ CLI_BIN_FILES="src/cli/onevm \
src/cli/onevnet \
src/cli/oneuser \
src/cli/oneimage \
src/cli/onecluster"
src/cli/onecluster \
src/cli/onetemplate"
#-----------------------------------------------------------------------------
# Sunstone files
@ -825,6 +841,7 @@ MAN_FILES="share/man/oneauth.8.gz \
share/man/oneuser.8.gz \
share/man/onevm.8.gz \
share/man/onevnet.8.gz \
share/man/onetemplate.8.gz \
share/man/econe-describe-images.8.gz \
share/man/econe-describe-instances.8.gz \
share/man/econe-register.8.gz \

View File

@ -69,24 +69,24 @@ main(int argc, char **) {
vector<xmlrpc_c::value> const paramArrayValue(resultArray.vectorValueValue());
//check posible Errors:
xmlrpc_c::value * firstvalue;
firstvalue = &(static_cast<xmlrpc_c::value>(paramArrayValue[0]));
xmlrpc_c::value_boolean * status = &(static_cast<xmlrpc_c::value_boolean>(*firstvalue));
xmlrpc_c::value firstvalue;
firstvalue = static_cast<xmlrpc_c::value>(paramArrayValue[0]);
xmlrpc_c::value_boolean status = static_cast<xmlrpc_c::value_boolean>(firstvalue);
xmlrpc_c::value * secondvalue;
secondvalue = &(static_cast<xmlrpc_c::value>(paramArrayValue[1]));
xmlrpc_c::value_string * valueS = &(static_cast<xmlrpc_c::value_string>(*secondvalue));
xmlrpc_c::value secondvalue;
secondvalue = static_cast<xmlrpc_c::value>(paramArrayValue[1]);
xmlrpc_c::value_string valueS = static_cast<xmlrpc_c::value_string>(secondvalue);
if(static_cast<bool>(*status)) {
if(static_cast<bool>(status)) {
//Success, returns the id assigned to the VM:
cout << "vmid returned: " << static_cast<string>(*valueS) << endl;
cout << "vmid returned: " << static_cast<string>(valueS) << endl;
return 0;
}
else{ //Failure:
string error_value=static_cast<string>(*valueS);
string error_value=static_cast<string>(valueS);
if (error_value.find("Error inserting",0)!=string::npos ) cout << "Error inserting VM in the database" << endl;
else if (error_value.find("Error parsing",0)!=string::npos ) cout << "Error parsing VM template" << endl;
else cout << "Unknown error " << static_cast<string>(*valueS) << endl;
else cout << "Unknown error " << static_cast<string>(valueS) << endl;
};
} catch (girerr::error const error) {
cerr << "Client threw error: " << error.what() << endl;

View File

@ -17,7 +17,8 @@ TESTS="$TWD_DIR/vnm/test \
$TWD_DIR/vm/test \
$TWD_DIR/um/test \
$TWD_DIR/lcm/test \
$TWD_DIR/pool/test"
$TWD_DIR/pool/test \
$TWD_DIR/vm_template/test"
#-------------------------------------------------------------------------------
# COMMAND LINE PARSING

View File

@ -86,9 +86,10 @@ void AuthRequest::add_auth(Object ob,
case IMAGE: oss << "IMAGE:" ; break;
case USER: oss << "USER:" ; break;
case CLUSTER: oss << "CLUSTER:" ; break;
case TEMPLATE: oss << "TEMPLATE:" ; break;
}
if (op == CREATE) //encode the ob_id, it is a template
if (op == CREATE || op == INSTANTIATE) //encode the ob_id, it is a template
{
string * encoded_id = base64_encode(ob_id);
@ -128,6 +129,10 @@ void AuthRequest::add_auth(Object ob,
case INFO:
oss << "INFO:" ;
break;
case INSTANTIATE:
oss << "INSTANTIATE:" ;
break;
}
oss << owner << ":" << pub;
@ -147,7 +152,14 @@ void AuthRequest::add_auth(Object ob,
switch (op)
{
case CREATE:
if ( ob == VM || ob == NET || ob == IMAGE )
if ( ob == VM || ob == NET || ob == IMAGE || ob == TEMPLATE )
{
auth = true;
}
break;
case INSTANTIATE:
if ( ob == VM )
{
auth = true;
}
@ -158,7 +170,7 @@ void AuthRequest::add_auth(Object ob,
break;
case USE:
if (ob == NET || ob == IMAGE)
if (ob == NET || ob == IMAGE || ob == TEMPLATE)
{
auth = (owner == uid) || pub;
}

View File

@ -91,7 +91,7 @@ void AuthManagerDriver::protocol(
{
is.clear();
getline(is,info);
NebulaLog::log("AuM",Log::INFO, info.c_str());
NebulaLog::log("AuM", log_type(result[0]), info.c_str());
}
return;

View File

@ -89,19 +89,43 @@ class Quota
# Checks if the user is below resource limits. If new_vm is defined
# checks if its requirements fit in limits
def check(user, new_vm=nil)
usage=@usage.total(user)
use=@usage.total(user)
use_after=use.clone
user_quota=get(user)
if new_vm
usage.cpu+=new_vm.cpu.to_f
usage.memory+=new_vm.memory.to_i
usage.num_vms+=1
use_after.cpu+=new_vm.cpu.to_f
use_after.memory+=new_vm.memory.to_i
use_after.num_vms+=1
end
STDERR.puts [user_quota, use_after, new_vm].inspect
error_message=""
if !(!user_quota[:cpu] || use_after.cpu<=user_quota[:cpu])
error_message<<"Cpu quota exceeded (Quota: #{user_quota[:cpu]}, "+
"Used: #{use.cpu}"
error_message<<", asked: #{new_vm.cpu.to_f}" if new_vm
error_message<<")."
end
if !(!user_quota[:memory] || use_after.memory<=user_quota[:memory])
error_message<<" Memory quota exceeded (Quota: "+
"#{user_quota[:memory]}, Used: #{use.memory}"
error_message<<", asked: #{new_vm.memory.to_i}" if new_vm
error_message<<")."
end
if !(!user_quota[:num_vms] || use_after.num_vms<=user_quota[:num_vms])
error_message<<" Num VMS quota exceeded (Quota: "+
"#{user_quota[:memory]}, Used: #{use.num_vms})."
end
if error_message==""
false
else
error_message.strip
end
STDERR.puts [user_quota, usage, new_vm].inspect
(!user_quota[:cpu] || usage.cpu<=user_quota[:cpu]) &&
(!user_quota[:memory] || usage.memory<=user_quota[:memory]) &&
(!user_quota[:num_vms] || usage.num_vms<=user_quota[:num_vms])
end
# Updates user resource consuption

View File

@ -48,7 +48,20 @@ class SimplePermissions
VmUsage.new(cpu, memory)
end
# Checks if the quota is enabled, and if it is not exceeded
def check_quota_enabled(uid, object, id, auth_result)
if @quota_enabled and object=='VM' and auth_result
STDERR.puts 'quota enabled'
@quota.update(uid.to_i)
if message=@quota.check(uid.to_i, get_vm_usage(id))
auth_result=message
end
end
return auth_result
end
# Method called by authorization driver
def auth(uid, tokens)
result=true
@ -71,21 +84,18 @@ class SimplePermissions
case action
when 'CREATE'
auth_result=true if %w{VM NET IMAGE}.include? object
if @quota_enabled and object=='VM' and auth_result
STDERR.puts 'quota enabled'
@quota.update(uid.to_i)
if !@quota.check(uid.to_i, get_vm_usage(id))
auth_result="Quota exceeded"
end
end
auth_result=true if %w{VM NET IMAGE TEMPLATE}.include? object
auth_result = check_quota_enabled(uid, object, id, auth_result)
when 'INSTANTIATE'
auth_result = true if %w{VM}.include? object
auth_result = check_quota_enabled(uid, object, id, auth_result)
when 'DELETE'
auth_result = (owner == uid)
when 'USE'
if %w{VM NET IMAGE}.include? object
if %w{VM NET IMAGE TEMPLATE}.include? object
auth_result = ((owner == uid) | (pub=='1'))
elsif object == 'HOST'
auth_result=true

View File

@ -60,8 +60,8 @@ describe 'Quota' do
it 'should check for quotas' do
@quota.update(0)
@quota.update(1)
@quota.check(0).should == true
@quota.check(1).should == true
@quota.check(0).should == false
@quota.check(1).should == false
vms=@quota.get_user(0)
vms[5]=VmUsage.new(40.0, 8192)
@ -69,13 +69,13 @@ describe 'Quota' do
vms=@quota.get_user(1)
vms[6]=VmUsage.new(40.0, 8192)
@quota.check(0).should == false
@quota.check(1).should == false
@quota.check(0).class.should == String
@quota.check(1).class.should == String
@quota.update(0)
@quota.update(1)
@quota.check(0).should == true
@quota.check(1).should == true
@quota.check(0).should == false
@quota.check(1).should == false
end
it 'should let update limits' do
@ -86,8 +86,8 @@ describe 'Quota' do
it 'should understand unlimited quotas' do
vms=@quota.get_user(0)
vms[7]=VmUsage.new(9999999999.0, 99999999999)
@quota.check(0).should == true
@quota.check(0, VmUsage.new(999999999.0, 99999999)).should == true
@quota.check(0).should == false
@quota.check(0, VmUsage.new(999999999.0, 99999999)).should == false
end
end

View File

@ -268,15 +268,19 @@ def get_entity_id(name, pool_class)
pool=pool_class.new(get_one_client)
result=pool.info
# TODO: Check for errors
class_name=pool_class.name.split('::').last.gsub(/Pool$/, '')
if( OpenNebula.is_error?(result) )
puts "Error: #{class_name} Pool info could not be retrieved. " +
result.message
exit -1
end
objects=pool.select {|object| object.name==name }
class_name=pool_class.name.split('::').last.gsub(/Pool$/, '')
if objects.length>0
if objects.length>1
puts "There are multiple #{class_name}'s with name #{name}."
puts "There are multiple #{class_name}s with name #{name}."
exit -1
else
result=objects.first.id
@ -313,6 +317,10 @@ def get_cluster_id(name)
get_entity_id(name, OpenNebula::ClusterPool)
end
def get_template_id(name)
get_entity_id(name, OpenNebula::TemplatePool)
end
def str_running_time(data)
stime=Time.at(data["STIME"].to_i)
if data["ETIME"]=="0"

411
src/cli/onetemplate Executable file
View File

@ -0,0 +1,411 @@
#!/usr/bin/env ruby
# -------------------------------------------------------------------------- #
# Copyright 2002-2011, 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"
else
RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby"
end
$: << RUBY_LIB_LOCATION
require 'OpenNebula'
require 'CommandManager'
require 'client_utilities'
require 'command_parse'
ShowTableTemplate={
:id => {
:name => "ID",
:desc => "ONE identifier for the Template",
:size => 4,
:proc => lambda {|d,e| d.id }
},
:user=> {
:name => "USER",
:desc => "Name of the owner",
:size => 8,
:proc => lambda {|d,e|
d["USERNAME"]
}
},
:name => {
:name => "NAME",
:desc => "Name of the Template",
:size => 20,
:proc => lambda {|d,e|
d.name
}
},
:regtime => {
:name => "REGTIME",
:desc => "Registration time of the Template",
:size => 20,
:proc => lambda {|d,e|
str_register_time(d)
}
},
:public => {
:name => "PUBLIC",
:desc => "Whether the Template is public or not",
:size => 3,
:proc => lambda {|d,e|
if d["PUBLIC"].to_i == 1 then "Yes" else "No" end}
},
:default => [:id, :user, :name, :regtime, :public]
}
class TemplateShow
def initialize(client, filter_flag="-2")
@templatepool=OpenNebula::TemplatePool.new(client, filter_flag.to_i)
@table=ShowTable.new(ShowTableTemplate)
end
def header_template_small
scr_bold
scr_underline
print @table.header_str
scr_restore
puts ""
end
def top(options=nil)
delay=1
delay=options[:delay] if options && options[:delay]
result=nil
begin
while true
scr_cls
scr_move(0,0)
result=list_short(options)
sleep delay
end
rescue Exception
end
result
end
def list_short(options=nil)
res=@templatepool.info()
if options
@table.columns=options[:columns] if options[:columns]
end
if OpenNebula.is_error?(res)
result=res
puts res.message
exit -1
else
if options[:filter_flag]
objs=@templatepool.select{|element|
element['USERNAME']==options[:filter_flag] }
else
objs=@templatepool
end
result=[true, ""]
header_template_small
if options
puts @table.data_str(objs, options)
else
puts @table.data_str(objs)
end
result
end
end
end
##########################
## COMMAND LINE PARSING ##
##########################
class OneTemplateParse < CommandParse
COMMANDS_HELP=<<-EOT
Description:
This command enables the user to manage templates.
Commands:
* create (Registers a Template from a template file)
onetemplate create <file>
file is a file name where the Template description is located
* addattr (Add a new Template attribute)
onetemplate addattr <template_id> <attribute_name> <attribute_value>
* update (Modifies a Template attribute)
onetemplate update <template_id> <attribute_name> <attribute_value>
* rmattr (Deletes a Template attribute)
onetemplate rmattr <template_id> <attribute_name>
* publish (Publish a Template)
onetemplate publish <template_id>
* unpublish (Unpublish an Template)
onetemplate unpublish <template_id>
* list (Shows Templates in the pool)
onetemplate list <filter_flag>
where filter_flag can be
a, all --> all the known Templates
m, mine --> the Templates belonging to the user in ONE_AUTH
and all the Public Templates
uid --> Templates of the user identified by this uid
user --> Templates of the user identified by the username
* top (Lists Templates continuously)
onetemplate top
* show (Gets information about an specific Template)
onetemplate show <template_id>
* delete (Deletes a Template)
onetemplate delete <template_id>
EOT
def text_commands
COMMANDS_HELP
end
def text_command_name
"onetemplate"
end
def list_options
table=ShowTable.new(ShowTableTemplate)
table.print_help
end
end
def get_user_flags
ops=Hash.new
if ARGV[0]
case ARGV[0]
when "a", "all"
ops[:filter_user]="-2"
when "m", "mine"
ops[:filter_user]="-1"
else
if !ARGV[0].match(/^[0123456789]+$/)
ops[:filter_user]="-2"
ops[:filter_flag]=ARGV[0]
else
ops[:filter_user]=ARGV[0]
end
end
else
ops[:filter_user]="-2"
end
ops
end
def get_template(template_path)
begin
template = File.read(ARGV[0])
rescue
result = OpenNebula::Error.new("Can not read template: #{ARGV[0]}")
end
if !is_successful?(result)
puts result.message
exit -1
end
return template
end
onetemplate_opts=OneTemplateParse.new
onetemplate_opts.parse(ARGV)
ops=onetemplate_opts.options
result=[false, "Unknown error"]
command=ARGV.shift
case command
when "create", "register", "add"
check_parameters("create", 1)
template_contents = get_template(ARGV[0])
template = OpenNebula::Template.new(OpenNebula::Template.build_xml, get_one_client)
result=template.allocate(template_contents)
if !OpenNebula.is_error?(result)
puts "ID: " + template.id.to_s if ops[:verbose]
exit 0
end
when "update", "addattr"
check_parameters("update", 3)
template_id = get_template_id(ARGV[0])
template = OpenNebula::Template.new_with_id(template_id, get_one_client)
result = template.update(ARGV[1],ARGV[2])
if is_successful?(result)
puts "Modified template" if ops[:verbose]
end
when "rmattr"
check_parameters("rmattr", 2)
template_id = get_template_id(ARGV[0])
template = OpenNebula::Template.new_with_id(template_id, get_one_client)
result = template.remove_attr(ARGV[1])
if is_successful?(result)
puts "Removed template attribute" if ops[:verbose]
end
when "publish"
check_parameters("publish", 1)
template_id = get_template_id(ARGV[0])
template = OpenNebula::Template.new_with_id(template_id, get_one_client)
result = template.publish
if is_successful?(result)
puts "Template published" if ops[:verbose]
end
when "unpublish"
check_parameters("unpublish", 1)
template_id = get_template_id(ARGV[0])
template = OpenNebula::Template.new_with_id(template_id, get_one_client)
result = template.unpublish
if is_successful?(result)
puts "Template unpublished" if ops[:verbose]
end
when "list"
ops.merge!(get_user_flags)
if !ops[:xml]
templatelist = TemplateShow.new(get_one_client, ops[:filter_user].to_i)
ops[:columns] = ops[:list] if ops[:list]
result = templatelist.list_short(ops)
else
templatepool = OpenNebula::TemplatePool.new(get_one_client,
ops[:filter_user].to_i)
templatepool.info
puts templatepool.to_xml
end
when "top"
ops.merge!(get_user_flags)
templatelist = TemplateShow.new(get_one_client, ops[:filter_user].to_i)
ops[:columns] = ops[:list] if ops[:list]
result = templatelist.top(ops)
when "show"
check_parameters("get_info", 1)
args = expand_args(ARGV)
args.each do |param|
template_id = get_template_id(param)
template = OpenNebula::Template.new_with_id(template_id, get_one_client)
result = template.info
if is_successful?(result)
if !ops[:xml]
str="%-15s: %-20s"
str_h1="%-80s"
print_header(str_h1, "TEMPLATE #{template[:id]} INFORMATION", true)
puts str % ["ID", template.id.to_s]
puts str % ["NAME", template.name]
value = template['REGTIME'].to_i
if value==0
value='-'
else
value=Time.at(value).strftime("%m/%d %H:%M:%S")
end
puts str % ["REGISTER TIME", value]
if template['PUBLIC'].to_i == 1
public_str = "Yes"
else
public_str = "No"
end
puts str % ["PUBLIC", public_str]
puts
print_header(str_h1,"TEMPLATE CONTENTS",false)
puts template.template_str
else
puts template.to_xml
end
end
end
when "delete"
check_parameters("delete", 1)
args = expand_args(ARGV)
args.each do |param|
template_id = get_template_id(param)
template = OpenNebula::Template.new(
OpenNebula::Template.build_xml(template_id),
get_one_client)
result = template.delete
if is_successful?(result)
puts "Template correctly deleted" if ops[:verbose]
end
end
else
onetemplate_opts.print_help
exit -1
end
if OpenNebula.is_error?(result)
puts "Error: " + result.message
exit -1
end

View File

@ -318,9 +318,15 @@ machine with the functionality present in onevm.
Commands:
* create (Submits a new virtual machine, adding it to the ONE VM pool)
onevm create <template>
onevm create [OPTION] {<template-file-path>, <template-id>, <template-name>}
template is a file name where the VM description is located
<template-file-path> is a file name where the VM description is located.
<template-id> is the numeric ID of a registered template (using onetemplate)
<template-name> is the name of a registered template (using onetemplate)
OPTION: -n STRING, --name=STRING
Replaces the NAME attribute if the VM is being created from a registered
Template
* deploy (Starts an existing VM in an specific host)
onevm deploy <vm_id> <host_id>
@ -462,6 +468,10 @@ EOT
"Image type") do |o|
options[:type]=o
end
opts.on_tail("-n vm_name", "--name vm_name", String,
"Set VM name") do |o|
options[:vm_name] = o
end
end
end
@ -502,12 +512,32 @@ when "submit", "create"
check_parameters("create", 1)
vm=OpenNebula::VirtualMachine.new(
OpenNebula::VirtualMachine.build_xml, get_one_client)
begin
template=File.read(ARGV[0])
result=vm.allocate(template)
rescue
result=OpenNebula::Error.new("Can not read template: #{ARGV[0]}")
template = ""
success = false
if( File.file?(ARGV[0]) )
# argument is a file path
begin
template = File.read(ARGV[0])
success = true
rescue
result = OpenNebula::Error.new("Can not read template: #{ARGV[0]}")
end
else
# argument could be a template ID or a template name
template_id = get_template_id(ARGV[0])
template = "TEMPLATE_ID = #{template_id}"
template << "\nNAME = #{ops[:vm_name]}" if ops[:vm_name]
success = true
end
if( success )
result = vm.allocate(template)
end
if is_successful?(result)
puts "ID: " + vm.id.to_s if ops[:verbose]
exit 0

View File

@ -26,7 +26,6 @@ env.Prepend(LIBS=[
'nebula_common',
'nebula_sql',
### TODO: delete not needed
'nebula_core_test',
'nebula_host',
@ -40,6 +39,7 @@ env.Prepend(LIBS=[
'nebula_mad',
'nebula_template',
'nebula_vm',
'nebula_vmtemplate',
'nebula_vnm',
'nebula_image',
'nebula_pool',

View File

@ -125,7 +125,7 @@ void HookManagerDriver::protocol(
is.clear();
getline(is,info);
NebulaLog::log("HKM",Log::INFO, info.c_str());
NebulaLog::log("HKM", log_type(result[0]), info.c_str());
}
return;
@ -156,19 +156,26 @@ void HookManagerDriver::protocol(
if ( is.good() )
{
is >> hook_name >> ws;
getline(is,hook_name);
}
getline (is,info);
if (result == "SUCCESS")
{
oss << "Hook " << hook_name << " successfully executed. " << info;
oss << "Success executing Hook: " << hook_name << ". " << info;
vm->log("HKM",Log::INFO,oss);
}
else
{
oss << "Error executing Hook: " << hook_name << ". " << info;
if ( !info.empty() && info[0] != '-' )
{
vm->set_template_error_message(oss.str());
vmpool->update(vm);
}
vm->log("HKM",Log::ERROR,oss);
}
}
@ -177,7 +184,7 @@ void HookManagerDriver::protocol(
string info;
getline(is,info);
vm->log("HKM",Log::INFO,info.c_str());
vm->log("HKM",log_type(result[0]),info.c_str());
}
vm->unlock();

View File

@ -28,14 +28,11 @@ end
$: << RUBY_LIB_LOCATION
require 'pp'
require 'OpenNebulaDriver'
require 'CommandManager'
class HookManagerDriver < OpenNebulaDriver
def initialize(num)
super(num, true)
super(num, true, 0)
register_action(:EXECUTE, method("action_execute"))
end
@ -51,13 +48,14 @@ class HookManagerDriver < OpenNebulaDriver
end
if cmd.code==0
send_message("EXECUTE", RESULT[:success], number, hook_name)
message = "#{hook_name}: #{cmd.stdout}"
send_message("EXECUTE", RESULT[:success], number, message)
else
send_message("EXECUTE", RESULT[:failure], number, hook_name)
message = "#{hook_name}: #{cmd.get_error_message}"
send_message("EXECUTE", RESULT[:failure], number, message)
end
end
end
hm=HookManagerDriver.new(15)
hm.start_driver

View File

@ -386,7 +386,7 @@ public:
void scale_test()
{
time_t the_time, the_time2;
int oid,i,j,rc;
int oid,i,j;
ostringstream oss,ossdump;
string err;
@ -419,7 +419,7 @@ public:
the_time = time(0);
rc = hp->dump(ossdump, "");
hp->dump(ossdump, "");
cout <<"\t"<<i<<"\t"<<the_time2<<"\t"<<time(0)-the_time<< endl;

View File

@ -31,6 +31,7 @@ env.Prepend(LIBS=[
'nebula_mad',
'nebula_template',
'nebula_vm',
'nebula_vmtemplate',
'nebula_vnm',
'nebula_image',
'nebula_pool',

View File

@ -110,7 +110,7 @@ void InformationManagerDriver::protocol(
hinfo += "\n";
oss << "Host " << id << " successfully monitored."; //, info: "<< hinfo;
oss << "Host " << id << " successfully monitored.";
NebulaLog::log("InM",Log::DEBUG,oss);
rc = host->update_info(hinfo);
@ -136,22 +136,23 @@ void InformationManagerDriver::protocol(
string info;
getline(is,info);
NebulaLog::log("InM",Log::INFO,info.c_str());
NebulaLog::log("InM",log_type(result[0]),info.c_str());
}
return;
error_driver_info:
ess << "Error monitoring host " << id << " : " << is.str();
NebulaLog::log("InM", Log::ERROR, ess);
goto error_common_info;
error_parse_info:
ess << "Error parsing host information: " << hinfo;
NebulaLog::log("InM",Log::ERROR,ess);
goto error_common_info;
error_common_info:
NebulaLog::log("InM",Log::ERROR,ess);
host->set_template_error_message(ess.str());
host->touch(false);

View File

@ -51,7 +51,7 @@ class DummyInformationManager < OpenNebulaDriver
#---------------------------------------------------------------------------
def action_monitor(number, host, not_used)
results = "HYPERVISOR=dummy,"
results << "NAME=#{host},"
results << "HOSTNAME=#{host},"
results << "TOTALCPU=800,"
results << "CPUSPEED=2.2GHz,"

View File

@ -31,18 +31,18 @@ end
$: << RUBY_LIB_LOCATION
require 'OpenNebulaDriver'
require 'CommandManager'
require 'getoptlong'
#-------------------------------------------------------------------------------
# The Local Information Manager Driver
#-------------------------------------------------------------------------------
class InformationManager < OpenNebulaDriver
class InformationManagerDriverSH < OpenNebulaDriver
#---------------------------------------------------------------------------
# Init the driver
#---------------------------------------------------------------------------
def initialize(hypervisor, num)
super(num, true)
super(num, true, 0)
@config = read_configuration
@hypervisor = hypervisor
@ -57,29 +57,40 @@ class InformationManager < OpenNebulaDriver
# 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, log_lambda)
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
local_action(cmd_string, number, "MONITOR")
end
end
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Information Manager main program
# IM Driver main program
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
hypervisor = ARGV[0]
im = InformationManager.new(hypervisor, 15)
opts = GetoptLong.new(
[ '--threads', '-t', GetoptLong::OPTIONAL_ARGUMENT ]
)
hypervisor = ''
threads = 15
begin
opts.each do |opt, arg|
case opt
when '--threads'
threads = arg.to_i
end
end
rescue Exception => e
exit(-1)
end
if ARGV.length >= 1
hypervisor = ARGV.shift
end
im = InformationManagerDriverSH.new(hypervisor,threads)
im.start_driver

View File

@ -31,25 +31,23 @@ end
$: << RUBY_LIB_LOCATION
require 'OpenNebulaDriver'
require 'CommandManager'
require 'getoptlong'
#-------------------------------------------------------------------------------
# The SSH Information Manager Driver
#-------------------------------------------------------------------------------
class InformationManager < OpenNebulaDriver
class InformationManagerDriverSSH < OpenNebulaDriver
#---------------------------------------------------------------------------
# Init the driver
#---------------------------------------------------------------------------
def initialize(hypervisor, threads, retries)
super(threads, true)
super(threads, true, retries)
@config = read_configuration
@hypervisor = hypervisor
@remote_dir = @config['SCRIPTS_REMOTE_DIR']
@retries = retries
# register actions
register_action(:MONITOR, method("action_monitor"))
@ -59,34 +57,19 @@ 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, log_lambda)
LocalCommand.run(sync_cmd, log_method(number))
end
cmd_string = "#{@remote_dir}/im/run_probes #{@hypervisor} #{host}"
cmd = RemotesCommand.run(cmd_string,
host,
@remote_dir,
log_lambda,
@retries)
if cmd.code == 0
send_message("MONITOR", RESULT[:success], number, cmd.stdout)
else
send_message("MONITOR", RESULT[:failure], number,
"Could not monitor host #{host}.")
end
remotes_action(cmd_string, number, host, "MONITOR", @remote_dir)
end
end
#-------------------------------------------------------------------------------
@ -121,5 +104,5 @@ if ARGV.length >= 1
hypervisor = ARGV.shift
end
im = InformationManager.new(hypervisor, threads, retries)
im = InformationManagerDriverSSH.new(hypervisor, threads, retries)
im.start_driver

View File

@ -16,6 +16,8 @@
# limitations under the License. #
#--------------------------------------------------------------------------- #
source $(dirname $0)/../scripts_common.sh
export LANG=C
HYPERVISOR_DIR=$1.d
@ -32,7 +34,7 @@ function run_dir {
./$i $ARGUMENTS
EXIT_CODE=$?
if [ "x$EXIT_CODE" != "x0" ]; then
echo "Error executing $i" 1>&2
error_message "Error executing $i"
exit $EXIT_CODE
fi
fi

View File

@ -93,6 +93,7 @@ void ImageManagerDriver::protocol(
int id;
Image * image;
string source;
string info;
@ -123,7 +124,7 @@ void ImageManagerDriver::protocol(
is.clear();
getline(is,info);
NebulaLog::log("ImG",Log::INFO, info.c_str());
NebulaLog::log("ImG",log_type(result[0]), info.c_str());
}
return;
@ -148,8 +149,6 @@ void ImageManagerDriver::protocol(
image->set_state(Image::READY);
ipool->update(image);
image->unlock();
NebulaLog::log("ImM", Log::INFO, "Image copied and ready to use.");
}
else
@ -164,8 +163,6 @@ void ImageManagerDriver::protocol(
image->set_state(Image::READY);
ipool->update(image);
image->unlock();
NebulaLog::log("ImM", Log::INFO, "Image saved and ready to use.");
}
else
@ -180,8 +177,6 @@ void ImageManagerDriver::protocol(
image->set_state(Image::READY);
ipool->update(image);
image->unlock();
NebulaLog::log("ImM", Log::INFO, "Image created and ready to use");
}
else
@ -192,14 +187,11 @@ void ImageManagerDriver::protocol(
else if ( action == "RM" )
{
int rc;
string source;
source = image->get_source();
rc = ipool->drop(image);
image->unlock();
if ( rc < 0 )
{
NebulaLog::log("ImM",Log::ERROR,"Image could not be removed from DB");
@ -211,20 +203,17 @@ void ImageManagerDriver::protocol(
}
else
{
ostringstream oss;
oss <<"Error removing image from repository. Remove file " << source
<<" to completely delete image.";
NebulaLog::log("ImM",Log::ERROR,oss);
goto error_rm;
}
}
else if (action == "LOG")
{
getline(is,info);
NebulaLog::log("ImM", Log::INFO, info.c_str());
NebulaLog::log("ImM", log_type(result[0]), info.c_str());
}
image->unlock();
return;
error_cp:
@ -240,6 +229,12 @@ error_mv:
error_mkfs:
os.str("");
os << "Error creating datablock";
goto error_common;
error_rm:
os.str("");
os << "Error removing image from repository. Remove file " << source
<< " to completely delete image.";
error_common:
getline(is,info);
@ -247,6 +242,7 @@ error_common:
if (!info.empty() && (info[0] != '-'))
{
os << ": " << info;
image->set_template_error_message(os.str());
}
NebulaLog::log("ImM", Log::ERROR, os);

View File

@ -32,7 +32,6 @@ end
$: << RUBY_LIB_LOCATION
require "OpenNebulaDriver"
require "CommandManager"
require 'getoptlong'
# This class provides basic messaging and logging functionality
@ -56,7 +55,7 @@ class ImageDriver < OpenNebulaDriver
# Register default actions for the protocol
# -------------------------------------------------------------------------
def initialize(fs_type, concurrency=10, threaded=true)
super(concurrency,threaded)
super(concurrency,threaded,0)
@actions_path = "#{VAR_LOCATION}/remotes/image/#{fs_type}"
@ -66,25 +65,6 @@ class ImageDriver < OpenNebulaDriver
register_action(ACTION[:mkfs].to_sym, method("mkfs"))
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
info = "-"
else
result = :failure
info = command_exe.stderr
end
info = "-" if info == nil || info.empty?
send_message(ACTION[action],RESULT[result],id,info)
end
# -------------------------------------------------------------------------
# Image Manager Protocol Actions (generic implementation
# -------------------------------------------------------------------------

View File

@ -24,14 +24,12 @@
# ------------ Set up the environment to source common tools ------------
if [ -z "${ONE_LOCATION}" ]; then
TMCOMMON=/usr/lib/one/mads/tm_common.sh
VAR_LOCATION=/var/lib/one/
LIB_LOCATION=/usr/lib/one
else
TMCOMMON=$ONE_LOCATION/lib/mads/tm_common.sh
VAR_LOCATION=$ONE_LOCATION/var/
LIB_LOCATION=$ONE_LOCATION/lib
fi
. $TMCOMMON
. $LIB_LOCATION/sh/scripts_common.sh
# ------------ Copy the image to the repository ------------
@ -41,12 +39,14 @@ DST=$2
case $SRC in
http://*)
log "Downloading $SRC to the image repository"
exec_and_log "$WGET -O $DST $SRC"
exec_and_log "$WGET -O $DST $SRC" \
"Error downloading $SRC"
;;
*)
log "Copying local image $SRC to the image repository"
exec_and_log "cp -f $SRC $DST"
exec_and_log "cp -f $SRC $DST" \
"Error copying $SRC to $DST"
;;
esac

View File

@ -24,12 +24,12 @@
# ------------ Set up the environment to source common tools ------------
if [ -z "${ONE_LOCATION}" ]; then
TMCOMMON=/usr/lib/one/mads/tm_common.sh
LIB_LOCATION=/usr/lib/one
else
TMCOMMON=$ONE_LOCATION/lib/mads/tm_common.sh
LIB_LOCATION=$ONE_LOCATION/lib
fi
. $TMCOMMON
. $LIB_LOCATION/sh/scripts_common.sh
# ------------ Create the image to the repository ------------
@ -37,6 +37,8 @@ DST=$1
FSTYPE=$2
SIZE=$3
exec_and_log "$DD if=/dev/zero of=$DST bs=1 count=1 seek=${SIZE}M"
exec_and_log "$MKFS -t $FSTYPE -F $DST"
exec_and_log "$DD if=/dev/zero of=$DST bs=1 count=1 seek=${SIZE}M" \
"Could not create image $DST"
exec_and_log "$MKFS -t $FSTYPE -F $DST" \
"Unable to create filesystem $FSTYPE in $DST"
exec_and_log "chmod 0660 $DST"

View File

@ -24,14 +24,12 @@
# ------------ Set up the environment to source common tools ------------
if [ -z "${ONE_LOCATION}" ]; then
TMCOMMON=/usr/lib/one/mads/tm_common.sh
VAR_LOCATION=/var/lib/one/
LIB_LOCATION=/usr/lib/one
else
TMCOMMON=$ONE_LOCATION/lib/mads/tm_common.sh
VAR_LOCATION=$ONE_LOCATION/var/
LIB_LOCATION=$ONE_LOCATION/lib
fi
. $TMCOMMON
. $LIB_LOCATION/sh/scripts_common.sh
# ------------ Move the image to the repository ------------
@ -41,12 +39,14 @@ DST=$2
case $SRC in
http://*)
log "Downloading $SRC to the image repository"
exec_and_log "$WGET -O $DST $SRC"
exec_and_log "$WGET -O $DST $SRC" \
"Error downloading $SRC"
;;
*)
log "Moving local image $SRC to the image repository"
exec_and_log "mv -f $SRC $DST"
exec_and_log "mv -f $SRC $DST" \
"Could not move $SRC to $DST"
;;
esac

View File

@ -23,14 +23,12 @@
# ------------ Set up the environment to source common tools ------------
if [ -z "${ONE_LOCATION}" ]; then
TMCOMMON=/usr/lib/one/mads/tm_common.sh
VAR_LOCATION=/var/lib/one/
LIB_LOCATION=/usr/lib/one
else
TMCOMMON=$ONE_LOCATION/lib/mads/tm_common.sh
VAR_LOCATION=$ONE_LOCATION/var/
LIB_LOCATION=$ONE_LOCATION/lib
fi
. $TMCOMMON
. $LIB_LOCATION/sh/scripts_common.sh
# ------------ Remove the image to the repository ------------
@ -38,5 +36,6 @@ SRC=$1
if [ -e $SRC ] ; then
log "Removing $SRC from the image repository"
exec_and_log "rm $SRC"
exec_and_log "rm $SRC" \
"Error deleting $SRC"
fi

View File

@ -30,6 +30,7 @@ env.Prepend(LIBS=[
'nebula_mad',
'nebula_template',
'nebula_vm',
'nebula_vmtemplate',
'nebula_vnm',
'nebula_image',
'nebula_pool',

View File

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

View File

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

View File

@ -27,6 +27,20 @@ require 'stringio'
# * +stdout+: string of the standard output. Read-only
# * +stderr+: string of the standard error. Read-only
# * +command+: command to execute. Read-only
#
# The protocol for scripts to log is as follows:
#
# * Log messages will be sent to STDOUT
# * The script will return 0 if it succeded or any other value
# if there was a failure
# * In case of failure the cause of the error will be written to STDERR
# wrapped by start and end marks as follows:
#
# ERROR MESSAGE --8<------
# error message for the failure
# ERROR MESSAGE ------>8--
class GenericCommand
attr_reader :code, :stdout, :stderr, :command
@ -72,13 +86,20 @@ class GenericCommand
if @code!=0
log("Command execution fail: #{command}")
log("STDERR follows.")
log(@stderr)
end
log(@stderr)
return @code
end
# Parses error message from +stderr+ output
def get_error_message
tmp=@stderr.scan(/^ERROR MESSAGE --8<------\n(.*?)ERROR MESSAGE ------>8--$/m)
return "-" if !tmp[0]
tmp[0].join(' ').strip
end
private
# Gets exit code from STDERR
@ -158,14 +179,14 @@ class RemotesCommand < SSHCommand
cmd = self.new(cmd_string, host, logger, stdin)
cmd.run
if cmd.code == MAGIC_RC
cmd.update_remotes(host, remote_dir, logger)
@command = command
cmd.run
end
while cmd.code != 0 and retries != 0
sleep 1
cmd.run

View File

@ -12,10 +12,12 @@
# See the License for the specific language governing permissions and */
# limitations under the License. */
# -------------------------------------------------------------------------- */
require "ActionManager"
require "CommandManager"
# Author:: dsa-research.org
# Copyright:: (c) 2009 Universidad Computense de Madrid
# Copyright:: (c) OpenNebula Project Leads (OpenNebula.org)
# License:: Apache License
# This class provides basic messaging and logging functionality
@ -34,14 +36,18 @@ class OpenNebulaDriver < ActionManager
:failure => "FAILURE"
}
def initialize(concurrency=10, threaded=true)
def initialize(concurrency=10, threaded=true, retries=0)
super(concurrency,threaded)
register_action(:INIT, method("init"))
@retries = retries
@send_mutex=Mutex.new
register_action(:INIT, method("init"))
end
# -------------------------------------------------------------------------
# Sends a message to the OpenNebula core through stdout
# -------------------------------------------------------------------------
def send_message(action="-", result=RESULT[:failure], id="-", info="-")
@send_mutex.synchronize {
STDOUT.puts "#{action} #{result} #{id} #{info}"
@ -49,25 +55,103 @@ class OpenNebulaDriver < ActionManager
}
end
# -------------------------------------------------------------------------
# Execute a command associated to an action and id in a remote host.
# -------------------------------------------------------------------------
def remotes_action(command, id, host, aname, remote_dir, std_in=nil)
command_exe = RemotesCommand.run(command,
host,
remote_dir,
log_method(id),
std_in,
@retries)
if command_exe.code == 0
result = RESULT[:success]
info = command_exe.stdout
else
result = RESULT[:failure]
info = command_exe.get_error_message
end
info = "-" if info == nil || info.empty?
send_message(aname,result,id,info)
end
# -------------------------------------------------------------------------
# Execute a command associated to an action and id on localhost
# -------------------------------------------------------------------------
def local_action(command, id, aname)
command_exe = LocalCommand.run(command, log_method(id))
if command_exe.code == 0
result = RESULT[:success]
info = command_exe.stdout
else
result = RESULT[:failure]
info = command_exe.get_error_message
end
info = "-" if info == nil || info.empty?
send_message(aname,result,id,info)
end
# -------------------------------------------------------------------------
# Sends a log message to ONE. The +message+ can be multiline, it will
# be automatically splitted by lines.
# -------------------------------------------------------------------------
def log(number, message)
in_error_message=false
msg=message.strip
msg.each_line {|line|
send_message("LOG", "-", number, line.strip)
severity='I'
l=line.strip
if l=='ERROR MESSAGE --8<------'
in_error_message=true
next
elsif l=='ERROR MESSAGE ------>8--'
in_error_message=false
next
else
if in_error_message
severity='E'
elsif line.match(/^(ERROR|DEBUG|INFO):(.*)$/)
line=$2
case $1
when 'ERROR'
severity='E'
when 'DEBUG'
severity='D'
when 'INFO'
severity='I'
else
severity='I'
end
end
end
send_message("LOG", severity, number, line.strip)
}
end
# -------------------------------------------------------------------------
# Generates a proc with that calls log with a hardcoded number. It will
# be used to add loging to command actions
# -------------------------------------------------------------------------
def log_method(num)
lambda {|message|
log(num, message)
}
end
# -------------------------------------------------------------------------
# Start the driver. Reads from STDIN and executes methods associated with
# the messages
# -------------------------------------------------------------------------
def start_driver
loop_thread = Thread.new { loop }
start_listener
@ -101,13 +185,17 @@ private
if action == :DRIVER_CANCEL
cancel_action(action_id)
log(action_id,"Driver command for #{action_id} cancelled")
else
else
trigger_action(action,action_id,*args)
end
end
end
end
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
if __FILE__ == $0
class SampleDriver < OpenNebulaDriver

View File

@ -66,10 +66,9 @@ class VirtualMachineDriver < OpenNebulaDriver
# Register default actions for the protocol
# -------------------------------------------------------------------------
def initialize(concurrency=10, threaded=true, retries=0)
super(concurrency,threaded)
super(concurrency,threaded,retries)
@hosts = Array.new
@retries = retries
register_action(ACTION[:deploy].to_sym, method("deploy"))
register_action(ACTION[:shutdown].to_sym, method("shutdown"))
@ -109,43 +108,14 @@ class VirtualMachineDriver < OpenNebulaDriver
# Execute a command associated to an action and id in a remote host.
# -------------------------------------------------------------------------
def remotes_action(command, id, host, action, remote_dir, std_in=nil)
command_exe = RemotesCommand.run(command,
host,
remote_dir,
log_method(id),
std_in,
@retries)
if command_exe.code == 0
result = :success
info = command_exe.stdout
else
result = :failure
info = command_exe.stderr
end
info = "-" if info == nil || info.empty?
send_message(ACTION[action],RESULT[result],id,info)
super(command,id,host,ACTION[action],remote_dir,std_in)
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
info = command_exe.stdout
else
result = :failure
info = command_exe.stderr
end
info = "-" if info == nil || info.empty?
send_message(ACTION[action],RESULT[result],id,info)
super(command,id,ACTION[action])
end
# -------------------------------------------------------------------------
@ -187,7 +157,9 @@ class VirtualMachineDriver < OpenNebulaDriver
end
private
# -------------------------------------------------------------------------
# Interface to handle the pending events from the ActionManager Interface
# -------------------------------------------------------------------------
def delete_running_action(action_id)
action=@action_running[action_id]
if action
@ -227,11 +199,6 @@ private
@action_queue.delete_at(action_index)
end
STDERR.puts "action: #{action.inspect}"
STDERR.puts "queue: #{@action_queue.inspect}"
STDERR.puts "hosts: #{@hosts.inspect}"
STDERR.flush
return action
end
@ -240,6 +207,10 @@ private
end
end
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
# -------------------------------------------------------------------------
if __FILE__ == $0
class TemplateDriver < VirtualMachineDriver

147
src/mad/sh/scripts_common.sh Executable file
View File

@ -0,0 +1,147 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2011, 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. #
#--------------------------------------------------------------------------- #
# Paths for utilities
AWK=awk
BASH=/bin/bash
CUT=cut
DATE=/bin/date
DD=/bin/dd
LVCREATE=/sbin/lvcreate
LVREMOVE=/sbin/lvremove
LVS=/sbin/lvs
MD5SUM=/usr/bin/md5sum
MKFS=/sbin/mkfs
MKISOFS=/usr/bin/mkisofs
MKSWAP=/sbin/mkswap
SCP=/usr/bin/scp
SED=/bin/sed
SSH=/usr/bin/ssh
SUDO=/usr/bin/sudo
WGET=/usr/bin/wget
# Used for log messages
SCRIPT_NAME=`basename $0`
# Formats date for logs
function log_date
{
$DATE +"%a %b %d %T %Y"
}
# Logs a message, alias to log_info
function log
{
log_info "$1"
}
# Log function that knows how to deal with severities and adds the
# script name
function log_function
{
echo "$1: $SCRIPT_NAME: $2" 1>&2
}
# Logs an info message
function log_info
{
log_function "INFO" "$1"
}
# Logs an error message
function log_error
{
log_function "ERROR" "$1"
}
# Logs a debug message
function log_debug
{
log_function "DEBUG" "$1"
}
# This function is used to pass error message to the mad
function error_message
{
(
echo "ERROR MESSAGE --8<------"
echo "$1"
echo "ERROR MESSAGE ------>8--"
) 1>&2
}
# Executes a command, if it fails returns error message and exits
# If a second parameter is present it is used as the error message when
# the command fails
function exec_and_log
{
message=$2
output=`$1 2>&1 1>/dev/null`
code=$?
if [ "x$code" != "x0" ]; then
log_error "Command \"$1\" failed."
log_error "$output"
if [ -n "$message" ]; then
error_message "$output"
else
error_message "$message"
fi
exit $code
fi
log "Executed \"$1\"."
}
# Like exec_and_log but the first argument is the number of seconds
# before here is timeout and kills the command
#
# NOTE: if the command is killed because a timeout the exit code
# will be 143 = 128+15 (SIGHUP)
function timeout_exec_and_log
{
TIMEOUT=$1
shift
CMD="$1"
exec_and_log "$CMD" &
CMD_PID=$!
# timeout process
(
sleep $TIMEOUT
kill $CMD_PID 2>/dev/null
log_error "Timeout executing $CMD"
error_message "Timeout executing $CMD"
exit -1
) &
TIMEOUT_PID=$!
# stops the execution until the command finalizes
wait $CMD_PID 2>/dev/null
CMD_CODE=$?
# if the script reaches here the command finished before it
# consumes timeout seconds so we can kill timeout process
kill $TIMEOUT_PID 2>/dev/null 1>/dev/null
wait $TIMEOUT_PID 2>/dev/null
# checks the exit code of the command and exits if it is not 0
if [ "x$CMD_CODE" != "x0" ]; then
exit $CMD_CODE
fi
}

View File

@ -235,6 +235,7 @@ void Nebula::start()
UserPool::bootstrap(db);
ImagePool::bootstrap(db);
ClusterPool::bootstrap(db);
VMTemplatePool::bootstrap(db);
}
catch (exception&)
{
@ -276,6 +277,8 @@ void Nebula::start()
default_device_prefix);
cpool = new ClusterPool(db);
tpool = new VMTemplatePool(db);
}
catch (exception&)
{
@ -442,6 +445,7 @@ void Nebula::start()
upool,
ipool,
cpool,
tpool,
rm_port,
log_location + "one_xmlrpc.log");
}

View File

@ -50,6 +50,7 @@ env.Prepend(LIBS=[
'nebula_host',
'nebula_vnm',
'nebula_vm',
'nebula_vmtemplate',
'nebula_common',
'nebula_sql',
'nebula_log',

View File

@ -22,7 +22,6 @@ 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;
/**
@ -42,7 +41,7 @@ public class ImagePool extends Pool implements Iterable<Image>
*
* @param client XML-RPC Client.
*
* @see VirtualMachinePool#VirtualMachinePool(Client, int)
* @see ImagePool#ImagePool(Client, int)
*/
public ImagePool(Client client)
{
@ -58,8 +57,8 @@ public class ImagePool extends Pool implements Iterable<Image>
* {@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>
* <li>-1: Connected user's Images and public ones</li>
* <li>>= 0: UID User's Images</li>
* </ul>
*/
public ImagePool(Client client, int filter)
@ -85,8 +84,8 @@ public class ImagePool extends Pool implements Iterable<Image>
* {@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>
* <li>-1: Connected user's Images and public ones</li>
* <li>>= 0: UID User's Images</li>
* </ul>
* @return If successful the message contains the string
* with the information returned by OpenNebula.

View File

@ -0,0 +1,236 @@
/*******************************************************************************
* Copyright 2002-2011, 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.template;
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 template.
* It also offers static XML-RPC call wrappers.
*/
public class Template extends PoolElement
{
private static final String METHOD_PREFIX = "template.";
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 PUBLISH = METHOD_PREFIX + "publish";
/**
* Creates a new Template representation.
* @param id The template id.
* @param client XML-RPC Client.
*/
public Template(int id, Client client)
{
super(id, client);
}
/**
* @see PoolElement
*/
protected Template(Node xmlElement, Client client)
{
super(xmlElement, client);
}
// =================================
// Static XML-RPC methods
// =================================
/**
* Allocates a new Template in OpenNebula.
*
* @param client XML-RPC Client.
* @param description A string containing the template of the template.
* @return If successful the message contains the associated
* id generated for this Template.
*/
public static OneResponse allocate(Client client, String description)
{
return client.call(ALLOCATE, description);
}
/**
* Retrieves the information of the given Template.
*
* @param client XML-RPC Client.
* @param id The template id for the template 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 template from OpenNebula.
*
* @param client XML-RPC Client.
* @param id The template id of the target template we want to delete.
* @return A encapsulated response.
*/
public static OneResponse delete(Client client, int id)
{
return client.call(DELETE, id);
}
/**
* Modifies a template attribute.
*
* @param client XML-RPC Client.
* @param id The template id of the target template 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 template 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 a template attribute.
*
* @param client XML-RPC Client.
* @param id The template id of the target template we want to modify.
* @param att_name The name of the attribute to remove.
* @return If successful the message contains the template id.
*/
public static OneResponse rmattr(Client client, int id, String att_name)
{
return client.call(RMATTR, id, att_name);
}
/**
* Publishes or unpublishes a template.
*
* @param client XML-RPC Client.
* @param id The template id of the target template we want to modify.
* @param publish True for publishing, false for unpublishing.
* @return If successful the message contains the template 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 Template.
*
* @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 template from OpenNebula.
*
* @return A encapsulated response.
*/
public OneResponse delete()
{
return delete(client, id);
}
/**
* Modifies a template 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 template id.
*/
public OneResponse update(String att_name, String att_val)
{
return update(client, id, att_name, att_val);
}
/**
* Removes a template attribute.
*
* @param att_name The name of the attribute to remove.
* @return If successful the message contains the template id.
*/
public OneResponse rmattr(String att_name)
{
return rmattr(client, id, att_name);
}
/**
* Publishes or unpublishes the template.
*
* @param publish True for publishing, false for unpublishing.
* @return If successful the message contains the template id.
*/
public OneResponse publish(boolean publish)
{
return publish(client, id, publish);
}
/**
* Publishes the template.
*
* @return If successful the message contains the template id.
*/
public OneResponse publish()
{
return publish(true);
}
/**
* Unpublishes the template.
*
* @return If successful the message contains the template id.
*/
public OneResponse unpublish()
{
return publish(false);
}
// =================================
// Helpers
// =================================
/**
* Returns true if the template is public.
*
* @return True if the template is public.
*/
public boolean isPublic()
{
String isPub = xpath("PUBLIC");
return isPub != null && isPub.equals("1");
}
}

View File

@ -0,0 +1,132 @@
/*******************************************************************************
* Copyright 2002-2011, 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.template;
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 Template pool.
* It also offers static XML-RPC call wrappers.
*/
public class TemplatePool extends Pool implements Iterable<Template>
{
private static final String ELEMENT_NAME = "VMTEMPLATE";
private static final String INFO_METHOD = "templatepool.info";
private int filter;
/**
* Creates a new Template pool with the default filter flag value
* set to 0 (Templates belonging to user with UID 0)
*
* @param client XML-RPC Client.
*
* @see TemplatePool#TemplatePool(Client, int)
*/
public TemplatePool(Client client)
{
super(ELEMENT_NAME, client);
this.filter = 0;
}
/**
* Creates a new Template pool.
*
* @param client XML-RPC Client.
* @param filter Filter flag used by default in the method
* {@link TemplatePool#info()}. Possible values:
* <ul>
* <li><= -2: All Templates</li>
* <li>-1: Connected user's Templates and public ones</li>
* <li>>= 0: UID User's Templates</li>
* </ul>
*/
public TemplatePool(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 Template(node, client);
}
/**
* Retrieves all or part of the templates in the pool.
*
* @param client XML-RPC Client.
* @param filter Filter flag used by default in the method
* {@link TemplatePool#info()}. Possible values:
* <ul>
* <li><= -2: All Templates</li>
* <li>-1: Connected user's Templates and public ones</li>
* <li>>= 0: UID User's Templates</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
* Templates in the pool. The filter used is the one set in
* the constructor.
*
* @see TemplatePool#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<Template> iterator()
{
AbstractList<Template> ab = new AbstractList<Template>()
{
public int size()
{
return getLength();
}
public Template get(int index)
{
return (Template) item(index);
}
};
return ab.iterator();
}
}

View File

@ -19,6 +19,7 @@ package org.opennebula.client.vm;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.PoolElement;
import org.opennebula.client.template.Template;
import org.w3c.dom.Node;
/**
@ -134,6 +135,56 @@ public class VirtualMachine extends PoolElement{
return client.call(ALLOCATE, description);
}
/**
* Allocates a new VM in OpenNebula from a registered Template.
*
* @param client XML-RPC Client.
* @param templateId The source Template's ID
* @param newName Name for the new VM, replaces the Template's one.
* Can be null.
* @return If successful the message contains the associated
* id generated for this VM.
*/
public static OneResponse allocateFromTemplate(Client client,
int templateId, String newName)
{
String template = "TEMPLATE_ID = " + templateId;
if( newName != null )
{
template += "\nNAME = " + newName;
}
return allocate(client, template);
}
/**
* Allocates a new VM in OpenNebula from a registered Template.
*
* @param client XML-RPC Client.
* @param templateId The source Template's ID
* @return If successful the message contains the associated
* id generated for this VM.
*/
public static OneResponse allocateFromTemplate(Client client,
int templateId)
{
return allocateFromTemplate(client, templateId, null);
}
/**
* Allocates a new VM in OpenNebula from a registered Template.
*
* @param client XML-RPC Client.
* @param template The source Template.
* @return If successful the message contains the associated
* id generated for this VM.
*/
public static OneResponse allocateFromTemplate(Client client,
Template template)
{
return allocateFromTemplate(client, template.id());
}
/**
* Retrieves the information of the given VM.
*

View File

@ -0,0 +1,201 @@
/*******************************************************************************
* Copyright 2002-2011, 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.template.*;
import org.opennebula.client.vm.VirtualMachine;
public class TemplateTest
{
private static Template template;
private static TemplatePool templatePool;
private static Client client;
private static OneResponse res;
private static String name = "new_test_template";
private static String template_str =
"NAME = \"" + name + "\"\n" +
"ATT1 = \"val1\"";
/**
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception
{
client = new Client();
templatePool = new TemplatePool(client);
}
/**
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception
{
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception
{
res = Template.allocate(client, template_str);
int oid = res.isError() ? -1 : Integer.parseInt(res.getMessage());
template = new Template(oid, client);
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception
{
template.delete();
}
@Test
public void allocate()
{
template.delete();
res = Template.allocate(client, template_str);
assertTrue( !res.isError() );
int oid = res.isError() ? -1 : Integer.parseInt(res.getMessage());
template = new Template(oid, client);
templatePool.info();
boolean found = false;
for(Template temp : templatePool)
{
found = found || temp.getName().equals(name);
}
assertTrue( found );
}
@Test
public void info()
{
res = template.info();
assertTrue( !res.isError() );
// assertTrue( template.getId().equals("0") );
// assertTrue( template.id() == 0 );
assertTrue( template.getName().equals(name) );
}
@Test
public void update()
{
// Update an existing att.
res = template.update("ATT1", "new_val_1");
assertTrue( !res.isError() );
res = template.info();
assertTrue( !res.isError() );
assertTrue( template.xpath("TEMPLATE/ATT1").equals("new_val_1") );
// Create a new att.
res = template.update("ATT2", "new_val_2");
assertTrue( !res.isError() );
res = template.info();
assertTrue( !res.isError() );
assertTrue( template.xpath("TEMPLATE/ATT2").equals("new_val_2") );
}
@Test
public void rmattr()
{
res = template.rmattr("ATT1");
assertTrue( !res.isError() );
res = template.info();
assertTrue( !res.isError() );
assertTrue( template.xpath("ATT1").equals("") );
}
@Test
public void publish()
{
res = template.publish();
assertTrue( !res.isError() );
template.info();
assertTrue( template.isPublic() );
}
@Test
public void unpublish()
{
res = template.unpublish();
assertTrue( !res.isError() );
template.info();
assertTrue( !template.isPublic() );
}
@Test
public void attributes()
{
res = template.info();
assertTrue( !res.isError() );
// assertTrue( template.xpath("ID").equals("0") );
assertTrue( template.xpath("NAME").equals(name) );
}
@Test
public void delete()
{
res = template.delete();
assertTrue( !res.isError() );
res = template.info();
assertTrue( res.isError() );
}
@Test
public void allocateFromTemplate()
{
template.info();
assertTrue( !res.isError() );
res = VirtualMachine.allocateFromTemplate(client, template);
assertTrue( !res.isError() );
assertTrue( res.getMessage().equals("0") );
}
}

View File

@ -1,9 +1,27 @@
#!/bin/bash
if [ -z $ONE_LOCATION ]; then
echo "ONE_LOCATION not defined."
exit -1
fi
ONEDCONF_LOCATION="$ONE_LOCATION/etc/oned.conf"
if [ -f $ONEDCONF_LOCATION ]; then
echo "$ONEDCONF_LOCATION has to be overwritten, move it to a safe place."
exit -1
fi
cp oned.conf $ONEDCONF_LOCATION
export ONE_XMLRPC=http://localhost:2666/RPC2
./test.sh ClusterTest
./test.sh HostTest
./test.sh ImageTest
./test.sh SessionTest
./test.sh UserTest
./test.sh VirtualMachineTest
./test.sh VirtualNetworkTest
./test.sh VirtualNetworkTest
./test.sh TemplateTest

View File

@ -37,6 +37,8 @@ require 'OpenNebula/Host'
require 'OpenNebula/HostPool'
require 'OpenNebula/Cluster'
require 'OpenNebula/ClusterPool'
require 'OpenNebula/Template'
require 'OpenNebula/TemplatePool'
module OpenNebula

View File

@ -0,0 +1,126 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2011, 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. #
#--------------------------------------------------------------------------- #
require 'OpenNebula/Pool'
module OpenNebula
class Template < PoolElement
# ---------------------------------------------------------------------
# Constants and Class Methods
# ---------------------------------------------------------------------
TEMPLATE_METHODS = {
:allocate => "template.allocate",
:info => "template.info",
:update => "template.update",
:rmattr => "template.rmattr",
:publish => "template.publish",
:delete => "template.delete"
}
# Creates a Template description with just its identifier
# this method should be used to create plain Template objects.
# +id+ the id of the user
#
# Example:
# template = Template.new(Template.build_xml(3),rpc_client)
#
def Template.build_xml(pe_id=nil)
if pe_id
obj_xml = "<VMTEMPLATE><ID>#{pe_id}</ID></VMTEMPLATE>"
else
obj_xml = "<VMTEMPLATE></VMTEMPLATE>"
end
XMLElement.build_xml(obj_xml,'VMTEMPLATE')
end
# ---------------------------------------------------------------------
# Class constructor
# ---------------------------------------------------------------------
def initialize(xml, client)
super(xml,client)
@client = client
end
# ---------------------------------------------------------------------
# XML-RPC Methods for the Template Object
# ---------------------------------------------------------------------
# Retrieves the information of the given Template.
def info()
super(TEMPLATE_METHODS[:info], 'VMTEMPLATE')
end
# Allocates a new Template in OpenNebula
#
# +templatename+ A string containing the name of the Template.
def allocate(templatename)
super(TEMPLATE_METHODS[:allocate], templatename)
end
# Deletes the Template
def delete()
super(TEMPLATE_METHODS[:delete])
end
# Modifies a template attribute
#
# +name+ Name of the attribute to be changed
#
# +value+ New value for the attribute
def update(name, value)
super(TEMPLATE_METHODS[:update], name, value)
end
# Deletes a template attribute
#
# +name+ Name of the attribute to be deleted
def remove_attr(name)
do_rm_attr(name)
end
# Publishes the Template, to be used by other users
def publish
set_publish(true)
end
# Unplubishes the Image
def unpublish
set_publish(false)
end
private
def set_publish(published)
return Error.new('ID not defined') if !@pe_id
rc = @client.call(TEMPLATE_METHODS[:publish], @pe_id, published)
rc = nil if !OpenNebula.is_error?(rc)
return rc
end
def do_rm_attr(name)
return Error.new('ID not defined') if !@pe_id
rc = @client.call(TEMPLATE_METHODS[:rmattr], @pe_id, name)
rc = nil if !OpenNebula.is_error?(rc)
return rc
end
end
end

View File

@ -0,0 +1,55 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2011, 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. #
#--------------------------------------------------------------------------- #
require 'OpenNebula/Pool'
module OpenNebula
class TemplatePool < Pool
# ---------------------------------------------------------------------
# Constants and Class attribute accessors
# ---------------------------------------------------------------------
TEMPLATE_POOL_METHODS = {
:info => "templatepool.info"
}
# ---------------------------------------------------------------------
# Class constructor & Pool Methods
# ---------------------------------------------------------------------
# +client+ a Client object that represents an XML-RPC connection
# +user_id+ used to refer to a Pool with Templates from that user
def initialize(client, user_id=-1)
super('VMTEMPLATE_POOL','VMTEMPLATE',client)
@user_id = user_id
end
# Factory method to create Template objects
def factory(element_xml)
OpenNebula::Template.new(element_xml,@client)
end
# ---------------------------------------------------------------------
# XML-RPC Methods for the Template Object
# ---------------------------------------------------------------------
# Retrieves all the Templates in the pool.
def info()
super(TEMPLATE_POOL_METHODS[:info], @user_id)
end
end
end

View File

@ -108,3 +108,38 @@ int PoolObjectSQL::drop(SqlDB *db)
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
const char * PoolObjectSQL::error_attribute_name = "ERROR";
void PoolObjectSQL::set_template_error_message(const string& message)
{
VectorAttribute * attr;
map<string,string> error_value;
char str[26];
time_t the_time;
the_time = time(NULL);
#ifdef SOLARIS
ctime_r(&(the_time),str,sizeof(char)*26);
#else
ctime_r(&(the_time),str);
#endif
str[24] = '\0'; // Get rid of final enter character
error_value.insert(make_pair("TIMESTAMP",str));
error_value.insert(make_pair("MESSAGE",message));
attr = new VectorAttribute(error_attribute_name,error_value);
obj_template->set(attr);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -214,7 +214,7 @@ void RequestManager::do_action(
void RequestManager::register_xml_methods()
{
xmlrpc_c::methodPtr vm_allocate(new
RequestManager::VirtualMachineAllocate(vmpool, vnpool, ipool, upool));
RequestManager::VirtualMachineAllocate(vmpool,vnpool,ipool,tpool,upool));
xmlrpc_c::methodPtr vm_deploy(new
RequestManager::VirtualMachineDeploy(vmpool,hpool,upool));
@ -233,7 +233,28 @@ void RequestManager::register_xml_methods()
xmlrpc_c::methodPtr vm_pool_info(new
RequestManager::VirtualMachinePoolInfo(vmpool,upool));
xmlrpc_c::methodPtr template_allocate(new
RequestManager::TemplateAllocate(tpool,upool));
xmlrpc_c::methodPtr template_delete(new
RequestManager::TemplateDelete(tpool, upool));
xmlrpc_c::methodPtr template_info(new
RequestManager::TemplateInfo(tpool, upool));
xmlrpc_c::methodPtr template_update(new
RequestManager::TemplateUpdate(tpool, upool));
xmlrpc_c::methodPtr template_rm_attribute(new
RequestManager::TemplateRemoveAttribute(tpool, upool));
xmlrpc_c::methodPtr template_publish(new
RequestManager::TemplatePublish(tpool, upool));
xmlrpc_c::methodPtr template_pool_info(new
RequestManager::TemplatePoolInfo(tpool,upool));
xmlrpc_c::methodPtr host_allocate(new
RequestManager::HostAllocate(hpool,upool));
@ -340,7 +361,18 @@ void RequestManager::register_xml_methods()
RequestManagerRegistry.addMethod("one.vm.savedisk", vm_savedisk);
RequestManagerRegistry.addMethod("one.vmpool.info", vm_pool_info);
/* VM Template related methods*/
RequestManagerRegistry.addMethod("one.template.allocate",template_allocate);
RequestManagerRegistry.addMethod("one.template.delete", template_delete);
RequestManagerRegistry.addMethod("one.template.info", template_info);
RequestManagerRegistry.addMethod("one.template.update", template_update);
RequestManagerRegistry.addMethod("one.template.rmattr", template_rm_attribute);
RequestManagerRegistry.addMethod("one.template.publish", template_publish);
RequestManagerRegistry.addMethod("one.templatepool.info",template_pool_info);
/* Host related methods*/
RequestManagerRegistry.addMethod("one.host.allocate", host_allocate);

View File

@ -30,10 +30,11 @@ void RequestManager::VirtualMachineAllocate::execute(
string str_template;
string error_str;
string user_name;
string template_id_str = "TEMPLATE_ID";;
const string method_name = "VirtualMachineAllocate";
int vid, uid;
int vid, uid, tid;
int rc;
ostringstream oss;
@ -42,7 +43,13 @@ void RequestManager::VirtualMachineAllocate::execute(
xmlrpc_c::value_array * arrayresult;
VirtualMachineTemplate * vm_template;
VirtualMachineTemplate * vm_template_aux;
User * user;
VMTemplate * registered_template;
bool using_template_pool;
int template_owner;
bool template_public;
char * error_msg = 0;
int num;
@ -77,11 +84,66 @@ void RequestManager::VirtualMachineAllocate::execute(
goto error_parse;
}
//--------------------------------------------------------------------------
// Look for a template id
//--------------------------------------------------------------------------
using_template_pool = vm_template->get(template_id_str, tid);
if( using_template_pool )
{
string name_str = "NAME";
string name_val;
ostringstream template_id_val;
registered_template = VirtualMachineAllocate::tpool->get(tid, true);
if( registered_template == 0 )
{
goto error_template_get;
}
// Use the template contents
vm_template_aux = registered_template->clone_template();
template_owner = registered_template->get_uid();
template_public = registered_template->isPublic();
registered_template->unlock();
// Set NAME & TEMPLATE_ID for the new template
vm_template->get(name_str,name_val);
if ( !name_val.empty() )
{
vm_template_aux->erase(name_str);
vm_template_aux->set(new SingleAttribute(name_str,name_val));
}
vm_template_aux->erase(template_id_str);
template_id_val << tid;
vm_template_aux->set(new
SingleAttribute(template_id_str,template_id_val.str()));
delete vm_template;
vm_template = vm_template_aux;
}
if ( uid != 0 )
{
AuthRequest ar(uid);
string t64;
if( using_template_pool )
{
ar.add_auth(AuthRequest::TEMPLATE,
tid,
AuthRequest::USE,
template_owner,
template_public);
}
num = vm_template->get("DISK",vectors);
for(int i=0; i<num; i++)
@ -113,11 +175,22 @@ void RequestManager::VirtualMachineAllocate::execute(
VirtualMachineAllocate::vnpool->authorize_nic(vector,uid,&ar);
}
ar.add_auth(AuthRequest::VM,
vm_template->to_xml(t64),
AuthRequest::CREATE,
uid,
false);
if( using_template_pool )
{
ar.add_auth(AuthRequest::VM,
vm_template->to_xml(t64),
AuthRequest::INSTANTIATE,
uid,
false);
}
else
{
ar.add_auth(AuthRequest::VM,
vm_template->to_xml(t64),
AuthRequest::CREATE,
uid,
false);
}
if (UserPool::authorize(ar) == -1)
{
@ -165,6 +238,11 @@ void RequestManager::VirtualMachineAllocate::execute(
return;
error_template_get:
oss.str(get_error(method_name, "TEMPLATE", tid));
delete vm_template;
goto error_common;
error_user_get:
oss.str(get_error(method_name, "USER", uid));

View File

@ -29,7 +29,6 @@ void RequestManager::ImageInfo::execute(
string session;
int iid;
int uid; // Image owner user id
int rc; // Requesting user id
Image * image;
@ -47,16 +46,6 @@ void RequestManager::ImageInfo::execute(
session = xmlrpc_c::value_string(paramList.getString(0));
iid = xmlrpc_c::value_int (paramList.getInt(1));
// Get image from the ImagePool
image = ImageInfo::ipool->get(iid,true);
if ( image == 0 )
{
goto error_image_get;
}
uid = image->get_uid();
// Check if it is a valid user
rc = ImageInfo::upool->authenticate(session);
@ -64,6 +53,14 @@ void RequestManager::ImageInfo::execute(
{
goto error_authenticate;
}
// Get image from the ImagePool
image = ImageInfo::ipool->get(iid,true);
if ( image == 0 )
{
goto error_image_get;
}
oss << *image;
@ -87,7 +84,6 @@ error_image_get:
error_authenticate:
oss.str(authenticate_error(method_name));
image->unlock();
goto error_common;
error_common:

View File

@ -65,7 +65,6 @@ void RequestManager::ImagePoolInfo::execute(
switch(filter_flag)
{
case -2:
// TODO define authentication bug #278
break;
case -1:
where_string << "UID=" << rc << " OR PUBLIC=1";

View File

@ -0,0 +1,183 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, 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. */
/* -------------------------------------------------------------------------- */
#include "RequestManager.h"
#include "NebulaLog.h"
#include "Nebula.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::TemplateAllocate::execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retval)
{
string session;
string str_template;
string error_str;
string user_name;
const string method_name = "TemplateAllocate";
int oid, uid;
int rc;
ostringstream oss;
vector<xmlrpc_c::value> arrayData;
xmlrpc_c::value_array * arrayresult;
VirtualMachineTemplate * template_contents;
User * user;
char * error_msg = 0;
NebulaLog::log("ReM",Log::DEBUG,"TemplateAllocate invoked");
session = xmlrpc_c::value_string(paramList.getString(0));
str_template = xmlrpc_c::value_string(paramList.getString(1));
str_template += "\n";
//--------------------------------------------------------------------------
// Authenticate the user
//--------------------------------------------------------------------------
uid = TemplateAllocate::upool->authenticate(session);
if (uid == -1)
{
goto error_authenticate;
}
//--------------------------------------------------------------------------
// Check the template syntax
//--------------------------------------------------------------------------
template_contents = new VirtualMachineTemplate;
rc = template_contents->parse(str_template,&error_msg);
if ( rc != 0 )
{
goto error_parse;
}
//--------------------------------------------------------------------------
// Authorize this request
//--------------------------------------------------------------------------
if ( uid != 0 )
{
AuthRequest ar(uid);
string t64;
ar.add_auth(AuthRequest::TEMPLATE,
template_contents->to_xml(t64),
AuthRequest::CREATE,
uid,
false);
if (UserPool::authorize(ar) == -1)
{
goto error_authorize;
}
}
//--------------------------------------------------------------------------
// Get the User Name
//--------------------------------------------------------------------------
user = TemplateAllocate::upool->get(uid,true);
if ( user == 0 )
{
goto error_user_get;
}
user_name = user->get_name();
user->unlock();
//--------------------------------------------------------------------------
// Allocate the VMTemplate
//--------------------------------------------------------------------------
rc = TemplateAllocate::tpool->allocate(uid,
user_name,
template_contents,
&oid,
error_str);
if ( rc < 0 )
{
goto error_allocate;
}
arrayData.push_back(xmlrpc_c::value_boolean(true));
arrayData.push_back(xmlrpc_c::value_int(oid));
// Copy arrayresult into retval mem space
arrayresult = new xmlrpc_c::value_array(arrayData);
*retval = *arrayresult;
delete arrayresult; // and get rid of the original
return;
error_user_get:
oss.str(get_error(method_name, "USER", uid));
delete template_contents;
goto error_common;
error_authenticate:
oss.str(authenticate_error(method_name));
goto error_common;
error_authorize:
oss.str(authorization_error(method_name, "CREATE", "TEMPLATE", uid, -1));
delete template_contents;
goto error_common;
error_parse:
oss << action_error(method_name, "PARSE", "VM TEMPLATE",-2,rc);
if (error_msg != 0)
{
oss << ". Reason: " << error_msg;
free(error_msg);
}
delete template_contents;
goto error_common;
error_allocate:
oss << action_error(method_name, "CREATE", "TEMPLATE", -2, 0);
oss << " " << error_str;
goto error_common;
error_common:
arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE
arrayData.push_back(xmlrpc_c::value_string(oss.str()));
NebulaLog::log("ReM",Log::ERROR,oss);
xmlrpc_c::value_array arrayresult_error(arrayData);
*retval = arrayresult_error;
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -0,0 +1,153 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, 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. */
/* -------------------------------------------------------------------------- */
#include "RequestManager.h"
#include "NebulaLog.h"
#include "Nebula.h"
#include "AuthManager.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::TemplateDelete::execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retval)
{
string session;
int oid;
int uid;
int rc;
int owner;
bool is_public;
VMTemplate * vm_template;
ostringstream oss;
const string method_name = "TemplateDelete";
vector<xmlrpc_c::value> arrayData;
xmlrpc_c::value_array * arrayresult;
NebulaLog::log("ReM",Log::DEBUG,"TemplateDelete invoked");
session = xmlrpc_c::value_string(paramList.getString(0));
oid = xmlrpc_c::value_int (paramList.getInt(1));
// First, we need to authenticate the user
uid = TemplateDelete::upool->authenticate(session);
if ( uid == -1 )
{
goto error_authenticate;
}
// Get template from the pool
vm_template = TemplateDelete::tpool->get(oid,true);
if ( vm_template == 0 )
{
goto error_get;
}
owner = vm_template->get_uid();
is_public = vm_template->isPublic();
vm_template->unlock();
//Authorize the operation
if ( uid != 0 ) // uid == 0 means oneadmin
{
AuthRequest ar(uid);
ar.add_auth(AuthRequest::TEMPLATE,
oid,
AuthRequest::DELETE,
owner,
is_public);
if (UserPool::authorize(ar) == -1)
{
goto error_authorize;
}
}
// Get template from the pool
vm_template = TemplateDelete::tpool->get(oid,true);
if ( vm_template == 0 )
{
goto error_get;
}
rc = TemplateDelete::tpool->drop(vm_template);
vm_template->unlock();
if ( rc < 0 )
{
goto error_delete;
}
arrayData.push_back(xmlrpc_c::value_boolean(true));
arrayData.push_back(xmlrpc_c::value_int(oid));
// Copy arrayresult into retval mem space
arrayresult = new xmlrpc_c::value_array(arrayData);
*retval = *arrayresult;
delete arrayresult; // and get rid of the original
return;
error_authenticate:
oss.str(authenticate_error(method_name));
goto error_common;
error_get:
oss.str(get_error(method_name, "TEMPLATE", oid));
goto error_common;
error_authorize:
oss.str(authorization_error(method_name, "DELETE", "TEMPLATE", uid, oid));
goto error_common;
error_delete:
oss.str(action_error(method_name, "DELETE", "TEMPLATE", oid, rc));
vm_template->unlock();
goto error_common;
error_common:
arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE
arrayData.push_back(xmlrpc_c::value_string(oss.str()));
NebulaLog::log("ReM",Log::ERROR,oss);
xmlrpc_c::value_array arrayresult_error(arrayData);
*retval = arrayresult_error;
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -0,0 +1,107 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, 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. */
/* -------------------------------------------------------------------------- */
#include "RequestManager.h"
#include "NebulaLog.h"
#include "AuthManager.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::TemplateInfo::execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retval)
{
string session;
int oid;
int uid; // owner user id
int rc; // Requesting user id
VMTemplate * vm_template;
ostringstream oss;
const string method_name = "TemplateInfo";
/* -- RPC specific vars -- */
vector<xmlrpc_c::value> arrayData;
xmlrpc_c::value_array * arrayresult;
NebulaLog::log("ReM",Log::DEBUG,"TemplateInfo method invoked");
// Get the parameters
session = xmlrpc_c::value_string(paramList.getString(0));
oid = xmlrpc_c::value_int (paramList.getInt(1));
// Get template from the pool
vm_template = TemplateInfo::tpool->get(oid,true);
if ( vm_template == 0 )
{
goto error_get;
}
uid = vm_template->get_uid();
// Check if it is a valid user
rc = TemplateInfo::upool->authenticate(session);
if ( rc == -1 )
{
goto error_authenticate;
}
oss << *vm_template;
vm_template->unlock();
// All nice, return the host info to the client
arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS
arrayData.push_back(xmlrpc_c::value_string(oss.str()));
// Copy arrayresult into retval mem space
arrayresult = new xmlrpc_c::value_array(arrayData);
*retval = *arrayresult;
delete arrayresult; // and get rid of the original
return;
error_get:
oss.str(get_error(method_name, "TEMPLATE", oid));
goto error_common;
error_authenticate:
oss.str(authenticate_error(method_name));
vm_template->unlock();
goto error_common;
error_common:
arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE
arrayData.push_back(xmlrpc_c::value_string(oss.str()));
NebulaLog::log("ReM",Log::ERROR,oss);
xmlrpc_c::value_array arrayresult_error(arrayData);
*retval = arrayresult_error;
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -0,0 +1,124 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, 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. */
/* -------------------------------------------------------------------------- */
#include "RequestManager.h"
#include "NebulaLog.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::TemplatePoolInfo::execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retval)
{
string session;
ostringstream oss;
ostringstream where_string;
int rc;
int filter_flag;
const string method_name = "TemplatePoolInfo";
/* -- RPC specific vars -- */
vector<xmlrpc_c::value> arrayData;
xmlrpc_c::value_array * arrayresult;
NebulaLog::log("ReM",Log::DEBUG,"TemplatePoolInfo method invoked");
// Get the parameters
session = xmlrpc_c::value_string(paramList.getString(0));
filter_flag = xmlrpc_c::value_int(paramList.getInt(1));
// Check if it is a valid user
rc = TemplatePoolInfo::upool->authenticate(session);
if ( rc == -1 )
{
goto error_authenticate;
}
/** Filter flag meaning table
* -2 :: All Templates
* -1 :: User's Templates AND public templates belonging to any user
* >= 0 :: UID User's Templates
**/
if ( filter_flag < -2 )
{
goto error_filter_flag;
}
switch(filter_flag)
{
case -2:
break;
case -1:
where_string << "UID=" << rc << " OR PUBLIC=1";
break;
default:
where_string << "UID=" << filter_flag;
}
// Call the template pool dump
rc = TemplatePoolInfo::tpool->dump(oss,where_string.str());
if ( rc != 0 )
{
goto error_dump;
}
// All nice, return pool info to the client
arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS
arrayData.push_back(xmlrpc_c::value_string(oss.str()));
arrayresult = new xmlrpc_c::value_array(arrayData);
// Copy arrayresult into retval mem space
*retval = *arrayresult;
// and get rid of the original
delete arrayresult;
return;
error_authenticate:
oss.str(authenticate_error(method_name));
goto error_common;
error_filter_flag:
oss << "Incorrect filter_flag, must be >= -2.";
goto error_common;
error_dump:
oss.str(get_error(method_name, "TEMPLATE", -1));
goto error_common;
error_common:
arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE
arrayData.push_back(xmlrpc_c::value_string(oss.str()));
NebulaLog::log("ReM",Log::ERROR,oss);
xmlrpc_c::value_array arrayresult_error(arrayData);
*retval = arrayresult_error;
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -0,0 +1,158 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, 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. */
/* -------------------------------------------------------------------------- */
#include "RequestManager.h"
#include "NebulaLog.h"
#include "Nebula.h"
#include "AuthManager.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::TemplatePublish::execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retval)
{
string session;
int oid;
bool publish_flag;
int uid;
int owner;
bool is_public;
VMTemplate * vm_template;
bool response;
ostringstream oss;
const string method_name = "TemplatePublish";
vector<xmlrpc_c::value> arrayData;
xmlrpc_c::value_array * arrayresult;
NebulaLog::log("ReM",Log::DEBUG,"TemplatePublish invoked");
session = xmlrpc_c::value_string (paramList.getString(0));
oid = xmlrpc_c::value_int (paramList.getInt(1));
publish_flag = xmlrpc_c::value_boolean(paramList.getBoolean(2));
// First, we need to authenticate the user
uid = TemplatePublish::upool->authenticate(session);
if ( uid == -1 )
{
goto error_authenticate;
}
// Get template from the pool
vm_template = TemplatePublish::tpool->get(oid,true);
if ( vm_template == 0 )
{
goto error_get;
}
owner = vm_template->get_uid();
is_public = vm_template->isPublic();
vm_template->unlock();
//Authorize the operation
if ( uid != 0 ) // uid == 0 means oneadmin
{
AuthRequest ar(uid);
ar.add_auth(AuthRequest::TEMPLATE,
oid,
AuthRequest::MANAGE,
owner,
is_public);
if (UserPool::authorize(ar) == -1)
{
goto error_authorize;
}
}
// Get the template locked again
vm_template = TemplatePublish::tpool->get(oid,true);
if ( vm_template == 0 )
{
goto error_get;
}
response = vm_template->publish(publish_flag);
if (!response)
{
vm_template->unlock();
goto error_publish;
}
TemplatePublish::tpool->update(vm_template);
vm_template->unlock();
arrayData.push_back(xmlrpc_c::value_boolean(true));
arrayData.push_back(xmlrpc_c::value_int(oid));
// Copy arrayresult into retval mem space
arrayresult = new xmlrpc_c::value_array(arrayData);
*retval = *arrayresult;
delete arrayresult; // and get rid of the original
return;
error_authenticate:
oss.str(authenticate_error(method_name));
goto error_common;
error_get:
oss.str(get_error(method_name, "TEMPLATE", oid));
goto error_common;
error_authorize:
oss.str(authorization_error(method_name, "MANAGE", "TEMPLATE", uid, oid));
goto error_common;
error_publish:
oss.str(action_error(method_name, "MANAGE", "TEMPLATE", oid, 0));
goto error_common;
error_common:
arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE
arrayData.push_back(xmlrpc_c::value_string(oss.str()));
NebulaLog::log("ReM",Log::ERROR,oss);
xmlrpc_c::value_array arrayresult_error(arrayData);
*retval = arrayresult_error;
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -0,0 +1,159 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, 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. */
/* -------------------------------------------------------------------------- */
#include "RequestManager.h"
#include "NebulaLog.h"
#include "Nebula.h"
#include "AuthManager.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::TemplateRemoveAttribute::execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retval)
{
string session;
string name;
int oid;
int uid;
int rc;
int owner;
bool is_public;
VMTemplate * vm_template;
ostringstream oss;
const string method_name = "TemplateRemoveAttribute";
vector<xmlrpc_c::value> arrayData;
xmlrpc_c::value_array * arrayresult;
NebulaLog::log("ReM",Log::DEBUG,"TemplateRemoveAttribute invoked");
session = xmlrpc_c::value_string(paramList.getString(0));
oid = xmlrpc_c::value_int (paramList.getInt(1));
name = xmlrpc_c::value_string(paramList.getString(2));
// First, we need to authenticate the user
uid = TemplateRemoveAttribute::upool->authenticate(session);
if ( uid == -1 )
{
goto error_authenticate;
}
// Get object from the pool
vm_template = TemplateRemoveAttribute::tpool->get(oid,true);
if ( vm_template == 0 )
{
goto error_get;
}
owner = vm_template->get_uid();
is_public = vm_template->isPublic();
vm_template->unlock();
//Authorize the operation
if ( uid != 0 ) // uid == 0 means oneadmin
{
AuthRequest ar(uid);
ar.add_auth(AuthRequest::TEMPLATE,
oid,
AuthRequest::MANAGE,
owner,
is_public);
if (UserPool::authorize(ar) == -1)
{
goto error_authorize;
}
}
// Get object from the pool
vm_template = TemplateRemoveAttribute::tpool->get(oid,true);
if ( vm_template == 0 )
{
goto error_get;
}
rc = vm_template->remove_template_attribute(name);
if(rc == 0)
{
rc = TemplateRemoveAttribute::tpool->update(vm_template);
}
if ( rc < 0 )
{
goto error_remove_attribute;
}
vm_template->unlock();
arrayData.push_back(xmlrpc_c::value_boolean(true));
arrayData.push_back(xmlrpc_c::value_int(oid));
// Copy arrayresult into retval mem space
arrayresult = new xmlrpc_c::value_array(arrayData);
*retval = *arrayresult;
delete arrayresult; // and get rid of the original
return;
error_authenticate:
oss.str(authenticate_error(method_name));
goto error_common;
error_get:
oss.str(get_error(method_name, "TEMPLATE", oid));
goto error_common;
error_authorize:
oss.str(authorization_error(method_name, "MANAGE", "TEMPLATE", uid, oid));
goto error_common;
error_remove_attribute:
oss.str(action_error(method_name, "PUBLISH/UNPUBLISH", "TEMPLATE", oid, rc));
vm_template->unlock();
goto error_common;
error_common:
arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE
arrayData.push_back(xmlrpc_c::value_string(oss.str()));
NebulaLog::log("ReM",Log::ERROR,oss);
xmlrpc_c::value_array arrayresult_error(arrayData);
*retval = arrayresult_error;
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -0,0 +1,160 @@
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2011, 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. */
/* -------------------------------------------------------------------------- */
#include "RequestManager.h"
#include "NebulaLog.h"
#include "Nebula.h"
#include "AuthManager.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void RequestManager::TemplateUpdate::execute(
xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retval)
{
string session;
int oid;
int uid;
string name;
string value;
int rc;
int owner;
bool is_public;
VMTemplate * vm_template;
ostringstream oss;
vector<xmlrpc_c::value> arrayData;
xmlrpc_c::value_array * arrayresult;
const string method_name = "TemplateUpdate";
NebulaLog::log("ReM",Log::DEBUG,"TemplateUpdate invoked");
session = xmlrpc_c::value_string(paramList.getString(0));
oid = xmlrpc_c::value_int (paramList.getInt(1));
name = xmlrpc_c::value_string(paramList.getString(2));
value = xmlrpc_c::value_string(paramList.getString(3));
// First, we need to authenticate the user
uid = TemplateUpdate::upool->authenticate(session);
if ( uid == -1 )
{
goto error_authenticate;
}
// Get template from the pool
vm_template = TemplateUpdate::tpool->get(oid,true);
if ( vm_template == 0 )
{
goto error_get;
}
owner = vm_template->get_uid();
is_public = vm_template->isPublic();
vm_template->unlock();
//Authorize the operation
if ( uid != 0 ) // uid == 0 means oneadmin
{
AuthRequest ar(uid);
ar.add_auth(AuthRequest::TEMPLATE,
oid,
AuthRequest::MANAGE,
owner,
is_public);
if (UserPool::authorize(ar) == -1)
{
goto error_authorize;
}
}
// Get template from the pool
vm_template = TemplateUpdate::tpool->get(oid,true);
if ( vm_template == 0 )
{
goto error_get;
}
rc = vm_template->replace_template_attribute(name, value);
if(rc == 0)
{
rc = TemplateUpdate::tpool->update(vm_template);
}
if ( rc < 0 )
{
goto error_update;
}
vm_template->unlock();
arrayData.push_back(xmlrpc_c::value_boolean(true));
arrayData.push_back(xmlrpc_c::value_int(oid));
// Copy arrayresult into retval mem space
arrayresult = new xmlrpc_c::value_array(arrayData);
*retval = *arrayresult;
delete arrayresult; // and get rid of the original
return;
error_authenticate:
oss.str(authenticate_error(method_name));
goto error_common;
error_get:
oss.str(get_error(method_name, "TEMPLATE", oid));
goto error_common;
error_authorize:
oss.str(authorization_error(method_name, "MANAGE", "TEMPLATE", uid, oid));
goto error_common;
error_update:
oss.str(action_error(method_name, "UPDATE ATTRIBUTE", "TEMPLATE", oid, rc));
vm_template->unlock();
goto error_common;
error_common:
arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE
arrayData.push_back(xmlrpc_c::value_string(oss.str()));
NebulaLog::log("ReM",Log::ERROR,oss);
xmlrpc_c::value_array arrayresult_error(arrayData);
*retval = arrayresult_error;
return;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

View File

@ -30,7 +30,6 @@ void RequestManager::VirtualNetworkDelete::execute(
string name;
int nid;
int uid;
VirtualNetwork * vn;
@ -99,8 +98,6 @@ void RequestManager::VirtualNetworkDelete::execute(
goto error_vn_get;
}
uid = vn->get_uid();
rc = vnpool->drop(vn);
vn->unlock();

View File

@ -61,7 +61,14 @@ source_files=[
'RequestManagerUserDelete.cc',
'RequestManagerUserChangePassword.cc',
'RequestManagerUserInfo.cc',
'RequestManagerUserPoolInfo.cc'
'RequestManagerUserPoolInfo.cc',
'RequestManagerTemplateAllocate.cc',
'RequestManagerTemplateDelete.cc',
'RequestManagerTemplateInfo.cc',
'RequestManagerTemplateUpdate.cc',
'RequestManagerTemplateRemoveAttribute.cc',
'RequestManagerTemplatePublish.cc',
'RequestManagerTemplatePoolInfo.cc',
]
# Build library

View File

@ -39,7 +39,7 @@ public:
*/
HostXML * get(int oid) const
{
return static_cast<const HostXML *>(PoolXML::get(oid));
return static_cast<HostXML *>(PoolXML::get(oid));
};
protected:

View File

@ -87,9 +87,8 @@ public:
update_from_str(message);
vector<xmlNodePtr> nodes;
int num_objs;
num_objs = get_suitable_nodes(nodes);
get_suitable_nodes(nodes);
for (unsigned int i=0 ;
i < nodes.size() && ( pool_limit <= 0 || i < pool_limit ) ;

View File

@ -68,16 +68,9 @@ int MySqlDB::exec(ostringstream& cmd, Callbackable* obj)
const char * c_str;
string str;
int (*callback)(void*,int,char**,char**);
void * arg;
str = cmd.str();
c_str = str.c_str();
callback = 0;
arg = 0;
lock();
rc = mysql_query(db, c_str);

View File

@ -20,6 +20,7 @@ include OpenNebula
require 'OpenNebulaJSON/ClusterJSON'
require 'OpenNebulaJSON/HostJSON'
require 'OpenNebulaJSON/ImageJSON'
require 'OpenNebulaJSON/TemplateJSON'
require 'OpenNebulaJSON/JSONUtils'
require 'OpenNebulaJSON/PoolJSON'
require 'OpenNebulaJSON/UserJSON'

View File

@ -21,6 +21,7 @@ module OpenNebulaJSON
class VirtualMachinePoolJSON < OpenNebula::VirtualMachinePool; include JSONUtils; end
class VirtualNetworkPoolJSON < OpenNebula::VirtualNetworkPool; include JSONUtils; end
class ImagePoolJSON < OpenNebula::ImagePool; include JSONUtils; end
class TemplatePoolJSON < OpenNebula::TemplatePool; include JSONUtils; end
class ClusterPoolJSON < OpenNebula::ClusterPool; include JSONUtils; end
class UserPoolJSON < OpenNebula::UserPool; include JSONUtils; end
end

View File

@ -0,0 +1,65 @@
# -------------------------------------------------------------------------- #
# Copyright 2002-2011, 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. #
#--------------------------------------------------------------------------- #
require 'OpenNebulaJSON/JSONUtils'
module OpenNebulaJSON
class TemplateJSON < OpenNebula::Template
include JSONUtils
def create(template_json)
template_hash = parse_json(template_json, 'vmtemplate')
if OpenNebula.is_error?(template_hash)
return template_hash
end
if template_hash['template_raw']
template = template_hash['template_raw']
else
template = template_to_str(template_hash)
end
self.allocate(template)
end
def perform_action(template_json)
action_hash = parse_json(template_json, 'action')
if OpenNebula.is_error?(action_hash)
return action_hash
end
rc = case action_hash['perform']
when "publish" then self.publish
when "rm_attr" then self.remove_attr(action_hash['params'])
when "unpublish" then self.unpublish
when "update" then self.update(action_hash['params'])
else
error_msg = "#{action_hash['perform']} action not " <<
" available for this resource"
OpenNebula::Error.new(error_msg)
end
end
def update(params=Hash.new)
super(params['name'], params['value'])
end
def remove_attr(params=Hash.new)
super(params['name'])
end
end
end

View File

@ -28,6 +28,12 @@ module OpenNebulaJSON
if vm_hash['vm_raw']
template = vm_hash['vm_raw']
elsif vm_hash['template_id']
template_id = vm_hash['template_id']
template = "TEMPLATE_ID = #{template_id}"
template << "\nNAME = #{vm_hash[:vm_name]}" if vm_hash[:vm_name]
else
template = template_to_str(vm_hash)
end
@ -55,7 +61,7 @@ module OpenNebulaJSON
when "restart" then self.restart
when "saveas" then self.save_as(action_hash['params'])
when "shutdown" then self.shutdown
when "resubmit" then self.resubmit
when "resubmit" then self.resubmit
else
error_msg = "#{action_hash['perform']} action not " <<
" available for this resource"

View File

@ -68,12 +68,13 @@ class SunstoneServer
def get_pool(kind)
user_flag = -2
pool = case kind
when "cluster" then ClusterPoolJSON.new(@client)
when "host" then HostPoolJSON.new(@client)
when "image" then ImagePoolJSON.new(@client, user_flag)
when "vm" then VirtualMachinePoolJSON.new(@client, user_flag)
when "vnet" then VirtualNetworkPoolJSON.new(@client, user_flag)
when "user" then UserPoolJSON.new(@client)
when "cluster" then ClusterPoolJSON.new(@client)
when "host" then HostPoolJSON.new(@client)
when "image" then ImagePoolJSON.new(@client, user_flag)
when "template" then TemplatePoolJSON.new(@client, user_flag)
when "vm" then VirtualMachinePoolJSON.new(@client, user_flag)
when "vnet" then VirtualNetworkPoolJSON.new(@client, user_flag)
when "user" then UserPoolJSON.new(@client)
else
error = Error.new("Error: #{kind} resource not supported")
return [404, error.to_json]
@ -104,12 +105,13 @@ class SunstoneServer
############################################################################
def create_resource(kind, template)
resource = case kind
when "cluster" then ClusterJSON.new(Cluster.build_xml, @client)
when "host" then HostJSON.new(Host.build_xml, @client)
when "image" then ImageJSON.new(Image.build_xml, @client)
when "vm" then VirtualMachineJSON.new(VirtualMachine.build_xml,@client)
when "vnet" then VirtualNetworkJSON.new(VirtualNetwork.build_xml, @client)
when "user" then UserJSON.new(User.build_xml, @client)
when "cluster" then ClusterJSON.new(Cluster.build_xml, @client)
when "host" then HostJSON.new(Host.build_xml, @client)
when "image" then ImageJSON.new(Image.build_xml, @client)
when "template" then TemplateJSON.new(Template.build_xml, @client)
when "vm" then VirtualMachineJSON.new(VirtualMachine.build_xml,@client)
when "vnet" then VirtualNetworkJSON.new(VirtualNetwork.build_xml, @client)
when "user" then UserJSON.new(User.build_xml, @client)
else
error = Error.new("Error: #{kind} resource not supported")
return [404, error.to_json]
@ -217,12 +219,13 @@ class SunstoneServer
def retrieve_resource(kind, id)
resource = case kind
when "cluster" then ClusterJSON.new_with_id(id, @client)
when "host" then HostJSON.new_with_id(id, @client)
when "image" then ImageJSON.new_with_id(id, @client)
when "vm" then VirtualMachineJSON.new_with_id(id, @client)
when "vnet" then VirtualNetworkJSON.new_with_id(id, @client)
when "user" then UserJSON.new_with_id(id, @client)
when "cluster" then ClusterJSON.new_with_id(id, @client)
when "host" then HostJSON.new_with_id(id, @client)
when "image" then ImageJSON.new_with_id(id, @client)
when "template" then TemplateJSON.new_with_id(id, @client)
when "vm" then VirtualMachineJSON.new_with_id(id, @client)
when "vnet" then VirtualNetworkJSON.new_with_id(id, @client)
when "user" then UserJSON.new_with_id(id, @client)
else
error = Error.new("Error: #{kind} resource not supported")
return error

View File

@ -230,7 +230,7 @@ div.tip span.ui-icon{
div.tip span.man_icon {
display:none;
}
.kvm .man_icon,.xen .man_icon,.img_man .man_icon {
.img_man .man_icon {
display:inline-block!important;
}

View File

@ -142,7 +142,7 @@ var OpenNebula = {
{
return Error('Incorrect Pool');
}
var p_pool = [];
if (response[pool_name]) {
@ -1931,5 +1931,301 @@ var OpenNebula = {
}
});
}
},
"Template" : {
"resource" : "VMTEMPLATE",
"create" : function(params)
{
var callback = params.success;
var callback_error = params.error;
var data = params.data;
var resource = OpenNebula.Template.resource;
var request = OpenNebula.Helper.request(resource,"create",data);
$.ajax({
url: "/template",
type: "POST",
dataType: "json",
data: JSON.stringify(data),
success: function(response)
{
if (callback)
{
callback(request, response);
}
},
error: function(response)
{
if (callback_error)
{
callback_error(request, OpenNebula.Error(response));
}
}
});
},
"addattr" : function(params)
{
var callback = params.success;
var callback_error = params.error;
var id = params.data.id;
var name = params.data.name;
var value = params.data.value;
var method = "update";
var action = OpenNebula.Helper.action(method, {
"name" : name,
"value" : value
});
var resource = OpenNebula.Template.resource;
var request = OpenNebula.Helper.request(resource,method, [id, name, value]);
$.ajax({
url: "/template/" + id + "/action",
type: "POST",
data: JSON.stringify(action),
success: function(response)
{
if (callback)
{
callback(request, response);
}
},
error: function(response)
{
if (callback_error)
{
callback_error(request, OpenNebula.Error(response));
}
}
});
},
"update" : function(params)
{
var callback = params.success;
var callback_error = params.error;
var id = params.data.id;
var name = params.data.name;
var value = params.data.value;
var method = "update";
var action = OpenNebula.Helper.action(method, {
"name" : name,
"value" : value
});
var resource = OpenNebula.Template.resource;
var request = OpenNebula.Helper.request(resource,method, [id, name, value]);
$.ajax({
url: "/template/" + id + "/action",
type: "POST",
data: JSON.stringify(action),
success: function(response)
{
if (callback)
{
callback(request, response);
}
},
error: function(response)
{
if (callback_error)
{
callback_error(request, OpenNebula.Error(response));
}
}
});
},
"rmattr" : function(params)
{
var callback = params.success;
var callback_error = params.error;
var id = params.data.id;
var name = params.data.name;
var value = params.data.value;
var method = "rm_attr";
var action = OpenNebula.Helper.action(method, {
"name" : name
});
var resource = OpenNebula.Template.resource;
var request = OpenNebula.Helper.request(resource,method, [id, name]);
$.ajax({
url: "/template/" + id + "/action",
type: "POST",
data: JSON.stringify(action),
success: function(response)
{
if (callback)
{
callback(request, response);
}
},
error: function(response)
{
if (callback_error)
{
callback_error(request, OpenNebula.Error(response));
}
}
});
},
"publish" : function(params)
{
var callback = params.success;
var callback_error = params.error;
var id = params.data.id;
var method = "publish";
var action = OpenNebula.Helper.action(method);
var resource = OpenNebula.Template.resource;
var request = OpenNebula.Helper.request(resource,method, id);
$.ajax({
url: "/template/" + id + "/action",
type: "POST",
data: JSON.stringify(action),
success: function()
{
if (callback)
{
callback(request);
}
},
error: function(response)
{
if(callback_error)
{
callback_error(request, OpenNebula.Error(response));
}
}
});
},
"unpublish" : function(params)
{
var callback = params.success;
var callback_error = params.error;
var id = params.data.id;
var method = "unpublish";
var action = OpenNebula.Helper.action(method);
var resource = OpenNebula.Template.resource;
var request = OpenNebula.Helper.request(resource,method, id);
$.ajax({
url: "/template/" + id + "/action",
type: "POST",
data: JSON.stringify(action),
success: function()
{
if (callback)
{
callback(request);
}
},
error: function(response)
{
if(callback_error)
{
callback_error(request, OpenNebula.Error(response));
}
}
});
},
"list" : function(params)
{
var callback = params.success;
var callback_error = params.error;
var timeout = params.timeout || false;
var resource = OpenNebula.Template.resource;
var request = OpenNebula.Helper.request(resource,"list");
$.ajax({
url: "/template",
type: "GET",
dataType: "json",
data: {timeout: timeout},
success: function(response)
{
if (callback)
{
var template_pool = OpenNebula.Helper.pool(resource,response);
callback(request, template_pool);
}
},
error: function(response)
{
if (callback_error)
{
callback_error(request, OpenNebula.Error(response));
}
}
});
},
"show" : function(params)
{
var callback = params.success;
var callback_error = params.error;
var id = params.data.id;
var resource = OpenNebula.Template.resource;
var request = OpenNebula.Helper.request(resource,"show", id);
$.ajax({
url: "/template/" + id,
type: "GET",
dataType: "json",
success: function(response)
{
if (callback)
{
callback(request, response);
}
},
error: function(response)
{
if (callback_error)
{
callback_error(request, OpenNebula.Error(response));
}
}
});
},
"delete" : function(params)
{
var callback = params.success;
var callback_error = params.error;
var id = params.data.id;
var resource = OpenNebula.Template.resource;
var request = OpenNebula.Helper.request(resource,"delete", id);
$.ajax({
url: "/template/" + id,
type: "DELETE",
success: function()
{
if (callback)
{
callback(request);
}
},
error: function(response)
{
if (callback_error)
{
callback_error(request, OpenNebula.Error(response));
}
}
});
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -93,6 +93,7 @@ function tableCheckboxesListener(dataTable){
last_action_b.button("disable");
};
$('.create_dialog_button',context).button("enable");
$('.alwaysActive',context).button("enable");
//listen to changes in the visible inputs
$('tbody input',dataTable).live("change",function(){
@ -127,6 +128,7 @@ function tableCheckboxesListener(dataTable){
//any case the create dialog buttons should always be enabled.
$('.create_dialog_button',context).button("enable");
$('.alwaysActive',context).button("enable");
});
}

View File

@ -448,6 +448,10 @@ function insertButtonsInTab(tab_name){
}
if (button.alwaysActive) {
button_code = $(button_code).addClass("alwaysActive");
}
$('div#'+tab_name+' .action_blocks').append(button_code);
}//for each button in tab

View File

@ -25,6 +25,7 @@
<script type="text/javascript" src="/js/sunstone-util.js"></script>
<script type="text/javascript" src="/js/plugins/dashboard-tab.js"></script>
<script type="text/javascript" src="/js/plugins/hosts-tab.js"></script>
<script type="text/javascript" src="/js/plugins/templates-tab.js"></script>
<script type="text/javascript" src="/js/plugins/vms-tab.js"></script>
<script type="text/javascript" src="/js/plugins/vnets-tab.js"></script>
<script type="text/javascript" src="/js/plugins/images-tab.js"></script>

View File

@ -309,7 +309,7 @@ void Template::get(
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void Template::get(
bool Template::get(
string& name,
int& value) const
{
@ -320,12 +320,13 @@ void Template::get(
if ( sval == "" )
{
value = 0;
return;
return false;
}
istringstream iss(sval);
iss >> value;
return true;
}
/* -------------------------------------------------------------------------- */

View File

@ -82,6 +82,11 @@ void Nebula::start()
delete cpool;
}
if ( tpool != 0)
{
delete tpool;
}
if ( vmm != 0)
{
delete vmm;
@ -214,6 +219,11 @@ void Nebula::start()
{
cpool = tester->create_cpool(db);
}
if (tester->need_template_pool)
{
tpool = tester->create_tpool(db);
}
}
catch (exception&)
{
@ -358,7 +368,7 @@ void Nebula::start()
{
try
{
rm = tester->create_rm(vmpool,hpool,vnpool,upool,ipool,cpool,
rm = tester->create_rm(vmpool,hpool,vnpool,upool,ipool,cpool,tpool,
log_location + "one_xmlrpc.log");
}
catch (bad_alloc&)

View File

@ -54,6 +54,11 @@ ClusterPool* NebulaTest::create_cpool(SqlDB* db)
return new ClusterPool(db);
}
VMTemplatePool* NebulaTest::create_tpool(SqlDB* db)
{
return new VMTemplatePool(db);
}
// -----------------------------------------------------------
// Managers
// -----------------------------------------------------------
@ -112,6 +117,7 @@ RequestManager* NebulaTest::create_rm(
UserPool * upool,
ImagePool * ipool,
ClusterPool * cpool,
VMTemplatePool * tpool,
string log_file)
{
int rm_port = 2633;
@ -122,6 +128,7 @@ RequestManager* NebulaTest::create_rm(
upool,
ipool,
cpool,
tpool,
rm_port,
log_file);
}

View File

@ -79,7 +79,7 @@ void TransferManagerDriver::protocol(
is.clear();
getline(is,info);
NebulaLog::log("TM",Log::INFO, info.c_str());
NebulaLog::log("TM",log_type(result[0]), info.c_str());
}
return;
@ -142,8 +142,16 @@ void TransferManagerDriver::protocol(
getline(is,info);
os.str("");
os << "Error excuting image transfer script: " << info;
os << "Error excuting image transfer script";
if (!info.empty() && info[0] != '-')
{
os << ": " << info;
vm->set_template_error_message(os.str());
vmpool->update(vm);
}
vm->log("TM",Log::ERROR,os);
switch (vm->get_lcm_state())
@ -171,7 +179,7 @@ void TransferManagerDriver::protocol(
string info;
getline(is,info);
vm->log("TM",Log::INFO,info.c_str());
vm->log("TM",log_type(result[0]),info.c_str());
}
vm->unlock();

View File

@ -27,18 +27,7 @@ are the names of the commands (uppercase) and contain the path of
the script that will be executed for that command.
It also contains some methods to execute the scripts, get the output
of the script (success/failure, error and log messages). The protocol
for scripts to do so is as follows:
* Log messages will be sent to STDOUT
* The script will return 0 if it succeded or any other value
if there was a failure
* In case of failure the cause of the error will be written to STDERR
wrapped by start and end marks as follows:
ERROR MESSAGE --8<------
error message for the failure
ERROR MESSAGE ------>8--
of the script (success/failure, error and log messages).
=end
class TMPlugin < Hash
@ -150,7 +139,7 @@ class TMScript
if res.code == 0
res = [true, ""]
else
res = [false, get_error_message(res.stderr)]
res = [false, res.get_error_message]
end
end
@ -176,13 +165,6 @@ class TMScript
@lines<< command
}
end
# Parses error message from +stderr+ output
def get_error_message(str)
tmp=str.scan(/^ERROR MESSAGE --8<------\n(.*?)ERROR MESSAGE ------>8--$/m)
return "Error message not available" if !tmp[0]
tmp[0][0].strip
end
end

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