diff --git a/SConstruct b/SConstruct index 818ee83cfa..6492bb173e 100644 --- a/SConstruct +++ b/SConstruct @@ -57,7 +57,7 @@ main_env.Append(LIBPATH=[ cwd+'/src/log', cwd+'/src/sql', cwd+'/src/host', - cwd+'/src/cluster', + cwd+'/src/group', cwd+'/src/mad', cwd+'/src/nebula', cwd+'/src/pool', @@ -186,7 +186,7 @@ build_scripts=[ 'src/common/SConstruct', 'src/template/SConstruct', 'src/host/SConstruct', - 'src/cluster/SConstruct', + 'src/group/SConstruct', 'src/mad/SConstruct', 'src/nebula/SConstruct', 'src/pool/SConstruct', @@ -233,7 +233,7 @@ if testing=='yes': 'src/authm/test/SConstruct', 'src/common/test/SConstruct', 'src/host/test/SConstruct', - 'src/cluster/test/SConstruct', + 'src/group/test/SConstruct', 'src/image/test/SConstruct', 'src/lcm/test/SConstruct', 'src/pool/test/SConstruct', diff --git a/include/AuthManager.h b/include/AuthManager.h index 0042d5d8a8..106497d2ee 100644 --- a/include/AuthManager.h +++ b/include/AuthManager.h @@ -281,7 +281,10 @@ public: 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 */ + INFO_POOL, /** Authorization to view any object in the pool */ + INFO_POOL_MINE, /** Authorization to view user and/or group objects */ + INSTANTIATE, /** Authorization to instantiate a VM from a TEMPLATE */ + CHOWN /** Authorization to change ownership of an object */ }; /** @@ -294,8 +297,8 @@ public: NET, IMAGE, USER, - CLUSTER, - TEMPLATE + TEMPLATE, + GROUP }; /** diff --git a/include/FixedLeases.h b/include/FixedLeases.h index fc1c420d08..399afb02d7 100644 --- a/include/FixedLeases.h +++ b/include/FixedLeases.h @@ -113,7 +113,7 @@ public: private: /** - * The default MAC prefix for the OpenNebula cluster + * The default MAC prefix for the Leases */ unsigned int mac_prefix; diff --git a/include/Cluster.h b/include/Group.h similarity index 67% rename from include/Cluster.h rename to include/Group.h index bf0c2d6a11..860d883e87 100644 --- a/include/Cluster.h +++ b/include/Group.h @@ -14,49 +14,24 @@ /* limitations under the License. */ /* -------------------------------------------------------------------------*/ -#ifndef CLUSTER_H_ -#define CLUSTER_H_ +#ifndef GROUP_H_ +#define GROUP_H_ #include "PoolSQL.h" -#include "Host.h" +#include "ObjectCollection.h" +#include "User.h" using namespace std; /** - * The Cluster class. + * The Group class. */ -class Cluster : public PoolObjectSQL +class Group : public PoolObjectSQL, ObjectCollection { public: - /** - * Adds the host to this cluster - * @param host The host to add - * - * @return 0 on success - */ -/* - int add_host(Host * host) - { - return host->set_cluster(name); - }; -*/ /** - * Removes the host from this cluster - * @param host The host to add - * - * @return 0 on success - */ -// May be needed in a future -// int remove_host(Host * host); - - /** - * Function to write a Cluster on an output stream - */ - friend ostream& operator<<(ostream& os, Cluster& cluster); - - /** - * Function to print the Cluster object into a string in XML format + * Function to print the Group object into a string in XML format * @param xml the resulting XML string * @return a reference to the generated string */ @@ -70,21 +45,43 @@ public: */ int from_xml(const string &xml_str); + /** + * Adds this user's ID to the set. + * @param id of the user to be added to the group + * @return 0 on success + */ + int add_user(int id) + { + return add_collection_id(id); + } + + /** + * Deletes this users's ID from the set. + * @param id of the user to be deleted from the group + * @return 0 on success + */ + int del_user(int id) + { + return del_collection_id(id); + } + private: // ------------------------------------------------------------------------- // Friends // ------------------------------------------------------------------------- - friend class ClusterPool; + friend class GroupPool; // ************************************************************************* // Constructor // ************************************************************************* - Cluster(int id, const string& name); + Group(int id, const string& name): + PoolObjectSQL(id,name,-1,-1,table), + ObjectCollection("USERS"){}; - virtual ~Cluster(); + virtual ~Group(){}; // ************************************************************************* // DataBase implementation (Private) @@ -105,28 +102,43 @@ private: int insert_replace(SqlDB *db, bool replace); /** - * Bootstraps the database table(s) associated to the Cluster + * Bootstraps the database table(s) associated to the Group */ static void bootstrap(SqlDB * db) { - ostringstream oss_cluster(Cluster::db_bootstrap); + ostringstream oss(Group::db_bootstrap); - db->exec(oss_cluster); + db->exec(oss); }; /** - * Writes the Cluster in the database. + * Writes the Group in the database. * @param db pointer to the db * @return 0 on success */ - int insert(SqlDB *db, string& error_str); + int insert(SqlDB *db, string& error_str) + { + int rc; + + rc = insert_replace(db, false); + + if ( rc != 0 ) + { + error_str = "Error inserting Group in DB."; + } + + return rc; + } /** - * Writes/updates the Cluster's data fields in the database. + * Writes/updates the Group's data fields in the database. * @param db pointer to the db * @return 0 on success */ - int update(SqlDB *db); + int update(SqlDB *db) + { + return insert_replace(db, true); + } }; -#endif /*CLUSTER_H_*/ +#endif /*GROUP_H_*/ diff --git a/include/ClusterPool.h b/include/GroupPool.h similarity index 50% rename from include/ClusterPool.h rename to include/GroupPool.h index 13b5ac7fab..0addc889ab 100644 --- a/include/ClusterPool.h +++ b/include/GroupPool.h @@ -14,63 +14,73 @@ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ -#ifndef CLUSTER_POOL_H_ -#define CLUSTER_POOL_H_ +#ifndef GROUP_POOL_H_ +#define GROUP_POOL_H_ -#include "Cluster.h" -#include "Host.h" +#include "Group.h" #include "SqlDB.h" using namespace std; -/** - * A cluster helper class. It is not a normal PoolSQL, - * but a series of static methods related to clusters. - */ -class ClusterPool : public PoolSQL + +class GroupPool : public PoolSQL { public: - ClusterPool(SqlDB * db); + GroupPool(SqlDB * db); - ~ClusterPool(){}; + ~GroupPool(){}; + + /* ---------------------------------------------------------------------- */ + /* Constants r DB management */ + /* ---------------------------------------------------------------------- */ /** - * Removes the host from the given cluster setting the default one. - * @param host The host to assign - * - * @return 0 on success + * Default name for the oneadmin group */ - int set_default_cluster(Host * host) - { - return host->set_cluster(ClusterPool::DEFAULT_CLUSTER_NAME); - }; + static const string ONEADMIN_NAME; /** - * Cluster name for the default cluster + * Identifier for the oneadmin group */ - static const string DEFAULT_CLUSTER_NAME; + static const int ONEADMIN_ID; + + /** + * Default name for the users group + */ + static const string USERS_NAME; + + /** + * Identifier for the user group + */ + static const int USERS_ID; /* ---------------------------------------------------------------------- */ /* Methods for DB management */ /* ---------------------------------------------------------------------- */ /** - * Allocates a new cluster in the pool - * @param clid the id assigned to the cluster - * @return the id assigned to the cluster or -1 in case of failure + * Allocates a new group, writting it in the pool database. No memory is + * allocated for the object. + * @param name Group name + * @param oid the id assigned to the Group + * @param error_str Returns the error reason, if any + * + * @return the oid assigned to the object, -1 in case of failure */ - int allocate(int * oid, string name, string& error_str); + int allocate(string name, + int * oid, + string& error_str); /** - * Function to get a Cluster from the pool, if the object is not in memory + * Function to get a group from the pool, if the object is not in memory * it is loaded from the DB - * @param oid Cluster unique id - * @param lock locks the Cluster mutex - * @return a pointer to the Cluster, 0 if the Cluster could not be loaded + * @param oid group unique id + * @param lock locks the group mutex + * @return a pointer to the group, 0 if the group could not be loaded */ - Cluster * get(int oid, bool lock) + Group * get(int oid, bool lock) { - return static_cast(PoolSQL::get(oid,lock)); + return static_cast(PoolSQL::get(oid,lock)); }; /** @@ -81,38 +91,42 @@ public: * * @return a pointer to the object, 0 in case of failure */ - Cluster * get(const string& name, bool lock) + Group * get(const string& name, bool lock) { - return static_cast(PoolSQL::get(name,-1,lock)); + return static_cast(PoolSQL::get(name,-1,lock)); }; - /** Update a particular Cluster - * @param user pointer to Cluster + /** Update a particular Group + * @param user pointer to Group * @return 0 on success */ - int update(Cluster * cluster) + int update(Group * group) { - return cluster->update(db); + return group->update(db); }; /** - * Drops the Cluster from the data base. The object mutex SHOULD be + * Drops the Group from the data base. The object mutex SHOULD be * locked. - * @param cluster a pointer to the object - * @return 0 on success. + * @param objsql a pointer to a Group object + * @param error_msg Error reason, if any + * @return 0 on success, + * -1 DB error, + * -2 object is a system group (ID < 100) + * -3 Group's User IDs set is not empty */ - int drop(Cluster * cluster); + int drop(PoolObjectSQL * objsql, string& error_msg); /** - * Bootstraps the database table(s) associated to the Cluster pool + * Bootstraps the database table(s) associated to the Group pool */ static void bootstrap(SqlDB * _db) { - Cluster::bootstrap(_db); + Group::bootstrap(_db); }; /** - * Dumps the Cluster pool in XML format. A filter can be also added to the + * Dumps the Group 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 @@ -121,7 +135,7 @@ public: */ int dump(ostringstream& oss, const string& where) { - return PoolSQL::dump(oss, "CLUSTER_POOL", Cluster::table, where); + return PoolSQL::dump(oss, "GROUP_POOL", Group::table, where); }; private: @@ -132,8 +146,8 @@ private: */ PoolObjectSQL * create() { - return new Cluster(-1,""); + return new Group(-1,""); }; }; -#endif /*CLUSTER_POOL_H_*/ +#endif /*GROUP_POOL_H_*/ diff --git a/include/Host.h b/include/Host.h index 26726c35ae..52643d3452 100644 --- a/include/Host.h +++ b/include/Host.h @@ -43,11 +43,6 @@ public: DISABLED = 4 /**< The host is disabled won't be monitored. */ }; - /** - * Function to write a Host on an output stream - */ - friend ostream& operator<<(ostream& os, Host& h); - /** * Function to print the Host object into a string in XML format * @param xml the resulting XML string @@ -171,16 +166,6 @@ public: return last_monitored; }; - /** - * Sets the cluster for this host - * @return time_t last monitored time - */ - int set_cluster(const string& cluster_name) - { - cluster = cluster_name; - return 0; - }; - // ------------------------------------------------------------------------ // Share functions // ------------------------------------------------------------------------ @@ -292,6 +277,14 @@ public: return host_share.test(cpu,mem,disk); } + /** + * Factory method for host templates + */ + Template * get_new_template() + { + return new HostTemplate; + } + private: // ------------------------------------------------------------------------- @@ -329,11 +322,6 @@ private: */ time_t last_monitored; - /** - * Name of the cluster this host belongs to. - */ - string cluster; - // ------------------------------------------------------------------------- // Host Attributes // ------------------------------------------------------------------------- @@ -350,8 +338,7 @@ private: const string& hostname="", const string& im_mad_name="", const string& vmm_mad_name="", - const string& tm_mad_name="", - const string& cluster=""); + const string& tm_mad_name=""); virtual ~Host(); diff --git a/include/Image.h b/include/Image.h index 1ce8c795c8..ad40595233 100644 --- a/include/Image.h +++ b/include/Image.h @@ -52,11 +52,6 @@ public: ERROR = 5 /** < Error state the operation FAILED*/ }; - /** - * Function to write an Image on an output stream - */ - friend ostream& operator<<(ostream& os, Image& i); - // ************************************************************************* // Image Public Methods // ************************************************************************* @@ -76,15 +71,6 @@ public: */ int from_xml(const string &xml_str); - /** - * Returns true if the image is public - * @return true if the image is public - */ - bool isPublic() - { - return (public_img == 1); - }; - /** * Returns true if the image is persistent * @return true if the image is persistent @@ -195,25 +181,25 @@ public: * @param pub true to publish the image * @return 0 on success */ - bool publish(bool pub) + int publish(bool pub) { - bool success = false; + int rc = -1; if (pub == true) { if (!isPersistent()) { - public_img = 1; - success = true; + public_obj = 1; + rc = 0; } } else { - public_img = 0; - success = true; + public_obj = 0; + rc = 0; } - return success; + return rc; } /** @@ -221,25 +207,25 @@ public: * @param persistent true to make an image persistent * @return 0 on success */ - bool persistent(bool persis) + int persistent(bool persis) { - bool success = false; + int rc = -1; if (persis == true) { if (!isPublic() && running_vms == 0) { persistent_img = 1; - success = true; + rc = 0; } } else { persistent_img = 0; - success = true; + rc = 0; } - return success; + return rc; } /** @@ -259,6 +245,14 @@ public: */ int disk_attribute(VectorAttribute * disk, int* index, ImageType* img_type); + /** + * Factory method for image templates + */ + Template * get_new_template() + { + return new ImageTemplate; + } + private: // ------------------------------------------------------------------------- @@ -271,21 +265,11 @@ private: // Image Description // ------------------------------------------------------------------------- - /** - * Image owner's name - */ - string user_name; - /** * Type of the Image */ ImageType type; - /** - * Public scope of the Image - */ - int public_img; - /** * Persistency of the Image */ @@ -346,8 +330,8 @@ protected: // Constructor // ************************************************************************* - Image(int uid, - const string& user_name, + Image(int uid, + int gid, ImageTemplate* img_template); virtual ~Image(); diff --git a/include/ImagePool.h b/include/ImagePool.h index 9dae46d2ed..6a5df81d8c 100644 --- a/include/ImagePool.h +++ b/include/ImagePool.h @@ -47,15 +47,17 @@ public: /** * Function to allocate a new Image object * @param uid the user id of the image's owner - * @param stemplate template associated with the image + * @param gid the id of the group this object is assigned to + * @param img_template template associated with the image * @param oid the id assigned to the Image + * @param error_str Returns the error reason, if any * @return the oid assigned to the object, * -1 in case of failure * -2 in case of template parse failure */ int allocate ( int uid, - string user_name, + int gid, ImageTemplate * img_template, int * oid, string& error_str); @@ -93,15 +95,6 @@ public: return image->update(db); }; - /** Drops an image from the DB, the image mutex MUST BE locked - * @param image pointer to Image - * @return 0 on success - */ - int drop(Image * image) - { - return PoolSQL::drop(image); - }; - /** * Bootstraps the database table(s) associated to the Image pool */ @@ -179,7 +172,7 @@ private: */ PoolObjectSQL * create() { - return new Image(-1,"",0); + return new Image(-1,-1,0); }; }; diff --git a/include/Nebula.h b/include/Nebula.h index e48209774e..bbb69f126e 100644 --- a/include/Nebula.h +++ b/include/Nebula.h @@ -26,6 +26,7 @@ #include "HostPool.h" #include "UserPool.h" #include "VMTemplatePool.h" +#include "GroupPool.h" #include "VirtualMachineManager.h" #include "LifeCycleManager.h" @@ -79,9 +80,9 @@ public: return ipool; }; - ClusterPool * get_cpool() + GroupPool * get_gpool() { - return cpool; + return gpool; }; VMTemplatePool * get_tpool() @@ -247,8 +248,8 @@ private: // ----------------------------------------------------------------------- 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) + upool(0),ipool(0),gpool(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"); @@ -308,9 +309,9 @@ private: delete ipool; } - if ( cpool != 0) + if ( gpool != 0) { - delete cpool; + delete gpool; } if ( tpool != 0) @@ -409,7 +410,7 @@ private: VirtualNetworkPool * vnpool; UserPool * upool; ImagePool * ipool; - ClusterPool * cpool; + GroupPool * gpool; VMTemplatePool * tpool; // --------------------------------------------------------------- diff --git a/include/ObjectCollection.h b/include/ObjectCollection.h new file mode 100644 index 0000000000..059639f0f2 --- /dev/null +++ b/include/ObjectCollection.h @@ -0,0 +1,102 @@ +/* -------------------------------------------------------------------------- */ +/* 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 OBJECT_COLLECTION_H_ +#define OBJECT_COLLECTION_H_ + +#include + +#include "PoolObjectSQL.h" + +using namespace std; + +/** + * Class to store a set of PoolObjectSQL IDs. + */ +class ObjectCollection +{ +protected: + + ObjectCollection(const string& _collection_name) + :collection_name(_collection_name){}; + + ~ObjectCollection(){}; + + /** + * Adds an ID to the set. + * @param id The new id + * + * @return 0 on success, -1 if the ID was already in the set + */ + int add_collection_id(int id); + + /** + * Deletes an ID from the set. + * @param id The id + * + * @return 0 on success, -1 if the ID was not in the set + */ + int del_collection_id(int id); + + /** + * Returns how many IDs are there in the set. + * @return how many IDs are there in the set. + */ + int get_collection_size() + { + return collection_set.size(); + }; + + /** + * Rebuilds the object from an xml node + * @param node The xml node pointer + * + * @return 0 on success, -1 otherwise + */ + int from_xml_node(const xmlNodePtr node); + + /** + * Function to print the Collection 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 a copy of the IDs set + */ + set get_collection_copy() + { + return set (collection_set); + }; + +private: + + /** + * The collection's name + */ + string collection_name; + + /** + * Set containing the relations IDs + */ + set collection_set; + +}; + +#endif /*OBJECT_COLLECTION_H_*/ diff --git a/include/PoolObjectSQL.h b/include/PoolObjectSQL.h index 5fedef7216..58794da920 100644 --- a/include/PoolObjectSQL.h +++ b/include/PoolObjectSQL.h @@ -37,9 +37,10 @@ class PoolObjectSQL : public ObjectSQL, public ObjectXML { public: - PoolObjectSQL(int id, const string& _name, int _uid,const char *_table) - :ObjectSQL(),ObjectXML(),oid(id),name(_name),uid(_uid), - valid(true),obj_template(0),table(_table) + PoolObjectSQL(int id, const string& _name, int _uid, + int _gid, const char *_table) + :ObjectSQL(),ObjectXML(),oid(id),name(_name),uid(_uid),gid(_gid), + valid(true),public_obj(0),obj_template(0),table(_table) { pthread_mutex_init(&mutex,0); }; @@ -63,11 +64,43 @@ public: return name; }; + /** + * Returns true if the image is public + * @return true if the image is public + */ + bool isPublic() + { + return (public_obj == 1); + }; + int get_uid() { return uid; }; + int get_gid() + { + return gid; + }; + + /** + * Changes the object's owner id + * @param _uid New User ID + */ + void set_uid(int _uid) + { + uid = _uid; + } + + /** + * Changes the object's group id + * @param _gid New Group ID + */ + void set_gid(int _gid) + { + gid = _gid; + }; + /* --------------------------------------------------------------------- */ /** @@ -231,6 +264,23 @@ public: */ void set_template_error_message(const string& message); + /** + * Factory method for templates, it should be implemented + * by classes that uses templates + * @return a new template + */ + virtual Template * get_new_template() + { + return 0; + } + + /** + * Replace template for this object. Object should be updated + * after calling this method + * @param tmpl string representation of the template + */ + int replace_template(const string& tmpl_str, string& error); + protected: /** @@ -305,11 +355,21 @@ protected: */ int uid; + /** + * Object's group, set it to -1 if group is not used + */ + int gid; + /** * The contents of this object are valid */ bool valid; + /** + * Set if the object is public + */ + int public_obj; + /** * Template for this object, will be allocated if needed */ diff --git a/include/PoolSQL.h b/include/PoolSQL.h index 1031b9ca1f..c7a76fe491 100644 --- a/include/PoolSQL.h +++ b/include/PoolSQL.h @@ -121,12 +121,20 @@ public: * 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. + * @param error_msg Error reason, if any + * @return 0 on success, -1 DB error */ - virtual int drop( - PoolObjectSQL * objsql) + virtual int drop(PoolObjectSQL * objsql, string& error_msg) { - return objsql->drop(db); + int rc = objsql->drop(db); + + if ( rc != 0 ) + { + error_msg = "SQL DB error"; + return -1; + } + + return 0; }; /** @@ -164,41 +172,57 @@ protected: int dump(ostringstream& oss, const string& elem_name, const char * table, const string& where); + /* ---------------------------------------------------------------------- */ + /* Interface to access the lastOID assigned by the pool */ + /* ---------------------------------------------------------------------- */ + /** - * Returns the value of the last identifier assigned by the pool + * Gets the value of the last identifier assigned by the pool + * @return the lastOID of the pool */ int get_lastOID() { return lastOID; }; + /** + * Sets the lastOID of the pool and updates the control database + * @param _lastOID for the pool + */ + void set_update_lastOID(int _lastOID) + { + lastOID = _lastOID; + + update_lastOID(); + }; + private: - pthread_mutex_t mutex; + pthread_mutex_t mutex; /** * Max size for the pool, to control the memory footprint of the pool. This * number MUST be greater than the max. number of objects that are * accessed simultaneously. */ - static const unsigned int MAX_POOL_SIZE; + static const unsigned int MAX_POOL_SIZE; /** * Last object ID assigned to an object. It must be initialized by the * target pool. */ - int lastOID; + int lastOID; /** * Tablename for this pool */ - string table; + string table; /** * The pool is implemented with a Map of SQL object pointers, using the * OID as key. */ - map pool; + map pool; /** * This is a name index for the pool map. The key is the name of the object @@ -216,7 +240,7 @@ private: * OID queue to implement a FIFO-like replacement policy for the pool * cache. */ - queue oid_queue; + queue oid_queue; /** * Function to lock the pool diff --git a/include/RangedLeases.h b/include/RangedLeases.h index ce847e3515..946db6f349 100644 --- a/include/RangedLeases.h +++ b/include/RangedLeases.h @@ -106,7 +106,7 @@ public: private: /** - * The default MAC prefix for the OpenNebula cluster + * The default MAC prefix for the Leases */ unsigned int mac_prefix; diff --git a/include/Request.h b/include/Request.h new file mode 100644 index 0000000000..25a21811f4 --- /dev/null +++ b/include/Request.h @@ -0,0 +1,205 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_H_ +#define REQUEST_H_ + +#include +#include + +#include "RequestManager.h" +#include "AuthManager.h" + +using namespace std; + +/** + * The Request Class represents the basic abstraction for the OpenNebula + * XML-RPC API. This interface must be implemented by any XML-RPC API call + */ +class Request: public xmlrpc_c::method +{ +public: + /** + * Wraps the actual execution function by authorizing the user + * and calling the request_execute virtual function + * @param _paramlist list of XML parameters + * @param _retval value to be returned to the client + */ + virtual void execute( + xmlrpc_c::paramList const& _paramList, + xmlrpc_c::value * const _retval); + + /** + * Error codes for the XML-RPC API + */ + enum ErrorCode { + SUCCESS = 0x0000, + AUTHENTICATION = 0x0100, + AUTHORIZATION = 0x0200, + NO_EXISTS = 0x0400, + ACTION = 0x0800, + XML_RPC_API = 0x1000, + INTERNAL = 0x2000, + }; + +protected: + + /* ------------------- Attributes of the Request ---------------------- */ + + int uid; /**< id of the user performing the request */ + + int gid; /**< id of the user's group */ + + PoolSQL * pool; /**< Pool of objects */ + + string method_name; /**< The name of the XML-RPC method */ + + AuthRequest::Object auth_object; /**< Auth object for the request */ + + AuthRequest::Operation auth_op; /**< Auth operation for the request */ + + + /* -------------------- Constructors ---------------------------------- */ + + Request(const string& mn, + const string& signature, + const string& help): uid(-1),gid(-1),pool(0),method_name(mn),retval(0) + { + _signature = signature; + _help = help; + }; + + virtual ~Request(){}; + + /* -------------------------------------------------------------------- */ + /* -------------------------------------------------------------------- */ + + /** + * Performs a basic autorization for this request using the uid/gid + * from the request. The function gets the object from the pool to get + * the public attribute and its owner. The authorization is based on + * object and type of operation for the request. + * @param oid of the object. + * + * @return true if the user is authorized. + */ + bool basic_authorization(int oid); + + /** + * Actual Execution method for the request. Must be implemented by the + * XML-RPC requests + * @param _paramlist of the XML-RPC call (complete list) + */ + virtual void request_execute(xmlrpc_c::paramList const& _paramList) = 0; + + /** + * Builds an XML-RPC response updating retval. After calling this function + * the xml-rpc excute method should return + * @param val to be returned to the client + */ + void success_response(int val); + + /** + * Builds an XML-RPC response updating retval. After calling this function + * the xml-rpc excute method should return + * @param val string to be returned to the client + */ + void success_response(const string& val); + + /** + * Builds an XML-RPC response updating retval. After calling this function + * the xml-rpc excute method should return + * @param ec error code for this call + * @param val string representation of the error + */ + void failure_response(ErrorCode ec, const string& val); + + /** + * Gets a string representation for the Auth object in the + * request. + * @param ob object for the auth operation + * @return string equivalent of the object + */ + static string object_name(AuthRequest::Object ob); + + /** + * Logs authorization errors + * @param message with the authorization error details + * @return string for logging + */ + string authorization_error (const string &message); + /** + * Logs authenticate errors + * @return string for logging + */ + string authenticate_error (); + + /** + * Logs get object errors + * @param object over which the get failed + * @param id of the object over which the get failed + * @return string for logging + */ + string get_error (const string &object, int id); + + /** + * Logs action errors + * @param err_desc brief description of the error + * @param err_detail additional error details from Managers & Pools + * @return string for logging + */ + string request_error (const string &err_desc, const string &err_detail); + + /** + * Logs allocate errors + * @param message with the allocate error details + * @return string for logging + */ + string allocate_error (const string& error); + + /** + * Logs allocate errors for a given resource + * @param obj the resource + * @param message with the allocate error details + * @return string for logging + */ + string allocate_error (AuthRequest::Object obj, const string& error); + + /** + * Logs allocate errors + * @param message with the allocate error details (parsing) + * @return string for logging + */ + string allocate_error (char *error); + +private: + /** + * Session token from the OpenNebula XML-RPC API + */ + string session; + + /** + * Return value of the request from libxmlrpc-c + */ + xmlrpc_c::value * retval; +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif //REQUEST_H_ + diff --git a/include/RequestManager.h b/include/RequestManager.h index e604581e30..952cb86769 100644 --- a/include/RequestManager.h +++ b/include/RequestManager.h @@ -23,8 +23,10 @@ #include "UserPool.h" #include "VirtualNetworkPool.h" #include "ImagePool.h" -#include "ClusterPool.h" #include "VMTemplatePool.h" +#include "GroupPool.h" + +#include "AuthManager.h" #include #include @@ -40,26 +42,13 @@ class RequestManager : public ActionListener { public: - RequestManager( - VirtualMachinePool * _vmpool, - HostPool * _hpool, - VirtualNetworkPool * _vnpool, - 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),tpool(_tpool),port(_port),socket_fd(-1), - xml_log_file(_xml_log_file) + RequestManager(int _port, const string _xml_log_file) + :port(_port), socket_fd(-1), xml_log_file(_xml_log_file) { am.addListener(this); }; - ~RequestManager() - {} - ; + ~RequestManager(){}; /** * This functions starts the associated listener thread (XML server), and @@ -86,6 +75,7 @@ public: am.trigger(ACTION_FINALIZE,0); }; + private: //-------------------------------------------------------------------------- @@ -106,41 +96,6 @@ private: */ pthread_t rm_xml_server_thread; - /** - * Pointer to the VM Pool, to access Virtual Machines - */ - VirtualMachinePool * vmpool; - - /** - * Pointer to the Host Pool, to access hosts - */ - HostPool * hpool; - - /** - * Pointer to the VN Pool, to access Virtual Netowrks - */ - VirtualNetworkPool * vnpool; - - /** - * Pointer to the User Pool, to access users - */ - UserPool * upool; - - /** - * Pointer to the Image Pool, to access images - */ - ImagePool * ipool; - - /** - * 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 */ @@ -178,1333 +133,12 @@ private: */ void do_action(const string & action, void * arg); + /** + * Register the XML-RPC API Calls + */ void register_xml_methods(); int setup_socket(); - - // ---------------------------------------------------------------------- - // ---------------------------------------------------------------------- - // Error Messages - // ---------------------------------------------------------------------- - // ---------------------------------------------------------------------- - - - /** - * Logs authorization errors - * @param method name of the RM method where the error arose - * @param action authorization action - * @param object object that needs to be authorized - * @param uid user that is authorized - * @param id id of the object, -1 for Pool - * @returns string for logging - */ - static string authorization_error (const string& method, - const string &action, - const string &object, - int uid, - int id) - { - ostringstream oss; - oss << "[" << method << "]" << " User [" << uid << "] not authorized" - << " to perform " << action << " on " << object; - - - if ( id != -1 ) - { - oss << " [" << id << "]."; - } - else - { - oss << " Pool"; - } - - return oss.str(); - } - - /** - * Logs authenticate errors - * @param method name of the RM method where the error arose - * @returns string for logging - */ - static string authenticate_error (const string& method) - { - ostringstream oss; - - oss << "[" << method << "]" << " User couldn't be authenticated," << - " aborting call."; - - return oss.str(); - } - - /** - * Logs get object errors - * @param method name of the RM method where the error arose - * @param object over which the get failed - * @param id of the object over which the get failed - * @returns string for logging - */ - static string get_error (const string& method, - const string &object, - int id) - { - ostringstream oss; - - oss << "[" << method << "]" << " Error getting " << - object; - - if ( id != -1 ) - { - oss << " [" << id << "]."; - } - else - { - oss << " Pool."; - } - - return oss.str(); - } - - /** - * Logs action errors - * @param method name of the RM method where the error arose - * @param action that triggered the error - * @param object over which the action was applied - * @param id id of the object, -1 for Pool, -2 for no-id objects - * (allocate error, parse error) - * @param rc returned error code (NULL to ignore) - * @returns string for logging - */ - static string action_error (const string& method, - const string &action, - const string &object, - int id, - int rc) - { - ostringstream oss; - - oss << "[" << method << "]" << " Error trying to " << action << " " - << object; - - switch(id) - { - case -2: - break; - case -1: - oss << "Pool."; - break; - default: - oss << " [" << id << "]."; - break; - } - - if ( rc != 0 ) - { - oss << " Returned error code [" << rc << "]."; - } - - return oss.str(); - } - - // ---------------------------------------------------------------------- - // ---------------------------------------------------------------------- - // XML-RPC Methods - // ---------------------------------------------------------------------- - // ---------------------------------------------------------------------- - - /* ---------------------------------------------------------------------- */ - /* Virtual Machine Interface */ - /* ---------------------------------------------------------------------- */ - class VirtualMachineAllocate: public xmlrpc_c::method - { - public: - VirtualMachineAllocate( - VirtualMachinePool * _vmpool, - VirtualNetworkPool * _vnpool, - ImagePool * _ipool, - VMTemplatePool * _tpool, - UserPool * _upool): - vmpool(_vmpool), - vnpool(_vnpool), - ipool(_ipool), - tpool(_tpool), - upool(_upool) - { - _signature="A:ss"; - _help="Allocates a virtual machine in the pool"; - }; - - ~VirtualMachineAllocate(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval); - private: - VirtualMachinePool * vmpool; - VirtualNetworkPool * vnpool; - ImagePool * ipool; - VMTemplatePool * tpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualMachineDeploy: public xmlrpc_c::method - { - public: - VirtualMachineDeploy( - VirtualMachinePool * _vmpool, - HostPool * _hpool, - UserPool * _upool): - vmpool(_vmpool), - hpool(_hpool), - upool(_upool) - { - _signature="A:sii"; - _help="Deploys a virtual machine"; - }; - - ~VirtualMachineDeploy(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval); - - private: - VirtualMachinePool * vmpool; - HostPool * hpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualMachineAction: public xmlrpc_c::method - { - public: - VirtualMachineAction( - VirtualMachinePool * _vmpool, - UserPool * _upool): - vmpool(_vmpool), - upool(_upool) - { - _signature="A:ssi"; - _help="Performs an action on a virtual machine"; - }; - - ~VirtualMachineAction(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval); - - private: - VirtualMachinePool * vmpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualMachineMigrate: public xmlrpc_c::method - { - public: - VirtualMachineMigrate( - VirtualMachinePool * _vmpool, - HostPool * _hpool, - UserPool * _upool): - vmpool(_vmpool), - hpool(_hpool), - upool(_upool) - { - _signature="A:siib"; - _help="Migrates a virtual machine"; - }; - - ~VirtualMachineMigrate(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval); - - private: - VirtualMachinePool * vmpool; - HostPool * hpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualMachineInfo: public xmlrpc_c::method - { - public: - VirtualMachineInfo( - VirtualMachinePool * _vmpool, - UserPool * _upool): - vmpool(_vmpool), - upool(_upool) - { - _signature="A:si"; - _help="Returns virtual machine information"; - }; - - ~VirtualMachineInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval); - - private: - VirtualMachinePool * vmpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualMachineSaveDisk: public xmlrpc_c::method - { - public: - VirtualMachineSaveDisk( - VirtualMachinePool * _vmpool, - UserPool * _upool, - ImagePool * _ipool): - vmpool(_vmpool), - upool(_upool), - ipool(_ipool) - { - _signature="A:siis"; - _help = "Sets the disk to be saved in a new Image with the given " - "name."; - }; - - ~VirtualMachineSaveDisk(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval); - - private: - VirtualMachinePool * vmpool; - UserPool * upool; - ImagePool * ipool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualMachinePoolInfo: public xmlrpc_c::method - { - public: - VirtualMachinePoolInfo( - VirtualMachinePool * _vmpool, - UserPool * _upool): - vmpool(_vmpool), - upool(_upool) - { - _signature="A:sii"; - _help="Returns the virtual machine pool"; - }; - - ~VirtualMachinePoolInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval); - - private: - VirtualMachinePool * vmpool; - 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 */ - /* ---------------------------------------------------------------------- */ - - class HostAllocate: public xmlrpc_c::method - { - public: - HostAllocate( - HostPool * _hpool, - UserPool * _upool): - hpool(_hpool), - upool(_upool) - { - _signature="A:sssss"; - _help="Allocates a host in the pool"; - }; - - ~HostAllocate(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - HostPool * hpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class HostInfo: public xmlrpc_c::method - { - public: - HostInfo( - HostPool * _hpool, - UserPool * _upool): - hpool(_hpool), - upool(_upool) - { - _signature="A:si"; - _help="Returns host information"; - }; - - ~HostInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - HostPool * hpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class HostPoolInfo: public xmlrpc_c::method - { - public: - HostPoolInfo(HostPool * _hpool, - UserPool * _upool): - hpool(_hpool), - upool(_upool) - { - _signature="A:s"; - _help="Returns the host pool information"; - }; - - ~HostPoolInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - HostPool * hpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class HostDelete: public xmlrpc_c::method - { - public: - HostDelete( - HostPool * _hpool, - UserPool * _upool): - hpool(_hpool), - upool(_upool) - { - _signature="A:si"; - _help="Deletes a host from the pool"; - }; - - ~HostDelete(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - HostPool * hpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class HostEnable: public xmlrpc_c::method - { - public: - HostEnable( - HostPool * _hpool, - UserPool * _upool): - hpool(_hpool), - upool(_upool) - { - _signature="A:sib"; - _help="Enables or disables a host"; - }; - - ~HostEnable(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - HostPool * hpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - /* Cluster Interface */ - /* ---------------------------------------------------------------------- */ - - class ClusterAllocate: public xmlrpc_c::method - { - public: - ClusterAllocate( - UserPool * _upool, - ClusterPool * _cpool): - upool(_upool), - cpool(_cpool) - { - _signature="A:ss"; - _help="Allocates a cluster in the pool"; - }; - - ~ClusterAllocate(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - UserPool * upool; - ClusterPool * cpool; - }; - - /* ---------------------------------------------------------------------- */ - - class ClusterInfo: public xmlrpc_c::method - { - public: - ClusterInfo( - UserPool * _upool, - ClusterPool * _cpool): - upool(_upool), - cpool(_cpool) - { - _signature="A:si"; - _help="Returns cluster information"; - }; - - ~ClusterInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - UserPool * upool; - ClusterPool * cpool; - }; - - /* ---------------------------------------------------------------------- */ - - class ClusterDelete: public xmlrpc_c::method - { - public: - ClusterDelete( - UserPool * _upool, - ClusterPool * _cpool): - upool(_upool), - cpool(_cpool) - { - _signature="A:si"; - _help="Deletes a cluster from the pool"; - }; - - ~ClusterDelete(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - UserPool * upool; - ClusterPool * cpool; - }; - - /* ---------------------------------------------------------------------- */ - - class ClusterAdd: public xmlrpc_c::method - { - public: - ClusterAdd( - HostPool * _hpool, - UserPool * _upool, - ClusterPool * _cpool): - hpool(_hpool), - upool(_upool), - cpool(_cpool) - { - _signature="A:sii"; - _help="Adds a host to a cluster"; - }; - - ~ClusterAdd(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - HostPool * hpool; - UserPool * upool; - ClusterPool * cpool; - }; - - /* ---------------------------------------------------------------------- */ - - class ClusterRemove: public xmlrpc_c::method - { - public: - ClusterRemove( - HostPool * _hpool, - UserPool * _upool, - ClusterPool * _cpool): - hpool(_hpool), - upool(_upool), - cpool(_cpool) - { - _signature="A:si"; - _help="Removes a host from its cluster"; - }; - - ~ClusterRemove(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - HostPool * hpool; - UserPool * upool; - ClusterPool * cpool; - }; - - /* ---------------------------------------------------------------------- */ - - class ClusterPoolInfo: public xmlrpc_c::method - { - public: - ClusterPoolInfo( - UserPool * _upool, - ClusterPool * _cpool): - upool(_upool), - cpool(_cpool) - { - _signature="A:s"; - _help="Returns the cluster pool information"; - }; - - ~ClusterPoolInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - UserPool * upool; - ClusterPool * cpool; - }; - - - /* ---------------------------------------------------------------------- */ - /* Virtual Network Interface */ - /* ---------------------------------------------------------------------- */ - - - class VirtualNetworkAllocate: public xmlrpc_c::method - { - public: - VirtualNetworkAllocate( - VirtualNetworkPool * _vnpool, - UserPool * _upool): - vnpool(_vnpool), - upool(_upool) - { - _signature="A:ss"; - _help="Creates a virtual network"; - }; - - ~VirtualNetworkAllocate(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - VirtualNetworkPool * vnpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualNetworkInfo: public xmlrpc_c::method - { - public: - VirtualNetworkInfo( - VirtualNetworkPool * _vnpool, - UserPool * _upool): - vnpool(_vnpool), - upool(_upool) - { - _signature="A:si"; - _help="Returns virtual network information"; - }; - - ~VirtualNetworkInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - VirtualNetworkPool * vnpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualNetworkPoolInfo: public xmlrpc_c::method - { - public: - VirtualNetworkPoolInfo(VirtualNetworkPool * _vnpool, - UserPool * _upool): - vnpool(_vnpool), - upool(_upool) - { - _signature="A:si"; - _help="Returns the virtual network pool information"; - }; - - ~VirtualNetworkPoolInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - VirtualNetworkPool * vnpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualNetworkPublish: public xmlrpc_c::method - { - public: - VirtualNetworkPublish( - VirtualNetworkPool * _vnpool, - UserPool * _upool): - vnpool(_vnpool), - upool(_upool) - { - _signature="A:sib"; - _help="Enables/Disables a virtual network"; - }; - - ~VirtualNetworkPublish(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - VirtualNetworkPool * vnpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualNetworkDelete: public xmlrpc_c::method - { - public: - VirtualNetworkDelete( - VirtualNetworkPool * _vnpool, - UserPool * _upool): - vnpool(_vnpool), - upool(_upool) - { - _signature="A:si"; - _help="Deletes a virtual network"; - }; - - ~VirtualNetworkDelete(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - VirtualNetworkPool * vnpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualNetworkAddLeases: public xmlrpc_c::method - { - public: - VirtualNetworkAddLeases( - VirtualNetworkPool * _vnpool, - UserPool * _upool): - vnpool(_vnpool), - upool(_upool) - { - _signature="A:sis"; - _help="Adds leases to a virtual network"; - }; - - ~VirtualNetworkAddLeases(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - VirtualNetworkPool * vnpool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class VirtualNetworkRemoveLeases: public xmlrpc_c::method - { - public: - VirtualNetworkRemoveLeases( - VirtualNetworkPool * _vnpool, - UserPool * _upool): - vnpool(_vnpool), - upool(_upool) - { - _signature="A:sis"; - _help="Removes leases from a virtual network"; - }; - - ~VirtualNetworkRemoveLeases(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - VirtualNetworkPool * vnpool; - UserPool * upool; - }; - /* ---------------------------------------------------------------------- */ - /* User Management Interface */ - /* ---------------------------------------------------------------------- */ - - - class UserAllocate: public xmlrpc_c::method - { - public: - UserAllocate(UserPool * _upool):upool(_upool) - { - _signature="A:sss"; - _help="Creates a new user"; - }; - - ~UserAllocate(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class UserDelete: public xmlrpc_c::method - { - public: - UserDelete(UserPool * _upool):upool(_upool) - { - _signature="A:si"; - _help="Deletes a user account"; - }; - - ~UserDelete(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class UserChangePassword: public xmlrpc_c::method - { - public: - UserChangePassword(UserPool * _upool):upool(_upool) - { - _signature="A:sis"; - _help="Changes the password for the given user."; - }; - - ~UserChangePassword(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class UserInfo: public xmlrpc_c::method - { - public: - UserInfo(UserPool * _upool):upool(_upool) - { - _signature="A:si"; - _help="Returns the information for a user"; - }; - - ~UserInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class UserPoolInfo: public xmlrpc_c::method - { - public: - UserPoolInfo(UserPool * _upool):upool(_upool) - { - _signature="A:s"; - _help="Returns content of the user pool"; - }; - - ~UserPoolInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - /* Image Pool Interface */ - /* ---------------------------------------------------------------------- */ - - class ImageAllocate: public xmlrpc_c::method - { - public: - ImageAllocate(ImagePool * _ipool, - UserPool * _upool): - ipool(_ipool), - upool(_upool) - { - _signature="A:ss"; - _help="Creates a new image"; - }; - - ~ImageAllocate(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - ImagePool * ipool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class ImageDelete: public xmlrpc_c::method - { - public: - ImageDelete(ImagePool * _ipool, - UserPool * _upool): - ipool(_ipool), - upool(_upool) - { - _signature="A:si"; - _help="Deletes an image"; - }; - - ~ImageDelete(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - ImagePool * ipool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class ImageInfo: public xmlrpc_c::method - { - public: - ImageInfo(ImagePool * _ipool, - UserPool * _upool): - ipool(_ipool), - upool(_upool) - { - _signature="A:si"; - _help="Returns information for an image"; - }; - - ~ImageInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - ImagePool * ipool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class ImageUpdate: public xmlrpc_c::method - { - public: - ImageUpdate(ImagePool * _ipool, - UserPool * _upool): - ipool(_ipool), - upool(_upool) - { - _signature="A:siss"; - _help="Modifies image attribute"; - }; - - ~ImageUpdate(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - ImagePool * ipool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class ImageRemoveAttribute: public xmlrpc_c::method - { - public: - ImageRemoveAttribute(ImagePool * _ipool, - UserPool * _upool): - ipool(_ipool), - upool(_upool) - { - _signature="A:sis"; - _help="Removes image attribute"; - }; - - ~ImageRemoveAttribute(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - ImagePool * ipool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class ImagePublish: public xmlrpc_c::method - { - public: - ImagePublish(ImagePool * _ipool, - UserPool * _upool): - ipool(_ipool), - upool(_upool) - { - _signature="A:sib"; - _help="Publish/Unpublish the Image"; - }; - - ~ImagePublish(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - ImagePool * ipool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class ImagePersistent: public xmlrpc_c::method - { - public: - ImagePersistent(ImagePool * _ipool, - UserPool * _upool): - ipool(_ipool), - upool(_upool) - { - _signature="A:sib"; - _help="Make an Image (non)persistent"; - }; - - ~ImagePersistent(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - ImagePool * ipool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class ImageEnable: public xmlrpc_c::method - { - public: - ImageEnable(ImagePool * _ipool, - UserPool * _upool): - ipool(_ipool), - upool(_upool) - { - _signature="A:sib"; - _help="Enables/Disables the Image"; - }; - - ~ImageEnable(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - ImagePool * ipool; - UserPool * upool; - }; - - /* ---------------------------------------------------------------------- */ - - class ImagePoolInfo: public xmlrpc_c::method - { - public: - ImagePoolInfo(ImagePool * _ipool, - UserPool * _upool): - ipool(_ipool), - upool(_upool) - { - _signature="A:si"; - _help="Returns content of image pool attending to the filter flag"; - }; - - ~ImagePoolInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - ImagePool * ipool; - UserPool * upool; - }; - }; diff --git a/include/RequestManagerAllocate.h b/include/RequestManagerAllocate.h new file mode 100644 index 0000000000..15d2f975cf --- /dev/null +++ b/include/RequestManagerAllocate.h @@ -0,0 +1,275 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_ALLOCATE_H_ +#define REQUEST_MANAGER_ALLOCATE_H_ + +#include "Request.h" +#include "Nebula.h" + +#include "VirtualNetworkTemplate.h" +#include "ImageTemplate.h" +#include "VirtualMachineTemplate.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerAllocate: public Request +{ +protected: + RequestManagerAllocate(const string& method_name, + const string& help, + const string& xml_args, + bool dt) + :Request(method_name,xml_args,help), do_template(dt) + { + auth_op = AuthRequest::CREATE; + }; + + ~RequestManagerAllocate(){}; + + /* -------------------------------------------------------------------- */ + + void request_execute(xmlrpc_c::paramList const& _paramList); + + virtual bool allocate_authorization(Template * obj_template); + + /* -------------------------------------------------------------------- */ + + virtual Template * get_object_template() { return 0; }; + + virtual int pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str) = 0; +private: + + bool do_template; +}; + + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualMachineAllocate: public RequestManagerAllocate +{ +public: + VirtualMachineAllocate(): + RequestManagerAllocate("VirtualMachineAllocate", + "Allocates a new virtual machine", + "A:ss", + true) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vmpool(); + auth_object = AuthRequest::VM; + }; + + ~VirtualMachineAllocate(){}; + /* --------------------------------------------------------------------- */ + + Template * get_object_template() + { + return new VirtualMachineTemplate; + }; + + int pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str); + + bool allocate_authorization(Template * obj_template); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualNetworkAllocate: public RequestManagerAllocate +{ +public: + VirtualNetworkAllocate(): + RequestManagerAllocate("VirtualNetworkInfo", + "Allocates a new virtual network", + "A:ss", + true) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vnpool(); + auth_object = AuthRequest::NET; + }; + + ~VirtualNetworkAllocate(){}; + + /* --------------------------------------------------------------------- */ + + Template * get_object_template() + { + return new VirtualNetworkTemplate; + }; + + int pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class ImageAllocate: public RequestManagerAllocate +{ +public: + ImageAllocate(): + RequestManagerAllocate("ImageAllocate", + "Allocates a new image", + "A:ss", + true) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_ipool(); + auth_object = AuthRequest::IMAGE; + }; + + ~ImageAllocate(){}; + + /* --------------------------------------------------------------------- */ + + Template * get_object_template() + { + return new ImageTemplate; + }; + + int pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class TemplateAllocate : public RequestManagerAllocate +{ +public: + TemplateAllocate(): + RequestManagerAllocate("TemplateAllocate", + "Allocates a new virtual machine template", + "A:ss", + true) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_tpool(); + auth_object = AuthRequest::TEMPLATE; + }; + + ~TemplateAllocate(){}; + + /* --------------------------------------------------------------------- */ + + Template * get_object_template() + { + return new VirtualMachineTemplate; + }; + + int pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class HostAllocate : public RequestManagerAllocate +{ +public: + HostAllocate(): + RequestManagerAllocate("HostInfo", + "Allocates a new host", + "A:sssss", + false) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_hpool(); + auth_object = AuthRequest::HOST; + }; + + ~HostAllocate(){}; + + int pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class UserAllocate: public RequestManagerAllocate +{ +public: + UserAllocate(): + RequestManagerAllocate("UserInfo", + "Returns user information", + "A:sss", + false) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_upool(); + auth_object = AuthRequest::USER; + }; + + ~UserAllocate(){}; + + int pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class GroupAllocate: public RequestManagerAllocate +{ +public: + GroupAllocate(): + RequestManagerAllocate("GroupAllocate", + "Allocates a new group", + "A:ss", + false) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_gpool(); + auth_object = AuthRequest::GROUP; + }; + + ~GroupAllocate(){}; + + int pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str); +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerChown.h b/include/RequestManagerChown.h new file mode 100644 index 0000000000..6d530b4a89 --- /dev/null +++ b/include/RequestManagerChown.h @@ -0,0 +1,149 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_CHOWN_H_ +#define REQUEST_MANAGER_CHOWN_H_ + +#include "Request.h" +#include "Nebula.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerChown : public Request +{ +protected: + RequestManagerChown(const string& method_name, + const string& help, + const string& params = "A:siii") + :Request(method_name,params,help) + { + auth_op = AuthRequest::CHOWN; + }; + + ~RequestManagerChown(){}; + + /* -------------------------------------------------------------------- */ + + virtual void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualMachineChown : public RequestManagerChown +{ +public: + VirtualMachineChown(): + RequestManagerChown("VirtualMachineChown", + "Changes ownership of a virtual machine") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vmpool(); + auth_object = AuthRequest::VM; + }; + + ~VirtualMachineChown(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class TemplateChown : public RequestManagerChown +{ +public: + TemplateChown(): + RequestManagerChown("TemplateChown", + "Changes ownership of a virtual machine template") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_tpool(); + auth_object = AuthRequest::TEMPLATE; + }; + + ~TemplateChown(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + + +class VirtualNetworkChown: public RequestManagerChown +{ +public: + VirtualNetworkChown(): + RequestManagerChown("VirtualNetworkChown", + "Changes ownership of a virtual network") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vnpool(); + auth_object = AuthRequest::NET; + }; + + ~VirtualNetworkChown(){}; + +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class ImageChown: public RequestManagerChown +{ +public: + ImageChown(): + RequestManagerChown("ImageChown", + "Changes ownership of an image") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_ipool(); + auth_object = AuthRequest::IMAGE; + }; + + ~ImageChown(){}; + +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class UserChown : public RequestManagerChown +{ +public: + UserChown(): + RequestManagerChown("UserChown", + "Changes ownership of a user", + "A:sii") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_upool(); + auth_object = AuthRequest::USER; + }; + + ~UserChown(){}; + + /* -------------------------------------------------------------------- */ + + virtual void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerDelete.h b/include/RequestManagerDelete.h new file mode 100644 index 0000000000..c6fe23a107 --- /dev/null +++ b/include/RequestManagerDelete.h @@ -0,0 +1,157 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_DELETE_H_ +#define REQUEST_MANAGER_DELETE_H_ + +#include "Request.h" +#include "Nebula.h" +#include "AuthManager.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerDelete: public Request +{ +protected: + RequestManagerDelete(const string& method_name, + const string& help) + :Request(method_name,"A:si",help) + { + auth_op = AuthRequest::DELETE; + } + + ~RequestManagerDelete(){}; + + /* -------------------------------------------------------------------- */ + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class TemplateDelete : public RequestManagerDelete +{ +public: + TemplateDelete(): + RequestManagerDelete("TemplateDelete", + "Deletes a virtual machine template") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_tpool(); + auth_object = AuthRequest::TEMPLATE; + }; + + ~TemplateDelete(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualNetworkDelete: public RequestManagerDelete +{ +public: + VirtualNetworkDelete(): + RequestManagerDelete("VirtualNetworkDelete", + "Deletes a virtual network") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vnpool(); + auth_object = AuthRequest::NET; + }; + + ~VirtualNetworkDelete(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class ImageDelete: public RequestManagerDelete +{ +public: + ImageDelete(): + RequestManagerDelete("ImageDelete", "Deletes an image") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_ipool(); + auth_object = AuthRequest::IMAGE; + }; + + ~ImageDelete(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class HostDelete : public RequestManagerDelete +{ +public: + HostDelete(): + RequestManagerDelete("HostDelete", "Deletes a host") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_hpool(); + auth_object = AuthRequest::HOST; + }; + + ~HostDelete(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + + +class GroupDelete: public RequestManagerDelete +{ +public: + GroupDelete(): + RequestManagerDelete("GroupDelete", "Deletes a group") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_gpool(); + auth_object = AuthRequest::GROUP; + }; + + ~GroupDelete(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class UserDelete: public RequestManagerDelete +{ +public: + UserDelete(): + RequestManagerDelete("UserDelete", "Deletes a user") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_upool(); + auth_object = AuthRequest::USER; + }; + + ~UserDelete(){}; +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerHost.h b/include/RequestManagerHost.h new file mode 100644 index 0000000000..2431c491a1 --- /dev/null +++ b/include/RequestManagerHost.h @@ -0,0 +1,73 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_HOST_H +#define REQUEST_MANAGER_HOST_H + +#include "Request.h" +#include "Nebula.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerHost: public Request +{ +protected: + RequestManagerHost( const string& method_name, + const string& help, + const string& params) + :Request(method_name,params,help) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_hpool(); + + auth_object = AuthRequest::HOST; + }; + + ~RequestManagerHost(){}; + + /* -------------------------------------------------------------------- */ + + virtual void request_execute(xmlrpc_c::paramList const& _paramList) = 0; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class HostEnable : public RequestManagerHost +{ +public: + HostEnable(): + RequestManagerHost("HostEnable", + "Enables or disables a host", + "A:sib") + { + auth_op = AuthRequest::MANAGE; + }; + + ~HostEnable(){}; + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerImage.h b/include/RequestManagerImage.h new file mode 100644 index 0000000000..7a24d4b752 --- /dev/null +++ b/include/RequestManagerImage.h @@ -0,0 +1,83 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_IMAGE_H +#define REQUEST_MANAGER_IMAGE_H + +#include "Request.h" +#include "Nebula.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerImage: public Request +{ +protected: + RequestManagerImage(const string& method_name, + const string& help) + :Request(method_name,"A:sib",help) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_ipool(); + + auth_object = AuthRequest::IMAGE; + auth_op = AuthRequest::MANAGE; + }; + + ~RequestManagerImage(){}; + + /* --------------------------------------------------------------------- */ + + virtual void request_execute(xmlrpc_c::paramList const& _paramList) = 0; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class ImageEnable : public RequestManagerImage +{ +public: + ImageEnable(): + RequestManagerImage("ImageEnable", "Enables or disables an image"){}; + + ~ImageEnable(){}; + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class ImagePersistent : public RequestManagerImage +{ +public: + ImagePersistent(): + RequestManagerImage("ImagePersistent", + "Makes an image persistent or non-persistent"){}; + + ~ImagePersistent(){}; + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerInfo.h b/include/RequestManagerInfo.h new file mode 100644 index 0000000000..d40ef114d4 --- /dev/null +++ b/include/RequestManagerInfo.h @@ -0,0 +1,180 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_INFO_H_ +#define REQUEST_MANAGER_INFO_H_ + +#include "Request.h" +#include "Nebula.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerInfo: public Request +{ +protected: + RequestManagerInfo(const string& method_name, + const string& help) + :Request(method_name,"A:si",help) + { + auth_op = AuthRequest::INFO; + }; + + ~RequestManagerInfo(){}; + + /* -------------------------------------------------------------------- */ + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualMachineInfo : public RequestManagerInfo +{ +public: + VirtualMachineInfo(): + RequestManagerInfo("VirtualMachineInfo", + "Returns virtual machine instance information") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vmpool(); + auth_object = AuthRequest::VM; + }; + + ~VirtualMachineInfo(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class TemplateInfo : public RequestManagerInfo +{ +public: + TemplateInfo(): + RequestManagerInfo("TemplateInfo", + "Returns virtual machine template information") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_tpool(); + auth_object = AuthRequest::TEMPLATE; + }; + + ~TemplateInfo(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + + +class VirtualNetworkInfo: public RequestManagerInfo +{ +public: + VirtualNetworkInfo(): + RequestManagerInfo("VirtualNetworkInfo", + "Returns virtual network information") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vnpool(); + auth_object = AuthRequest::NET; + }; + + ~VirtualNetworkInfo(){}; + +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class ImageInfo: public RequestManagerInfo +{ +public: + ImageInfo(): + RequestManagerInfo("ImageInfo", + "Returns image information") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_ipool(); + auth_object = AuthRequest::IMAGE; + }; + + ~ImageInfo(){}; + +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class HostInfo : public RequestManagerInfo +{ +public: + HostInfo(): + RequestManagerInfo("HostInfo", + "Returns host information") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_hpool(); + auth_object = AuthRequest::HOST; + }; + + ~HostInfo(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + + +class GroupInfo: public RequestManagerInfo +{ +public: + GroupInfo(): + RequestManagerInfo("GroupInfo", + "Returns group information") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_gpool(); + auth_object = AuthRequest::GROUP; + }; + + ~GroupInfo(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class UserInfo: public RequestManagerInfo +{ +public: + UserInfo(): + RequestManagerInfo("UserInfo", + "Returns user information") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_upool(); + auth_object = AuthRequest::USER; + }; + + ~UserInfo(){}; +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerPoolInfo.h b/include/RequestManagerPoolInfo.h new file mode 100644 index 0000000000..d9bca1daa6 --- /dev/null +++ b/include/RequestManagerPoolInfo.h @@ -0,0 +1,106 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_POOL_INFO_H_ +#define REQUEST_MANAGER_POOL_INFO_H_ + +#include "Request.h" +#include "Nebula.h" +#include "AuthManager.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerPoolInfo: public Request +{ +protected: + RequestManagerPoolInfo(const string& method_name, + const string& help) + :Request(method_name,"A:s",help) + { + auth_op = AuthRequest::INFO_POOL; + }; + + ~RequestManagerPoolInfo(){}; + + /* -------------------------------------------------------------------- */ + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class HostPoolInfo : public RequestManagerPoolInfo +{ +public: + HostPoolInfo(): + RequestManagerPoolInfo("HostPoolInfo", + "Returns the host pool") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_hpool(); + auth_object = AuthRequest::HOST; + }; + + ~HostPoolInfo(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class GroupPoolInfo: public RequestManagerPoolInfo +{ +public: + GroupPoolInfo(): + RequestManagerPoolInfo("GroupPoolInfo", + "Returns the group pool") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_gpool(); + auth_object = AuthRequest::GROUP; + }; + + ~GroupPoolInfo(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class UserPoolInfo: public RequestManagerPoolInfo +{ +public: + UserPoolInfo(): + RequestManagerPoolInfo("UserPoolInfo", + "Returns the user pool") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_upool(); + auth_object = AuthRequest::USER; + }; + + ~UserPoolInfo(){}; +}; + + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerPoolInfoFilter.h b/include/RequestManagerPoolInfoFilter.h new file mode 100644 index 0000000000..102d24845d --- /dev/null +++ b/include/RequestManagerPoolInfoFilter.h @@ -0,0 +1,131 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_POOL_INFO_FILTER_H_ +#define REQUEST_MANAGER_POOL_INFO_FILTER_H_ + +#include "Request.h" +#include "Nebula.h" +#include "AuthManager.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerPoolInfoFilter: public Request +{ +protected: + RequestManagerPoolInfoFilter(const string& method_name, + const string& help) + :Request(method_name,"A:si",help) + { + auth_op = AuthRequest::INFO_POOL; + }; + + ~RequestManagerPoolInfoFilter(){}; + + /* -------------------------------------------------------------------- */ + + static const int ALL; /**< Secify all objects in the pool (-2) */ + static const int MINE; /**< Secify user's objects in the pool (-3)*/ + static const int MINE_GROUP; /**< Secify users + group objects (-1) */ + + /* -------------------------------------------------------------------- */ + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualMachinePoolInfo : public RequestManagerPoolInfoFilter +{ +public: + VirtualMachinePoolInfo(): + RequestManagerPoolInfoFilter("VirtualMachinePoolInfo", + "Returns the virtual machine instances pool") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vmpool(); + auth_object = AuthRequest::VM; + }; + + ~VirtualMachinePoolInfo(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class TemplatePoolInfo : public RequestManagerPoolInfoFilter +{ +public: + TemplatePoolInfo(): + RequestManagerPoolInfoFilter("TemplatePoolInfo", + "Returns the virtual machine template pool") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_tpool(); + auth_object = AuthRequest::TEMPLATE; + }; + + ~TemplatePoolInfo(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + + +class VirtualNetworkPoolInfo: public RequestManagerPoolInfoFilter +{ +public: + VirtualNetworkPoolInfo(): + RequestManagerPoolInfoFilter("VirtualNetworkPoolInfo", + "Returns the virtual network pool") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vnpool(); + auth_object = AuthRequest::NET; + }; + + ~VirtualNetworkPoolInfo(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class ImagePoolInfo: public RequestManagerPoolInfoFilter +{ +public: + ImagePoolInfo(): + RequestManagerPoolInfoFilter("ImagePoolInfo", + "Returns the image pool") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_ipool(); + auth_object = AuthRequest::IMAGE; + }; + + ~ImagePoolInfo(){}; +}; + + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerPublish.h b/include/RequestManagerPublish.h new file mode 100644 index 0000000000..95952680b5 --- /dev/null +++ b/include/RequestManagerPublish.h @@ -0,0 +1,136 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_PUBLISH_H_ +#define REQUEST_MANAGER_PUBLISH_H_ + +#include "Request.h" +#include "Nebula.h" +#include "AuthManager.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerPublish: public Request +{ +protected: + RequestManagerPublish(const string& method_name, + const string& help) + :Request(method_name,"A:sib",help) + { + auth_op = AuthRequest::MANAGE; + } + + ~RequestManagerPublish(){}; + + /* -------------------------------------------------------------------- */ + + void request_execute(xmlrpc_c::paramList const& _paramList); + + virtual int publish(PoolObjectSQL *object, bool pflag) = 0; +}; + + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class TemplatePublish : public RequestManagerPublish +{ +public: + TemplatePublish(): + RequestManagerPublish("TemplatePublish", + "Publish a virtual machine template") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_tpool(); + auth_object = AuthRequest::TEMPLATE; + }; + + ~TemplatePublish(){}; + + int publish(PoolObjectSQL *object, bool pflag) + { + VMTemplate * robject; + + robject = static_cast(object); + + return robject->publish(pflag); + } +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualNetworkPublish: public RequestManagerPublish +{ +public: + VirtualNetworkPublish(): + RequestManagerPublish("VirtualNetworkPublish", + "Publish a virtual network") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vnpool(); + auth_object = AuthRequest::NET; + }; + + ~VirtualNetworkPublish(){}; + + int publish(PoolObjectSQL *object, bool pflag) + { + VirtualNetwork * robject; + + robject = static_cast(object); + + robject->publish(pflag); + + return 0; + } +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class ImagePublish: public RequestManagerPublish +{ +public: + ImagePublish(): + RequestManagerPublish("ImagePublish", "Publish an image") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_ipool(); + auth_object = AuthRequest::IMAGE; + }; + + ~ImagePublish(){}; + + int publish(PoolObjectSQL *object, bool pflag) + { + Image * robject; + + robject = static_cast(object); + + return robject->publish(pflag); + } +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerUpdateTemplate.h b/include/RequestManagerUpdateTemplate.h new file mode 100644 index 0000000000..444d12479d --- /dev/null +++ b/include/RequestManagerUpdateTemplate.h @@ -0,0 +1,104 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_UPDATE_TEMPLATE_H +#define REQUEST_MANAGER_UPDATE_TEMPLATE_H + +#include "Request.h" +#include "Nebula.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerUpdateTemplate: public Request +{ +protected: + RequestManagerUpdateTemplate(const string& method_name, + const string& help) + :Request(method_name,"A:sis",help) + { + auth_op = AuthRequest::MANAGE; + }; + + ~RequestManagerUpdateTemplate(){}; + + /* -------------------------------------------------------------------- */ + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class TemplateUpdateTemplate: public RequestManagerUpdateTemplate +{ +public: + TemplateUpdateTemplate(): + RequestManagerUpdateTemplate("TemplateUpdateTemplate", + "Updates a virtual machine template") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_tpool(); + auth_object = AuthRequest::TEMPLATE; + }; + + ~TemplateUpdateTemplate(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class ImageUpdateTemplate: public RequestManagerUpdateTemplate +{ +public: + ImageUpdateTemplate(): + RequestManagerUpdateTemplate("ImageUpdateTemplate", + "Updates an image template") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_ipool(); + auth_object = AuthRequest::IMAGE; + }; + + ~ImageUpdateTemplate(){}; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class HostUpdateTemplate : public RequestManagerUpdateTemplate +{ +public: + HostUpdateTemplate(): + RequestManagerUpdateTemplate("HostUpdateTemplate", + "Updates a host template") + { + Nebula& nd = Nebula::instance(); + pool = nd.get_hpool(); + auth_object = AuthRequest::HOST; + }; + + ~HostUpdateTemplate(){}; +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerUser.h b/include/RequestManagerUser.h new file mode 100644 index 0000000000..deff4d2541 --- /dev/null +++ b/include/RequestManagerUser.h @@ -0,0 +1,113 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_USER_H +#define REQUEST_MANAGER_USER_H + +#include "Request.h" +#include "Nebula.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerUser: public Request +{ +protected: + RequestManagerUser(const string& method_name, + const string& help, + const string& params) + :Request(method_name,params,help) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_upool(); + + auth_object = AuthRequest::USER; + auth_op = AuthRequest::MANAGE; + }; + + ~RequestManagerUser(){}; + + /* -------------------------------------------------------------------- */ + + void request_execute(xmlrpc_c::paramList const& _paramList); + + virtual int user_action(User * user, + xmlrpc_c::paramList const& _paramList, + string& error_str ) = 0; + + /* -------------------------------------------------------------------- */ +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class UserChangePassword : public RequestManagerUser +{ +public: + UserChangePassword(): + RequestManagerUser("UserChangePassword", + "Changes user's password", + "A:sis"){}; + ~UserChangePassword(){}; + + int user_action(User * user, + xmlrpc_c::paramList const& _paramList, + string& err); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class UserAddGroup : public RequestManagerUser +{ +public: + UserAddGroup(): + RequestManagerUser("UserAddGroup", + "Adds a new group to the user", + "A:sii"){}; + ~UserAddGroup(){}; + + int user_action(User * user, + xmlrpc_c::paramList const& _paramList, + string& err); +}; + + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class UserDelGroup : public RequestManagerUser +{ +public: + UserDelGroup(): + RequestManagerUser("UserDelGroup", + "Deletes a new group to the user", + "A:sii"){}; + ~UserDelGroup(){}; + + int user_action(User * user, + xmlrpc_c::paramList const& _paramList, + string& err); +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerVMTemplate.h b/include/RequestManagerVMTemplate.h new file mode 100644 index 0000000000..7269cbecf7 --- /dev/null +++ b/include/RequestManagerVMTemplate.h @@ -0,0 +1,73 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_VM_TEMPLATE_H +#define REQUEST_MANAGER_VM_TEMPLATE_H + +#include "Request.h" +#include "Nebula.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerVMTemplate: public Request +{ +protected: + RequestManagerVMTemplate(const string& method_name, + const string& help, + const string& params) + :Request(method_name,params,help) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_tpool(); + + auth_object = AuthRequest::TEMPLATE; + }; + + ~RequestManagerVMTemplate(){}; + + /* -------------------------------------------------------------------- */ + + virtual void request_execute(xmlrpc_c::paramList const& _paramList) = 0; +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VMTemplateInstantiate : public RequestManagerVMTemplate +{ +public: + VMTemplateInstantiate(): + RequestManagerVMTemplate("TemplateInstantiate", + "Instantiates a new virtual machine using a template", + "A:sis") + { + auth_op = AuthRequest::INSTANTIATE; + }; + + ~VMTemplateInstantiate(){}; + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerVirtualMachine.h b/include/RequestManagerVirtualMachine.h new file mode 100644 index 0000000000..8f42963fe8 --- /dev/null +++ b/include/RequestManagerVirtualMachine.h @@ -0,0 +1,130 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_VIRTUAL_MACHINE_H_ +#define REQUEST_MANAGER_VIRTUAL_MACHINE_H + +#include "Request.h" +#include "Nebula.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerVirtualMachine: public Request +{ +protected: + RequestManagerVirtualMachine(const string& method_name, + const string& help, + const string& params) + :Request(method_name,params,help) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vmpool(); + + auth_object = AuthRequest::VM; + auth_op = AuthRequest::MANAGE; + }; + + ~RequestManagerVirtualMachine(){}; + + /* -------------------------------------------------------------------- */ + + virtual void request_execute(xmlrpc_c::paramList const& _paramList) = 0; + + bool vm_authorization(int id, int hid, ImageTemplate *tmpl); + + int get_host_information(int hid, string& name, string& vmm, string& tm); + + int add_history(VirtualMachine * vm, + int hid, + const string& hostname, + const string& vmm_mad, + const string& tm_mad); + + VirtualMachine * get_vm(int id); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualMachineAction : public RequestManagerVirtualMachine +{ +public: + VirtualMachineAction(): + RequestManagerVirtualMachine("VirtualMachineAction", + "Performs an action on a virtual machine", + "A:ssi"){}; + ~VirtualMachineAction(){}; + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualMachineDeploy : public RequestManagerVirtualMachine +{ +public: + VirtualMachineDeploy(): + RequestManagerVirtualMachine("VirtualMachineDeploy", + "Deploys a virtual machine", + "A:sii"){}; + + ~VirtualMachineDeploy(){}; + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualMachineMigrate : public RequestManagerVirtualMachine +{ +public: + VirtualMachineMigrate(): + RequestManagerVirtualMachine("VirtualMachineDeploy", + "Migrates a virtual machine", + "A:siib"){}; + + ~VirtualMachineMigrate(){}; + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualMachineSaveDisk : public RequestManagerVirtualMachine +{ +public: + VirtualMachineSaveDisk(): + RequestManagerVirtualMachine("VirtualMachineSaveDisk", + "Saves a disk from virtual machine as a new image", + "A:siis"){}; + + ~VirtualMachineSaveDisk(){}; + + void request_execute(xmlrpc_c::paramList const& _paramList); +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/RequestManagerVirtualNetwork.h b/include/RequestManagerVirtualNetwork.h new file mode 100644 index 0000000000..3e77b61b74 --- /dev/null +++ b/include/RequestManagerVirtualNetwork.h @@ -0,0 +1,100 @@ +/* -------------------------------------------------------------------------- */ +/* 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 REQUEST_MANAGER_VIRTUAL_NETWORK_H +#define REQUEST_MANAGER_VIRTUAL_NETWORK_H + +#include "Request.h" +#include "Nebula.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class RequestManagerVirtualNetwork: public Request +{ +protected: + RequestManagerVirtualNetwork(const string& method_name, + const string& help) + :Request(method_name,"A:sis",help) + { + Nebula& nd = Nebula::instance(); + pool = nd.get_vnpool(); + + auth_object = AuthRequest::NET; + auth_op = AuthRequest::MANAGE; + }; + + ~RequestManagerVirtualNetwork(){}; + + /* -------------------------------------------------------------------- */ + + void request_execute(xmlrpc_c::paramList const& _paramList); + + virtual int leases_action(VirtualNetwork * vn, + VirtualNetworkTemplate * tmpl, + string& error_str) = 0; + /* -------------------------------------------------------------------- */ + + string leases_error (char * error); +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualNetworkAddLeases : public RequestManagerVirtualNetwork +{ +public: + VirtualNetworkAddLeases(): + RequestManagerVirtualNetwork("VirtualNetworkAddLeases", + "Adds leases to a virtual network"){}; + ~VirtualNetworkAddLeases(){}; + + int leases_action(VirtualNetwork * vn, + VirtualNetworkTemplate * tmpl, + string& error_str) + { + return vn->add_leases(tmpl, error_str); + } +}; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +class VirtualNetworkRemoveLeases : public RequestManagerVirtualNetwork +{ +public: + VirtualNetworkRemoveLeases(): + RequestManagerVirtualNetwork("VirtualNetworkRemoveLeases", + "Removes leases from a virtual network"){}; + ~VirtualNetworkRemoveLeases(){}; + + int leases_action(VirtualNetwork * vn, + VirtualNetworkTemplate * tmpl, + string& error_str) + { + return vn->remove_leases(tmpl, error_str); + } +}; + + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif diff --git a/include/Template.h b/include/Template.h index 2c623ffb42..ffca1d9612 100644 --- a/include/Template.h +++ b/include/Template.h @@ -128,24 +128,23 @@ public: * attributes MUST be freed by the calling funtion * @param name of the attribute * @param values a vector containing a pointer to the attributes - * @returns the number of attributes removed + * @return the number of attributes removed */ virtual int remove( const string& name, vector& values); - /** * Removes an attribute from the template, and frees the attributes. * @param name of the attribute - * @returns the number of attributes removed + * @return the number of attributes removed */ virtual int erase(const string& name); /** * Gets all the attributes with the given name. * @param name the attribute name. - * @returns the number of elements in the vector + * @return the number of elements in the vector */ virtual int get( const string& name, @@ -154,7 +153,7 @@ public: /** * Gets all the attributes with the given name, non-const version * @param name the attribute name. - * @returns the number of elements in the vector + * @return the number of elements in the vector */ virtual int get( const string& name, @@ -176,7 +175,7 @@ public: * @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 + * @return True if the Single attribute was found */ virtual bool get( string& name, diff --git a/include/User.h b/include/User.h index 437dd28f87..ee57ed35ba 100644 --- a/include/User.h +++ b/include/User.h @@ -18,6 +18,7 @@ #define USER_H_ #include "PoolSQL.h" +#include "ObjectCollection.h" using namespace std; @@ -27,15 +28,10 @@ using namespace std; /** * The User class. */ -class User : public PoolObjectSQL +class User : public PoolObjectSQL, public ObjectCollection { public: - /** - * Function to write a User on an output stream - */ - friend ostream& operator<<(ostream& os, User& u); - /** * Function to print the User object into a string in XML format * @param xml the resulting XML string @@ -94,6 +90,47 @@ public: **/ static int split_secret(const string secret, string& user, string& pass); + /** + * Returns a copy of the groups for the user + */ + set get_groups() + { + return get_collection_copy(); + }; + + // ************************************************************************* + // Group IDs set Management + // ************************************************************************* + + /** + * Adds a group ID to the groups set. + * + * @param id The new id + * @return 0 on success, -1 if the ID was already in the set + */ + int add_group(int group_id) + { + return add_collection_id(group_id); + } + + /** + * Deletes a group ID from the groups set. + * + * @param id The id + * @return 0 on success, + * -1 if the ID was not in the set, + * -2 if the group to delete is the main group + */ + int del_group(int group_id) + { + if( group_id == gid ) + { + return -2; + } + + return del_collection_id(group_id); + } + private: // ------------------------------------------------------------------------- // Friends @@ -145,18 +182,20 @@ private: */ int from_xml(const string &xml_str); + protected: // ************************************************************************* // Constructor // ************************************************************************* - User(int id, - string _username, - string _password, - bool _enabled); + User(int id, int _gid, const string& _username, const string& _password, bool _enabled): + PoolObjectSQL(id,_username,-1,_gid,table), + ObjectCollection("GROUPS"), + password(_password), enabled(_enabled) + { }; - virtual ~User(); + virtual ~User(){}; // ************************************************************************* // DataBase implementation diff --git a/include/UserPool.h b/include/UserPool.h index e381deb017..5154067aa4 100644 --- a/include/UserPool.h +++ b/include/UserPool.h @@ -19,6 +19,7 @@ #include "PoolSQL.h" #include "User.h" +#include "GroupPool.h" #include #include @@ -49,7 +50,8 @@ public: */ int allocate ( int * oid, - string hostname, + int gid, + string username, string password, bool enabled, string& error_str); @@ -87,14 +89,6 @@ public: return user->update(db); }; - /** Drops a user from the DB, the user mutex MUST BE locked - * @param user pointer to User - */ - int drop(User * user) - { - return PoolSQL::drop(user); - }; - /** * Bootstraps the database table(s) associated to the User pool */ @@ -106,9 +100,11 @@ public: /** * Returns whether there is a user with given username/password or not * @param session, colon separated username and password string - * @return -1 if authn failed, uid of the user in other case + * @param uid of the user if authN succeeded -1 otherwise + * @param gid of the user if authN succeeded -1 otherwise + * @return false if authn failed, true otherwise */ - int authenticate(string& session); + bool authenticate(const string& session, int& uid, int& gid); /** * Returns whether there is a user with given username/password or not @@ -137,7 +133,7 @@ private: */ PoolObjectSQL * create() { - return new User(-1,"","",true); + return new User(-1,-1,"","",true); }; }; diff --git a/include/VMTemplate.h b/include/VMTemplate.h index 7a92818bda..b47a6fd705 100644 --- a/include/VMTemplate.h +++ b/include/VMTemplate.h @@ -30,11 +30,6 @@ 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 @@ -42,38 +37,37 @@ public: */ 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) + int publish(bool pub) { if (pub == true) { - public_template = 1; + public_obj = 1; } else { - public_template = 0; + public_obj = 0; } - return true; + return 0; }; // ------------------------------------------------------------------------ // Template Contents // ------------------------------------------------------------------------ + /** + * Factory method for virtual machine templates + */ + Template * get_new_template() + { + return new VirtualMachineTemplate; + } + /** * Returns a copy of the VirtualMachineTemplate * @return A copy of the VirtualMachineTemplate @@ -82,15 +76,6 @@ public: { return new VirtualMachineTemplate( *(static_cast(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: @@ -104,16 +89,6 @@ private: // VMTemplate Attributes // ------------------------------------------------------------------------- - /** - * Owner's name - */ - string user_name; - - /** - * Public scope of the VMTemplate - */ - int public_template; - /** * Registration time */ @@ -154,8 +129,8 @@ protected: // ************************************************************************* // Constructor // ************************************************************************* - VMTemplate(int id, int uid, string _user_name, - VirtualMachineTemplate * _template_contents); + VMTemplate(int id, int uid, int gid, + VirtualMachineTemplate * _template_contents); ~VMTemplate(); diff --git a/include/VMTemplatePool.h b/include/VMTemplatePool.h index 92660f6226..4ebb5a0280 100644 --- a/include/VMTemplatePool.h +++ b/include/VMTemplatePool.h @@ -35,7 +35,7 @@ public: * 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 gid the id of the group this object is assigned to * @param template_contents a VM Template object * @param oid the id assigned to the Template * @param error_str Returns the error reason, if any @@ -43,7 +43,7 @@ public: * @return the oid assigned to the object, -1 in case of failure */ int allocate(int uid, - string user_name, + int gid, VirtualMachineTemplate * template_contents, int * oid, string& error_str); @@ -87,17 +87,6 @@ public: 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 @@ -139,7 +128,7 @@ private: */ PoolObjectSQL * create() { - return new VMTemplate(-1,-1,"", 0); + return new VMTemplate(-1,-1,-1,0); }; }; diff --git a/include/VirtualMachine.h b/include/VirtualMachine.h index 6295b100ca..ff0e436ac5 100644 --- a/include/VirtualMachine.h +++ b/include/VirtualMachine.h @@ -28,6 +28,8 @@ using namespace std; +class AuthRequest; + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -114,11 +116,6 @@ public: } }; - /** - * Function to write a Virtual Machine in an output stream - */ - friend ostream& operator<<(ostream& os, const VirtualMachine& vm); - /** * Function to print the VirtualMachine object into a string in * XML format @@ -540,6 +537,14 @@ public: * @return 0 on success. */ int parse_template_attribute(const string& attribute, string& parsed); + + /** + * Factory method for virtual machine templates + */ + Template * get_new_template() + { + return new VirtualMachineTemplate; + } // ------------------------------------------------------------------------ // States @@ -657,6 +662,19 @@ public: */ int save_disk(int disk_id, int img_id, string& error_str); + // ------------------------------------------------------------------------ + // Authorization related functions + // ------------------------------------------------------------------------ + /** + * Sets an authorization request for a VirtualMachine template based on + * the images and networks used + * @param uid for template owner + * @param ar the AuthRequest object + * @param tmpl the virtual machine template + */ + static void set_auth_request(int uid, + AuthRequest& ar, + VirtualMachineTemplate *tmpl); private: // ------------------------------------------------------------------------- @@ -668,14 +686,6 @@ private: // Virtual Machine Attributes // ************************************************************************* - // ------------------------------------------------------------------------- - // Identification variables - // ------------------------------------------------------------------------- - /** - * Owner's name - */ - string user_name; - // ------------------------------------------------------------------------- // VM Scheduling & Managing Information // ------------------------------------------------------------------------- @@ -855,8 +865,8 @@ protected: // Constructor //************************************************************************** - VirtualMachine(int id, int uid, string _user_name, - VirtualMachineTemplate * _vm_template); + VirtualMachine(int id, int uid, + int gid, VirtualMachineTemplate * _vm_template); virtual ~VirtualMachine(); diff --git a/include/VirtualMachinePool.h b/include/VirtualMachinePool.h index cedf998473..f84723259c 100644 --- a/include/VirtualMachinePool.h +++ b/include/VirtualMachinePool.h @@ -41,7 +41,7 @@ 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 gid the id of the group this object is assigned to * @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 @@ -51,7 +51,7 @@ public: */ int allocate ( int uid, - string user_name, + int gid, VirtualMachineTemplate * vm_template, int * oid, string& error_str, @@ -146,7 +146,6 @@ public: * pool * @param oss the output stream to dump the pool contents * @param where filter for the objects, defaults to all - * @param extended condition to include history and username data * @param state include only VMs in this state. -1 means any state, * except DONE * @@ -161,7 +160,7 @@ private: */ PoolObjectSQL * create() { - return new VirtualMachine(-1,-1,"", 0); + return new VirtualMachine(-1,-1,-1,0); }; }; diff --git a/include/VirtualNetwork.h b/include/VirtualNetwork.h index 5df5114888..51ed7fd7dd 100644 --- a/include/VirtualNetwork.h +++ b/include/VirtualNetwork.h @@ -20,6 +20,7 @@ #include "PoolSQL.h" #include "Leases.h" +#include "VirtualNetworkTemplate.h" #include #include @@ -32,7 +33,6 @@ using namespace std; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -class VirtualNetworkTemplate; /** * The Virtual Network class. It represents a Virtual Network at manages its @@ -58,15 +58,6 @@ public: // Virtual Network Public Methods // ************************************************************************* - /** - * Returns true if the Virtual Network is public - * @return true if the Virtual Network is public - */ - bool isPublic() - { - return (public_vnet == 1); - }; - /** * Publish or unpublish a virtual network * @param pub true to publish the image @@ -76,14 +67,22 @@ public: { if (pub == true) { - public_vnet = 1; + public_obj = 1; } else { - public_vnet = 0; + public_obj = 0; } } + /** + * Factory method for virtual network templates + */ + Template * get_new_template() + { + return new VirtualNetworkTemplate; + } + /** * Adds Leases to the virtual network (Only implemented for FIXED networks) * @param leases_template template in the form LEASES = [IP=XX, MAC=XX]. @@ -187,14 +186,6 @@ private: // Virtual Network Private Attributes // ************************************************************************* - // ------------------------------------------------------------------------- - // Identification variables - // ------------------------------------------------------------------------- - /** - * Owner's name - */ - string user_name; - // ------------------------------------------------------------------------- // Binded physical attributes // ------------------------------------------------------------------------- @@ -212,11 +203,6 @@ private: */ NetworkType type; - /** - * Public scope of this Virtual Network - */ - int public_vnet; - /** * Pointer to leases class, can be fixed or ranged. * Holds information on given (and, optionally, possible) leases @@ -268,8 +254,8 @@ private: // Constructor //************************************************************************** - VirtualNetwork(int uid, - string _user_name, + VirtualNetwork(int uid, + int gid, VirtualNetworkTemplate * _vn_template = 0); ~VirtualNetwork(); diff --git a/include/VirtualNetworkPool.h b/include/VirtualNetworkPool.h index 09e908cf93..1f6f2d3724 100644 --- a/include/VirtualNetworkPool.h +++ b/include/VirtualNetworkPool.h @@ -42,16 +42,18 @@ public: /** * Function to allocate a new VNET object * @param uid user identifier + * @param gid the id of the group this object is assigned to * @param vn_template a VirtualNetworkTemplate describing the VNET * @param oid the id assigned to the VM (output) + * @param error_str Returns the error reason, if any * @return oid on success, -1 error */ int allocate ( - int uid, - string user_name, - VirtualNetworkTemplate * vn_template, - int * oid, - string& error_str); + int uid, + int gid, + VirtualNetworkTemplate * vn_template, + int * oid, + string& error_str); /** * Function to get a VN from the pool, if the object is not in memory @@ -154,7 +156,7 @@ private: */ PoolObjectSQL * create() { - return new VirtualNetwork(0,"",0); + return new VirtualNetwork(-1,-1, 0); }; }; diff --git a/include/test/NebulaTest.h b/include/test/NebulaTest.h index 52c551799d..d8800d58f1 100644 --- a/include/test/NebulaTest.h +++ b/include/test/NebulaTest.h @@ -25,7 +25,6 @@ #include "VirtualNetworkPool.h" #include "HostPool.h" #include "UserPool.h" -#include "ClusterPool.h" #include "VMTemplatePool.h" #include "VirtualMachineManager.h" @@ -44,12 +43,13 @@ 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_template_pool(false),need_vmm(false), + need_user_pool(false), need_template_pool(false), + need_group_pool(false), + need_vmm(false), need_im(false), need_tm(false), need_lcm(false), need_dm(false), need_rm(false), need_hm(false), - need_authm(false) + need_authm(false), need_imagem(false) {}; virtual ~NebulaTest(){}; @@ -64,8 +64,8 @@ public: bool need_vnet_pool; bool need_image_pool; bool need_user_pool; - bool need_cluster_pool; bool need_template_pool; + bool need_group_pool; bool need_vmm; bool need_im; @@ -100,10 +100,10 @@ public: string default_image_type, string default_device_prefix); - virtual ClusterPool* create_cpool(SqlDB* db); - virtual VMTemplatePool* create_tpool(SqlDB* db); + virtual GroupPool* create_gpool(SqlDB* db); + // ------------------------------------------------------------------------ // Managers // ------------------------------------------------------------------------ @@ -126,15 +126,7 @@ public: virtual DispatchManager* create_dm(VirtualMachinePool* vmpool, HostPool* hpool); - virtual RequestManager* create_rm( - VirtualMachinePool * vmpool, - HostPool * hpool, - VirtualNetworkPool * vnpool, - UserPool * upool, - ImagePool * ipool, - ClusterPool * cpool, - VMTemplatePool * tpool, - string log_file); + virtual RequestManager* create_rm(string log_file); virtual HookManager* create_hm(VirtualMachinePool * vmpool); diff --git a/include/test/PoolTest.h b/include/test/PoolTest.h index 1e5afe32d9..cc7d558652 100644 --- a/include/test/PoolTest.h +++ b/include/test/PoolTest.h @@ -68,6 +68,37 @@ protected: PoolTest():pool(0){}; virtual ~PoolTest(){}; + /** + * Replaces all elements, padding them with 0 + */ + string fix_regtimes(string& xml) + { + return fix_time(xml, "REGTIME"); + } + + string fix_stimes(string& xml) + { + return fix_time(xml, "STIME"); + } + + string fix_time(string& xml, string elem_name) + { + string start = "<" + elem_name + ">"; + string replacement = "0000000000"; + size_t pos = 0; + + while( (pos = xml.find(start, pos)) != string::npos ) + { + if ( xml[pos+start.size()] != '0' ) + { + xml.replace( pos+start.size(), replacement.size(), replacement); + } + pos++; + } + + return xml; + } + public: void setUp() @@ -180,6 +211,7 @@ public: void drop_and_get() { int oid_0, oid_1; + string error_str; // Allocate two objects oid_0 = allocate(0); @@ -201,7 +233,7 @@ public: obj->lock(); // Delete it - pool->drop(obj); + pool->drop(obj, error_str); if(obj != 0) { diff --git a/install.sh b/install.sh index 7e48aaa9d7..681b8cff95 100755 --- a/install.sh +++ b/install.sh @@ -348,8 +348,8 @@ BIN_FILES="src/nebula/oned \ src/cli/onevnet \ src/cli/oneuser \ src/cli/oneimage \ - src/cli/onecluster \ src/cli/onetemplate \ + src/cli/onegroup \ src/cli/onedb \ share/scripts/one \ src/authm_mad/oneauth" @@ -393,10 +393,10 @@ RUBY_OPENNEBULA_LIB_FILES="src/oca/ruby/OpenNebula/Host.rb \ src/oca/ruby/OpenNebula/VirtualNetworkPool.rb \ src/oca/ruby/OpenNebula/Image.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/Group.rb \ + src/oca/ruby/OpenNebula/GroupPool.rb \ src/oca/ruby/OpenNebula/XMLUtils.rb" @@ -726,8 +726,8 @@ CLI_BIN_FILES="src/cli/onevm \ src/cli/onevnet \ src/cli/oneuser \ src/cli/oneimage \ - src/cli/onecluster \ - src/cli/onetemplate" + src/cli/onetemplate \ + src/cli/onegroup" #----------------------------------------------------------------------------- # Sunstone files @@ -836,7 +836,6 @@ SUNSTONE_RUBY_LIB_FILES="src/mad/ruby/CommandManager.rb \ #----------------------------------------------------------------------------- MAN_FILES="share/man/oneauth.1.gz \ - share/man/onecluster.1.gz \ share/man/onehost.1.gz \ share/man/oneimage.1.gz \ share/man/oneuser.1.gz \ diff --git a/share/man/SConstruct b/share/man/SConstruct index 41e8b02af5..d25d1256b6 100644 --- a/share/man/SConstruct +++ b/share/man/SConstruct @@ -34,7 +34,6 @@ env.Man('occi-compute') env.Man('occi-network') env.Man('occi-storage') env.Man('oneauth') -env.Man('onecluster') env.Man('onedb') env.Man('onehost') env.Man('oneimage') diff --git a/share/man/onecluster.1 b/share/man/onecluster.1 deleted file mode 100644 index 6b8ee43ec0..0000000000 --- a/share/man/onecluster.1 +++ /dev/null @@ -1,76 +0,0 @@ -.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.37.1. -.TH OPENNEBULAPRO "1" "May 2011" "OpenNebulaPro 2.2.0" "User Commands" -.SH NAME -OpenNebulaPro \- OpenNebula Cluster command -.SH SYNOPSIS -.B onecluster -[\fI\fR] \fI \fR[\fI\fR] -.SH DESCRIPTION - -This command enables the OpenNebula administrator to manage clusters. The -administrator can create, delete, as well as add and remove hosts from them. -Any user can list available clusters. -.SH OPTIONS -.TP -\fB\-l\fR, \fB\-\-list\fR x,y,z -Selects columns to display with list -command -.TP -\fB\-\-list\-columns\fR -Information about the columns available -to display, order or filter -.TP -\fB\-o\fR, \fB\-\-order\fR x,y,z -Order by these columns, column starting -with \- means decreasing order -.TP -\fB\-f\fR, \fB\-\-filter\fR x,y,z -Filter data. An array is specified -with column=value pairs. -.TP -\fB\-x\fR, \fB\-\-xml\fR -Returns xml instead of human readable text -.TP -\fB\-v\fR, \fB\-\-verbose\fR -Tells more information if the command -is successful -.TP -\fB\-h\fR, \fB\-\-help\fR -Shows this help message -.TP -\fB\-\-version\fR -Shows version and copyright information -.SH COMMANDS -.TP -\fBcreate\fR (Creates a new cluster) -.IP -onecluster create clustername -.TP -\fBdelete\fR (Removes a cluster) -.IP -onecluster delete -.TP -\fBlist\fR (Lists all the clusters in the pool) -.IP -onecluster list -.TP -\fBaddhost\fR (Add a host to the cluster) -.IP -onecluster addhost -.TP -\fBremovehost\fR (Remove a host from the cluster) -.IP -onecluster removehost -.SH COPYRIGHT -Copyright 2010\-2011, C12G Labs S.L. -.PP -Licensed under the C12G Commercial Open\-source License (the -"License"); you may not use this file except in compliance -with the License. You may obtain a copy of the License as part -of the software distribution. -.PP -Unless 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. diff --git a/share/test/do_tests.sh b/share/test/do_tests.sh index 1e18096337..932b862d6c 100755 --- a/share/test/do_tests.sh +++ b/share/test/do_tests.sh @@ -10,7 +10,6 @@ TESTS="$TWD_DIR/vnm/test \ $TWD_DIR/scheduler/src/pool/test \ $TWD_DIR/common/test \ $TWD_DIR/host/test \ - $TWD_DIR/cluster/test \ $TWD_DIR/template/test \ $TWD_DIR/image/test \ $TWD_DIR/authm/test \ @@ -18,7 +17,8 @@ TESTS="$TWD_DIR/vnm/test \ $TWD_DIR/um/test \ $TWD_DIR/lcm/test \ $TWD_DIR/pool/test \ - $TWD_DIR/vm_template/test" + $TWD_DIR/vm_template/test \ + $TWD_DIR/group/test" #------------------------------------------------------------------------------- # COMMAND LINE PARSING diff --git a/src/authm/AuthManager.cc b/src/authm/AuthManager.cc index d661f76b74..0753d69f85 100644 --- a/src/authm/AuthManager.cc +++ b/src/authm/AuthManager.cc @@ -46,8 +46,8 @@ void AuthRequest::add_auth(Object ob, case NET: oss << "NET:" ; break; case IMAGE: oss << "IMAGE:" ; break; case USER: oss << "USER:" ; break; - case CLUSTER: oss << "CLUSTER:" ; break; case TEMPLATE: oss << "TEMPLATE:" ; break; + case GROUP: oss << "GROUP:" ; break; } if (op == CREATE || op == INSTANTIATE) //encode the ob_id, it is a template @@ -91,9 +91,21 @@ void AuthRequest::add_auth(Object ob, oss << "INFO:" ; break; + case INFO_POOL: + oss << "INFO_POOL:" ; + break; + + case INFO_POOL_MINE: + oss << "INFO_POOL_MINE:" ; + break; + case INSTANTIATE: oss << "INSTANTIATE:" ; break; + + case CHOWN: + oss << "CHOWN:" ; + break; } oss << owner << ":" << pub; @@ -145,8 +157,36 @@ void AuthRequest::add_auth(Object ob, auth = owner == uid; break; - case INFO: // This is for completeness, as the only INFO existing - // is for UserPool, and just oneadmin can see it + case INFO: + if ( ob != USER ) // User info only for root or owner + { + auth = true; + } + else + { + istringstream iss(ob_id); + int ob_id_int; + + iss >> ob_id_int; + + if (ob_id_int == uid) + { + auth = true; + } + } + break; + + case INFO_POOL: + if ( ob != USER ) // User pool only for oneadmin + { + auth = true; + } + break; + + case INFO_POOL_MINE: + auth = true; + break; + case CHOWN: //true only for oneadmin break; } } diff --git a/src/cli/client_utilities.rb b/src/cli/client_utilities.rb index 90e7307bd1..ec89423f8e 100644 --- a/src/cli/client_utilities.rb +++ b/src/cli/client_utilities.rb @@ -313,14 +313,14 @@ def get_image_id(name) get_entity_id(name, OpenNebula::ImagePool) end -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 get_group_id(name) + get_entity_id(name, OpenNebula::GroupPool) +end + def str_running_time(data) stime=Time.at(data["STIME"].to_i) if data["ETIME"]=="0" diff --git a/src/cli/onecluster b/src/cli/onegroup similarity index 56% rename from src/cli/onecluster rename to src/cli/onegroup index bda90aac1f..5a6670c0aa 100755 --- a/src/cli/onecluster +++ b/src/cli/onegroup @@ -35,30 +35,38 @@ require 'command_parse' ShowTableUP={ :id => { :name => "ID", - :desc => "ONE identifier for cluster", + :desc => "ONE identifier for group", :size => 4, - :proc => lambda {|d,e| - d.id + :proc => lambda {|d,e| + d.id + } + }, + :uid => { + :name => "OWNER", + :desc => "Owner of the group", + :size => 5, + :proc => lambda {|d,e| + d.uid } }, :name => { :name => "NAME", - :desc => "Name of the cluster", - :size => 8, + :desc => "Name of the group", + :size => 16, :proc => lambda {|d,e| d.name } }, - - :default => [:id, :name] + + :default => [:id, :uid, :name] } class UPShow def initialize - @clusterpool=OpenNebula::ClusterPool.new(get_one_client) + @grouppool=OpenNebula::GroupPool.new(get_one_client) @table=ShowTable.new(ShowTableUP) end - + def header_up_small scr_bold scr_underline @@ -66,9 +74,9 @@ class UPShow scr_restore puts "" end - + def list_short(options=nil) - res=@clusterpool.info + res=@grouppool.info if options @table.columns=options[:columns] if options[:columns] end @@ -78,41 +86,33 @@ class UPShow else result=res header_up_small - - puts @table.data_str(@clusterpool, options) + + puts @table.data_str(@grouppool, options) result end end end class OneUPParse < CommandParse - + COMMANDS_HELP=<<-EOT Description: -This command enables the OpenNebula administrator to manage clusters. The -administrator can create, delete, as well as add and remove hosts from them. -Any user can list available clusters. +This command enables the OpenNebula administrator to manage groups. Commands: -* create (Creates a new cluster) - onecluster create clustername - -* delete (Removes a cluster) - onecluster delete - -* list (Lists all the clusters in the pool) - onecluster list +* create (Creates a new group) + onegroup create groupname + +* delete (Removes a group) + onegroup delete + +* list (Lists all the groups in the pool) + onegroup list -* addhost (Add a host to the cluster) - onecluster addhost - -* removehost (Remove a host from the cluster) - onecluster removehost - EOT def text_commands @@ -120,7 +120,7 @@ EOT end def text_command_name - "onecluster" + "onegroup" end def list_options @@ -141,76 +141,40 @@ command=ARGV.shift case command when "create" check_parameters("create", 1) - cluster=OpenNebula::Cluster.new(OpenNebula::Cluster.build_xml, get_one_client) - result=cluster.allocate(ARGV[0]) - + group=OpenNebula::Group.new(OpenNebula::Group.build_xml, get_one_client) + result=group.allocate(ARGV[0]) + if is_successful?(result) - puts "ID: " + cluster.id.to_s if ops[:verbose] + puts "ID: " + group.id.to_s if ops[:verbose] exit 0 end - + when "delete" check_parameters("delete", 1) args=expand_args(ARGV) args.each do |param| - cluster_id=get_cluster_id(param) - cluster=OpenNebula::Cluster.new( - OpenNebula::Cluster.build_xml(cluster_id), get_one_client) - result=cluster.delete + group_id=get_group_id(param) + group=OpenNebula::Group.new( + OpenNebula::Group.build_xml(group_id), get_one_client) + result=group.delete if !OpenNebula.is_error?(result) - puts "Cluster deleted" if ops[:verbose] + puts "Group deleted" if ops[:verbose] break end end -when "addhost" - check_parameters("addhost", 2) - cluster_id=get_cluster_id(ARGV[-1]) - cluster=OpenNebula::Cluster.new( - OpenNebula::Cluster.build_xml(cluster_id), get_one_client) - args=expand_args(ARGV[0..-2]) - - args.each do |param| - host_id=get_host_id(param) - - result=cluster.add_host(host_id) - if is_successful?(result) - puts "Added HOST to the Cluster" if ops[:verbose] - else - break - end - end - -when "removehost" - check_parameters("removehost", 2) - cluster_id=get_cluster_id(ARGV[-1]) - cluster=OpenNebula::Cluster.new( - OpenNebula::Cluster.build_xml(cluster_id), get_one_client) - args=expand_args(ARGV[0..-2]) - - args.each do |param| - host_id=get_host_id(param) - - result=cluster.remove_host(host_id) - if is_successful?(result) - puts "Host removed from the Cluster" if ops[:verbose] - else - break - end - end - when "list" if !ops[:xml] uplist=UPShow.new ops[:columns]=ops[:list] if ops[:list] result=uplist.list_short(ops) else - clusterpool=OpenNebula::ClusterPool.new(get_one_client) - clusterpool.info - puts clusterpool.to_xml(true) + grouppool=OpenNebula::GroupPool.new(get_one_client) + grouppool.info + puts grouppool.to_xml(true) end - + else oneup_opts.print_help exit -1 diff --git a/src/cli/onehost b/src/cli/onehost index 281ce5335a..c6a9475474 100755 --- a/src/cli/onehost +++ b/src/cli/onehost @@ -46,12 +46,19 @@ ShowTableHost={ :left => true, :proc => lambda {|d,e| d.name } }, + # TODO + :cid => { + :name => "CID", + :desc => "Cluster ID", + :size => 4, + :proc => lambda {|d,e| d.cluster_id } + }, :cluster => { :name => "CLUSTER", :desc => "Clustername", :size => 8, :left => true, - :proc => lambda {|d,e| d.cluster } + :proc => lambda { "TODO" } }, :rvm => { :name => "RVM", @@ -107,7 +114,7 @@ ShowTableHost={ }, - :default => [:id, :name, :cluster, :rvm, :tcpu, :fcpu, :acpu, :tmem, :fmem, :stat] + :default => [:id, :name, :rvm, :tcpu, :fcpu, :acpu, :tmem, :fmem, :stat] } class HostShow @@ -285,7 +292,10 @@ when "show" puts str % ["ID", host.id.to_s] puts str % ["NAME", host.name] - puts str % ["CLUSTER", host['CLUSTER']] + + # TODO + puts str % ["CLUSTER", "TODO"] +# puts str % ["CLUSTER", host['CLUSTER']] puts str % ["STATE", host.state_str] puts str % ["IM_MAD", host['IM_MAD']] puts str % ["VM_MAD", host['VM_MAD']] diff --git a/src/cli/oneimage b/src/cli/oneimage index 09cd59fd64..ce0f0c5ace 100755 --- a/src/cli/oneimage +++ b/src/cli/oneimage @@ -44,7 +44,23 @@ ShowTableImage={ :desc => "Name of the owner", :size => 8, :proc => lambda {|d,e| - d["USERNAME"] + "TODO" + } + }, + :uid=> { + :name => "UID", + :desc => "Id of the owner", + :size => 4, + :proc => lambda {|d,e| + d["UID"] + } + }, + :gid=> { + :name => "GID", + :desc => "Id of the group", + :size => 4, + :proc => lambda {|d,e| + d.gid } }, :name => { @@ -215,11 +231,8 @@ Commands: * addattr (Add a new image attribute) oneimage addattr -* update (Modifies an image attribute) - oneimage update - -* rmattr (Deletes an Image attribute) - oneimage rmattr +* update (Lets the user edit and replace the image template) + oneimage update * enable (Enabled an Image) oneimage enable @@ -238,14 +251,21 @@ Commands: * nonpersistent (Makes an Image non persistent) oneimage nonpersistent - + +* chown (Changes the Image owner and group) + oneimage chown [] + +* chgrp (Changes the Image group) + oneimage chgrp + * list (Shows Images in the pool) oneimage list where filter_flag can be a, all --> all the known Images m, mine --> the Images belonging to the user in ONE_AUTH - and all the Public Images + g, group --> 'mine' plus the Images belonging to the groups + the user is member of uid --> Images of the user identified by this uid user --> Images of the user identified by the username @@ -282,6 +302,8 @@ def get_user_flags when "a", "all" ops[:filter_user]="-2" when "m", "mine" + ops[:filter_user]="-3" + when "g", "group" ops[:filter_user]="-1" else if !ARGV[0].match(/^[0123456789]+$/) @@ -333,29 +355,28 @@ when "register", "create", "add" puts "ID: " + image.id.to_s if ops[:verbose] end - -when "update", "addattr" - check_parameters("update", 3) +when "update" + check_parameters("update", 1) image_id=get_image_id(ARGV[0]) image=OpenNebula::Image.new_with_id(image_id, get_one_client) - - result=image.update(ARGV[1],ARGV[2]) + rc = image.info if is_successful?(result) - puts "Modified image" if ops[:verbose] + file = File.open('/tmp/template', "w") + file << image.template_str + file.close + + system "vim /tmp/template" + str = File.read('/tmp/test') + + result = image.update( str ) + + if is_successful?(result) + puts "Modified image" if ops[:verbose] + end + end -when "rmattr" - check_parameters("rmattr", 2) - image_id=get_image_id(ARGV[0]) - - image=OpenNebula::Image.new_with_id(image_id, get_one_client) - - result=image.remove_attr(ARGV[1]) - if is_successful?(result) - puts "Removed image atrribute" if ops[:verbose] - end - when "enable" check_parameters("enable", 1) image_id=get_image_id(ARGV[0]) @@ -421,7 +442,35 @@ when "nonpersistent" if is_successful?(result) puts "Image made nonpersistent" if ops[:verbose] end - + +when "chown" + check_parameters("chown", 2) + + image_id = get_image_id(ARGV[0]) + new_uid = ARGV[1].to_i + new_gid = ( ARGV.length > 2 ) ? ARGV[2].to_i : -1 + + image = OpenNebula::Image.new_with_id(image_id, get_one_client) + + result = image.chown( new_uid, new_gid ) + if is_successful?(result) + puts "Image user/group changed" if ops[:verbose] + end + +when "chgrp" + check_parameters("chgrp", 2) + + image_id = get_image_id(ARGV[0]) + new_uid = -1 + new_gid = ARGV[1].to_i + + image = OpenNebula::Image.new_with_id(image_id, get_one_client) + + result = image.chown( new_uid, new_gid ) + if is_successful?(result) + puts "Image group changed" if ops[:verbose] + end + when "list" ops.merge!(get_user_flags) if !ops[:xml] diff --git a/src/cli/onetemplate b/src/cli/onetemplate index 890b5fb77a..c9e5121607 100755 --- a/src/cli/onetemplate +++ b/src/cli/onetemplate @@ -44,7 +44,23 @@ ShowTableTemplate={ :desc => "Name of the owner", :size => 8, :proc => lambda {|d,e| - d["USERNAME"] + "TODO" + } + }, + :uid=> { + :name => "UID", + :desc => "Id of the owner", + :size => 4, + :proc => lambda {|d,e| + d["UID"] + } + }, + :gid=> { + :name => "GID", + :desc => "Id of the group", + :size => 4, + :proc => lambda {|d,e| + d.gid } }, :name => { @@ -164,14 +180,11 @@ Commands: file is a file name where the Template description is located -* addattr (Add a new Template attribute) - onetemplate addattr +* instantiate (Creates a VM instance from a Template) + onetemplate instantiate -* update (Modifies a Template attribute) - onetemplate update - -* rmattr (Deletes a Template attribute) - onetemplate rmattr +* update (Lets the user edit and replace the Template contents) + onetemplate update * publish (Publish a Template) onetemplate publish @@ -179,13 +192,20 @@ Commands: * unpublish (Unpublish an Template) onetemplate unpublish +* chown (Changes the Template owner and group) + onetemplate chown [] + +* chgrp (Changes the Template group) + onetemplate chgrp + * list (Shows Templates in the pool) onetemplate list 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 + g, group --> 'mine' plus the Templates belonging to the groups + the user is member of uid --> Templates of the user identified by this uid user --> Templates of the user identified by the username @@ -222,6 +242,8 @@ def get_user_flags when "a", "all" ops[:filter_user]="-2" when "m", "mine" + ops[:filter_user]="-3" + when "g", "group" ops[:filter_user]="-1" else if !ARGV[0].match(/^[0123456789]+$/) @@ -274,27 +296,19 @@ when "create", "register", "add" exit 0 end -when "update", "addattr" - check_parameters("update", 3) +when "instantiate" + check_parameters("instantiate", 1) 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]) + result = template.instantiate if is_successful?(result) - puts "Modified template" if ops[:verbose] + puts "Template instantiated." 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 "update" + puts "TODO" when "publish" check_parameters("publish", 1) @@ -318,6 +332,34 @@ when "unpublish" puts "Template unpublished" if ops[:verbose] end +when "chown" + check_parameters("chown", 2) + + obj_id = get_template_id(ARGV[0]) + new_uid = ARGV[1].to_i + new_gid = ( ARGV.length > 2 ) ? ARGV[2].to_i : -1 + + obj = OpenNebula::Template.new_with_id(obj_id, get_one_client) + + result = obj.chown( new_uid, new_gid ) + if is_successful?(result) + puts "Template user/group changed" if ops[:verbose] + end + +when "chgrp" + check_parameters("chgrp", 2) + + obj_id = get_template_id(ARGV[0]) + new_uid = -1 + new_gid = ARGV[1].to_i + + obj = OpenNebula::Template.new_with_id(obj_id, get_one_client) + + result = obj.chown( new_uid, new_gid ) + if is_successful?(result) + puts "Template group changed" if ops[:verbose] + end + when "list" ops.merge!(get_user_flags) if !ops[:xml] diff --git a/src/cli/oneuser b/src/cli/oneuser index 305cc276ce..0c120e488b 100755 --- a/src/cli/oneuser +++ b/src/cli/oneuser @@ -39,6 +39,14 @@ ShowTableUP={ :size => 4, :proc => lambda {|d,e| d.id } }, + :gid=> { + :name => "GID", + :desc => "Id of the group", + :size => 4, + :proc => lambda {|d,e| + d.gid + } + }, :user => { :name => "USER", :desc => "name of the user", @@ -54,7 +62,7 @@ ShowTableUP={ :proc => lambda {|d,e| d['PASSWORD'] } }, - :default => [:id, :user, :password] + :default => [:id, :gid, :user, :password] } class UPShow @@ -116,6 +124,14 @@ Commands: * passwd (Changes the given user's password) oneuser passwd password +* chgrp (Changes the User group) + oneuser chgrp + +* addgroup (Adds a secondary group) + oneuser addgroup + +* delgroup (Deletes a secondary group. Fails if the group is the main one) + oneuser delgroup Information Columns: @@ -257,6 +273,46 @@ when "passwd" puts end +when "chgrp" + check_parameters("chgrp", 2) + + obj_id = get_user_id(ARGV[0]) + new_gid = ARGV[1].to_i + + obj = OpenNebula::User.new_with_id(obj_id, get_one_client) + + result = obj.chgrp( new_gid ) + if is_successful?(result) + puts "User group changed" if ops[:verbose] + end + +when "addgroup" + check_parameters("addgroup", 2) + + obj_id = get_user_id(ARGV[0]) + new_gid = ARGV[1].to_i + + obj = OpenNebula::User.new_with_id(obj_id, get_one_client) + + result = obj.addgroup( new_gid ) + if is_successful?(result) + puts "User group added" if ops[:verbose] + end + +when "delgroup" + check_parameters("delgroup", 2) + + obj_id = get_user_id(ARGV[0]) + new_gid = ARGV[1].to_i + + obj = OpenNebula::User.new_with_id(obj_id, get_one_client) + + result = obj.delgroup( new_gid ) + if is_successful?(result) + puts "User group deleted" if ops[:verbose] + end + + when "list" if !ops[:xml] uplist=UPShow.new diff --git a/src/cli/onevm b/src/cli/onevm index d4f31105a1..1628b9bf20 100755 --- a/src/cli/onevm +++ b/src/cli/onevm @@ -39,6 +39,22 @@ ShowTableVM={ :size => 5, :proc => lambda {|d,e| d.id } }, + :uid=> { + :name => "UID", + :desc => "Id of the owner", + :size => 4, + :proc => lambda {|d,e| + d["UID"] + } + }, + :gid=> { + :name => "GID", + :desc => "Id of the group", + :size => 4, + :proc => lambda {|d,e| + d.gid + } + }, :name => { :name => "NAME", :desc => "Name of the domain", @@ -52,7 +68,7 @@ ShowTableVM={ :desc => "Name of the owner", :size => 8, :proc => lambda {|d,e| - d["USERNAME"] + "TODO" } }, :stat => { @@ -318,15 +334,9 @@ machine with the functionality present in onevm. Commands: * create (Submits a new virtual machine, adding it to the ONE VM pool) - onevm create [OPTION] {, , } + onevm create [OPTION] is a file name where the VM description is located. - is the numeric ID of a registered template (using onetemplate) - 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 @@ -400,13 +410,22 @@ Commands: States: ANY, except SUSPENDED or DONE +* chown (Changes the VM owner and group) + onevm chown [] + +* chgrp (Changes the VM group) + onevm chgrp + * list (Shows VMs in the pool) onevm list - where filter_flag can be - a, all --> all the known VMs - m, mine --> the VMs belonging to the user in ONE_AUTH - uid --> VMs of the user identified by this uid - user --> VMs of the user identified by the username + + where filter_flag can be + a, all --> all the known VMs + m, mine --> the VMs belonging to the user in ONE_AUTH + g, group --> 'mine' plus the VMs belonging to the groups + the user is member of + uid --> VMs of the user identified by this uid + user --> VMs of the user identified by the username * show (Gets information about a specific VM) onevm show @@ -483,6 +502,8 @@ def get_user_flags when "a", "all" ops[:filter_user]="-2" when "m", "mine" + ops[:filter_user]="-3" + when "g", "group" ops[:filter_user]="-1" else if !ARGV[0].match(/^[0123456789]+$/) @@ -512,32 +533,12 @@ when "submit", "create" check_parameters("create", 1) vm=OpenNebula::VirtualMachine.new( OpenNebula::VirtualMachine.build_xml, get_one_client) - - 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 + begin + template=File.read(ARGV[0]) + result=vm.allocate(template) + rescue + result=OpenNebula::Error.new("Can not read template: #{ARGV[0]}") end - - if( success ) - result = vm.allocate(template) - end - if is_successful?(result) puts "ID: " + vm.id.to_s if ops[:verbose] exit 0 @@ -749,6 +750,34 @@ when "resubmit" end end +when "chown" + check_parameters("chown", 2) + + obj_id = get_vm_id(ARGV[0]) + new_uid = ARGV[1].to_i + new_gid = ( ARGV.length > 2 ) ? ARGV[2].to_i : -1 + + obj = OpenNebula::VirtualMachine.new_with_id(obj_id, get_one_client) + + result = obj.chown( new_uid, new_gid ) + if is_successful?(result) + puts "VM user/group changed" if ops[:verbose] + end + +when "chgrp" + check_parameters("chgrp", 2) + + obj_id = get_vm_id(ARGV[0]) + new_uid = -1 + new_gid = ARGV[1].to_i + + obj = OpenNebula::VirtualMachine.new_with_id(obj_id, get_one_client) + + result = obj.chown( new_uid, new_gid ) + if is_successful?(result) + puts "VM group changed" if ops[:verbose] + end + when "list" ops.merge!(get_user_flags) if !ops[:xml] diff --git a/src/cli/onevnet b/src/cli/onevnet index 48682d624b..4582b62d98 100755 --- a/src/cli/onevnet +++ b/src/cli/onevnet @@ -51,7 +51,23 @@ ShowTableVN={ :desc => "Username of the virtual network owner", :size => 8, :left => true, - :proc => lambda {|d,e| d["USERNAME"] } + :proc => lambda {|d,e| "TODO" } + }, + :uid=> { + :name => "UID", + :desc => "Id of the owner", + :size => 4, + :proc => lambda {|d,e| + d["UID"] + } + }, + :gid=> { + :name => "GID", + :desc => "Id of the group", + :size => 4, + :proc => lambda {|d,e| + d.gid + } }, :type => { :name => "TYPE", @@ -170,15 +186,22 @@ Commands: * rmleases (Removes a lease fom the virtual network) onevnet rmleases +* chown (Changes the virtual network owner and group) + onevnet chown [] + +* chgrp (Changes the virtual network group) + onevnet chgrp + * list (Lists virtual networks in the pool) onevnet list - where filter_flag can be - a, all : all the known VNs - m, mine : the VNs belonging to the user in ONE_AUTH - and all the Public VNs - uid : VNs of the user identified by this uid - user : VNs of the user identified by the username - + + where filter_flag can be + a, all --> all the known VNets + m, mine --> the VNets belonging to the user in ONE_AUTH + g, group --> 'mine' plus the VNets belonging to the groups + the user is member of + uid --> VNets of the user identified by this uid + user --> VNets of the user identified by the username Information columns: @@ -325,12 +348,42 @@ when "rmleases" puts "Leases removed" if ops[:verbose] end +when "chown" + check_parameters("chown", 2) + + obj_id = get_vn_id(ARGV[0]) + new_uid = ARGV[1].to_i + new_gid = ( ARGV.length > 2 ) ? ARGV[2].to_i : -1 + + obj = OpenNebula::VirtualNetwork.new_with_id(obj_id, get_one_client) + + result = obj.chown( new_uid, new_gid ) + if is_successful?(result) + puts "Virtual Network user/group changed" if ops[:verbose] + end + +when "chgrp" + check_parameters("chgrp", 2) + + obj_id = get_vn_id(ARGV[0]) + new_uid = -1 + new_gid = ARGV[1].to_i + + obj = OpenNebula::VirtualNetwork.new_with_id(obj_id, get_one_client) + + result = obj.chown( new_uid, new_gid ) + if is_successful?(result) + puts "Virtual Network group changed" if ops[:verbose] + end + when "list" if ARGV[0] case ARGV[0] when "a", "all" filter_flag="-2" when "m", "mine" + filter_flag="-3" + when "g", "group" filter_flag="-1" else if !ARGV[0].match(/^[0123456789]+$/) diff --git a/src/cluster/ClusterPool.cc b/src/cluster/ClusterPool.cc deleted file mode 100644 index ef1280e8ef..0000000000 --- a/src/cluster/ClusterPool.cc +++ /dev/null @@ -1,150 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ -/* */ -/* Licensed under the Apache License, Version 2.0 (the "License"); you may */ -/* not use this file except in compliance with the License. You may obtain */ -/* a copy of the License at */ -/* */ -/* http://www.apache.org/licenses/LICENSE-2.0 */ -/* */ -/* Unless required by applicable law or agreed to in writing, software */ -/* distributed under the License is distributed on an "AS IS" BASIS, */ -/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ -/* See the License for the specific language governing permissions and */ -/* limitations under the License. */ -/* -------------------------------------------------------------------------- */ - -#include "ClusterPool.h" -#include "Nebula.h" -#include "NebulaLog.h" - -#include - -const string ClusterPool::DEFAULT_CLUSTER_NAME = "default"; - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -ClusterPool::ClusterPool(SqlDB * db):PoolSQL(db, Cluster::table) -{ - // lastOID is set in PoolSQL::init_cb - if (get_lastOID() == -1) - { - int rc; - Cluster * cluster; - string error_str; - - // Build a new Cluster object - cluster = new Cluster(0, ClusterPool::DEFAULT_CLUSTER_NAME); - - // Insert the Object in the pool - rc = PoolSQL::allocate(cluster, error_str); - - if(rc != 0) - { - ostringstream oss; - - oss << "Error trying to create default cluster: " << error_str; - NebulaLog::log("CLUSTER",Log::ERROR,oss); - - throw runtime_error(oss.str()); - } - } -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -int ClusterPool::allocate(int * oid, string name, string& error_str) -{ - Cluster * cluster; - ostringstream oss; - - if ( name.empty() ) - { - goto error_name; - } - - // Check for duplicates - cluster = get(name, false); - - if( cluster != 0 ) - { - goto error_duplicated; - } - - // Build a new Cluster object - cluster = new Cluster(-1, name); - - // Insert the Object in the pool - *oid = PoolSQL::allocate(cluster, error_str); - - return *oid; - - -error_name: - oss << "NAME cannot be empty."; - goto error_common; - -error_duplicated: - oss << "NAME is already taken by CLUSTER " << cluster->get_oid() << "."; - -error_common: - *oid = -1; - error_str = oss.str(); - - return *oid; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -int ClusterPool::drop(Cluster * cluster) -{ - int rc; - - Host* host; - vector hids; - vector::iterator hid_it; - - Nebula& nd = Nebula::instance(); - HostPool * hpool = nd.get_hpool(); - - string cluster_name = cluster->get_name(); - string where = "cluster = '" + cluster_name + "'"; - - // Return error if cluster is 'default' - if( cluster->get_oid() == 0 ) - { - NebulaLog::log("CLUSTER",Log::WARNING, - "Default cluster cannot be deleted."); - - return -1; - } - - rc = cluster->drop(db); - - // Move the hosts assigned to the deleted cluster to the default one - if( rc == 0 ) - { - hpool->search(hids, where); - - for ( hid_it=hids.begin() ; hid_it < hids.end(); hid_it++ ) - { - host = hpool->get(*hid_it, true); - - if ( host == 0 ) - { - continue; - } - - set_default_cluster(host); - - hpool->update(host); - - host->unlock(); - } - } - - return rc; -} diff --git a/src/cluster/test/ClusterPoolTest.cc b/src/cluster/test/ClusterPoolTest.cc deleted file mode 100644 index bdb102dd05..0000000000 --- a/src/cluster/test/ClusterPoolTest.cc +++ /dev/null @@ -1,415 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ -/* */ -/* Licensed under the Apache License, Version 2.0 (the "License"); you may */ -/* not use this file except in compliance with the License. You may obtain */ -/* a copy of the License at */ -/* */ -/* http://www.apache.org/licenses/LICENSE-2.0 */ -/* */ -/* Unless required by applicable law or agreed to in writing, software */ -/* distributed under the License is distributed on an "AS IS" BASIS, */ -/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ -/* See the License for the specific language governing permissions and */ -/* limitations under the License. */ -/* -------------------------------------------------------------------------- */ - -#include -#include -#include - -#include "ClusterPool.h" -#include "PoolTest.h" - -using namespace std; - -const string names[] = {"cluster_a", "Second cluster"}; - -const string xmls[] = -{ - "1cluster_a", - "2Second cluster" -}; - -const string cluster_default = - "0default"; - -const string cluster_xml_dump = - "0default1cluster_a3cluster_c4cluster_d"; - -const string host_0_cluster = - "0Host one0im_madvmm_madtm_mad0cluster_a0000000000000"; - -const string host_0_default = - "0Host one0" - "im_madvmm_madtm_mad" - "0default" - "000" - "000" - "000" - "000" - "0"; - -/* ************************************************************************* */ -/* ************************************************************************* */ - - -#include "NebulaTest.h" - -class NebulaTestCluster: public NebulaTest -{ -public: - NebulaTestCluster():NebulaTest() - { - NebulaTest::the_tester = this; - - need_host_pool = true; - need_cluster_pool= true; - } -}; - -class ClusterPoolTest : public PoolTest -{ - CPPUNIT_TEST_SUITE (ClusterPoolTest); - - // Not all tests from PoolTest can be used. Because - // of the initial default cluster added to the DB, the - // oid_assignment would fail. - CPPUNIT_TEST (get_from_cache); - CPPUNIT_TEST (get_from_db); - CPPUNIT_TEST (wrong_get); - CPPUNIT_TEST (drop_and_get); - - CPPUNIT_TEST (name_pool); - - CPPUNIT_TEST (duplicates); - CPPUNIT_TEST (set_cluster); - CPPUNIT_TEST (remove_cluster); - CPPUNIT_TEST (delete_cluster); - CPPUNIT_TEST (dump); - - CPPUNIT_TEST_SUITE_END (); - -protected: - - NebulaTestCluster * tester; - HostPool * hpool; - ClusterPool * cpool; - - - - void bootstrap(SqlDB* db) - { - // setUp overwritten - }; - - PoolSQL* create_pool(SqlDB* db) - { - // setUp overwritten - return cpool; - }; - - int allocate(int index) - { - int oid; - string err; - - return cpool->allocate(&oid, names[index], err); - }; - - void check(int index, PoolObjectSQL* obj) - { - Cluster * cluster = static_cast(obj); - - CPPUNIT_ASSERT( obj != 0 ); - - string xml_str = ""; - string name = cluster->get_name(); - - CPPUNIT_ASSERT( name == names[index] ); - - // Get the xml - cluster->to_xml(xml_str); - -// A little help for debugging -/* - if( xml_str != xmls[index] ) - { - cout << endl << xml_str << endl << "========" - << endl << xmls[index]; - } -//*/ - CPPUNIT_ASSERT( xml_str == xmls[index]); - }; - -private: - - /** - * Allocates a Host. - */ - void init_hp() - { - int oid; - string err; - - // Allocate a host - oid = hpool->allocate(&oid, "Host one","im_mad","vmm_mad", "tm_mad", err); - CPPUNIT_ASSERT(oid == 0); - - hpool->clean(); - }; - -public: - ClusterPoolTest() - { - xmlInitParser(); - }; - - ~ClusterPoolTest() - { - xmlCleanupParser(); - }; - - void setUp() - { - create_db(); - - tester = new NebulaTestCluster(); - - Nebula& neb = Nebula::instance(); - neb.start(); - - hpool = neb.get_hpool(); - cpool = neb.get_cpool(); - - pool = cpool; - }; - - void tearDown() - { - delete_db(); - - delete tester; - }; - - /* ********************************************************************* */ - /* ********************************************************************* */ - - // Test intended to check the PoolSQL name index functionallity - void name_pool() - { - Cluster * cluster; - int oid; - string err; - - - // Allocate some clusters - cpool->allocate(&oid, "name_1", err); - CPPUNIT_ASSERT( oid == 1 ); - - cpool->allocate(&oid, "name_2", err); - CPPUNIT_ASSERT( oid == 2 ); - - cpool->allocate(&oid, "name_3", err); - CPPUNIT_ASSERT( oid == 3 ); - - // Clean the cache - cpool->clean(); - - cpool->allocate(&oid, "name_4", err); - CPPUNIT_ASSERT( oid == 4 ); - - cpool->allocate(&oid, "name_5", err); - CPPUNIT_ASSERT( oid == 5 ); - - // Cluster names 0-3 should be unknown, and 4-5 cached - // Ask for a cached object - cluster = cpool->get("name_5", false); - CPPUNIT_ASSERT( cluster != 0 ); - CPPUNIT_ASSERT( cluster->get_oid() == 5 ); - CPPUNIT_ASSERT( cluster->get_name() == "name_5" ); - - // Ask for non-cached object - cluster = cpool->get("name_2", false); - CPPUNIT_ASSERT( cluster != 0 ); - CPPUNIT_ASSERT( cluster->get_oid() == 2 ); - CPPUNIT_ASSERT( cluster->get_name() == "name_2" ); - - // Ask for non-existing object - cluster = cpool->get("name_X", false); - CPPUNIT_ASSERT( cluster == 0 ); - }; - - /* ********************************************************************* */ - - void duplicates() - { - int rc, oid; - string err; - - // Allocate a cluster. - rc = cpool->allocate(&oid, names[1], err); - CPPUNIT_ASSERT( oid == 1 ); - CPPUNIT_ASSERT( oid == rc ); - - // Try to allocate twice the same cluster, should fail - rc = cpool->allocate(&oid, names[1], err); - CPPUNIT_ASSERT( rc == -1 ); - CPPUNIT_ASSERT( oid == rc ); - } - - /* ********************************************************************* */ - - void set_cluster() - { - Host* host; - int rc; - string xml_str, err; - - init_hp(); - - host = hpool->get(0, false); - CPPUNIT_ASSERT(host != 0); - - rc = host->set_cluster("cluster_a"); - CPPUNIT_ASSERT( rc == 0 ); - - hpool->update(host); - - host->to_xml(xml_str); - CPPUNIT_ASSERT( xml_str == host_0_cluster); - } - - /* ********************************************************************* */ - - void remove_cluster() - { - Host* host; - - int rc; - string xml_str; - - init_hp(); - - host = hpool->get(0, false); - CPPUNIT_ASSERT(host != 0); - - // Set cluster - rc = host->set_cluster("cluster_a"); - CPPUNIT_ASSERT( rc == 0 ); - - hpool->update(host); - - host->to_xml(xml_str); - CPPUNIT_ASSERT( xml_str == host_0_cluster); - - // Remove from the cluster - rc = cpool->set_default_cluster(host); - CPPUNIT_ASSERT( rc == 0 ); - - hpool->update(host); - - // The host should have been moved to the default cluster - - host = hpool->get(0, false); - CPPUNIT_ASSERT(host != 0); - - host->to_xml(xml_str); - CPPUNIT_ASSERT( xml_str == host_0_default); - } - - /* ********************************************************************* */ - - void delete_cluster() - { - Host * host; - Cluster * cluster; - - int rc, oid; - string xml_str; - - init_hp(); - host = hpool->get(0, false); - CPPUNIT_ASSERT(host != 0); - - // Allocate a cluster - oid = allocate(0); - CPPUNIT_ASSERT(oid == 1); - - cluster = cpool->get(1, false); - - // Set cluster - rc = host->set_cluster(cluster->get_name()); - CPPUNIT_ASSERT( rc == 0 ); - - hpool->update(host); - - host->to_xml(xml_str); - CPPUNIT_ASSERT( xml_str == host_0_cluster); - - // Delete the cluster - rc = cpool->drop(cluster); - CPPUNIT_ASSERT( rc == 0 ); - - // The host should have been moved to the default cluster - host = hpool->get(0, false); - host->to_xml(xml_str); -/* - if( xml_str != host_0_default ) - { - cout << endl << xml_str << endl << "========" - << endl << host_0_default; - } -//*/ - CPPUNIT_ASSERT( xml_str == host_0_default); - } - - /* ********************************************************************* */ - - void dump() - { - Cluster * cluster; - int oid, rc; - ostringstream oss; - string err; - - // Allocate some clusters - rc = cpool->allocate(&oid, "cluster_a", err); - CPPUNIT_ASSERT( rc == 1 ); - - rc = cpool->allocate(&oid, "cluster_b", err); - CPPUNIT_ASSERT( rc == 2 ); - - rc = cpool->allocate(&oid, "cluster_c", err); - CPPUNIT_ASSERT( rc == 3 ); - - rc = cpool->allocate(&oid, "cluster_d", err); - CPPUNIT_ASSERT( rc == 4 ); - - // Drop one of them - cluster = cpool->get(2, false); - CPPUNIT_ASSERT( cluster != 0 ); - - rc = cpool->drop(cluster); - CPPUNIT_ASSERT( rc == 0 ); - - // dump the pool - rc = cpool->dump(oss,""); -/* - if( oss.str() != cluster_xml_dump ) - { - cout << endl << oss.str() << endl << "========" - << endl << cluster_xml_dump; - } -//*/ - CPPUNIT_ASSERT( oss.str() == cluster_xml_dump ); - } -}; - -/* ************************************************************************* */ -/* ************************************************************************* */ - -int main(int argc, char ** argv) -{ - return PoolTest::main(argc, argv, ClusterPoolTest::suite()); -} diff --git a/src/cluster/Cluster.cc b/src/group/Group.cc similarity index 61% rename from src/cluster/Cluster.cc rename to src/group/Group.cc index 185604d78f..3b710bc7d6 100644 --- a/src/cluster/Cluster.cc +++ b/src/group/Group.cc @@ -20,62 +20,21 @@ #include #include -#include "Cluster.h" +#include "Group.h" +const char * Group::table = "group_pool"; -const char * Cluster::table = "cluster_pool"; - -const char * Cluster::db_names = "oid, name, body"; - -const char * Cluster::db_bootstrap = "CREATE TABLE IF NOT EXISTS cluster_pool (" - "oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, UNIQUE(name))"; +const char * Group::db_names = "oid, name, body"; +const char * Group::db_bootstrap = "CREATE TABLE IF NOT EXISTS group_pool (" + "oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, " + "UNIQUE(name))"; /* ************************************************************************ */ -/* Cluster :: Constructor/Destructor */ +/* Group :: Database Access Functions */ /* ************************************************************************ */ -Cluster::Cluster(int id, const string& name):PoolObjectSQL(id,name,-1,table){}; - -Cluster::~Cluster(){}; - -/* ************************************************************************ */ -/* Cluster :: Database Access Functions */ -/* ************************************************************************ */ - -/* ------------------------------------------------------------------------ */ -/* ------------------------------------------------------------------------ */ - -int Cluster::insert(SqlDB *db, string& error_str) -{ - int rc; - - rc = insert_replace(db, false); - - if ( rc != 0 ) - { - error_str = "Error inserting Cluster in DB."; - } - - return rc; -} - -/* ------------------------------------------------------------------------ */ -/* ------------------------------------------------------------------------ */ - -int Cluster::update(SqlDB *db) -{ - int rc; - - rc = insert_replace(db, true); - - return rc; -} - -/* ------------------------------------------------------------------------ */ -/* ------------------------------------------------------------------------ */ - -int Cluster::insert_replace(SqlDB *db, bool replace) +int Group::insert_replace(SqlDB *db, bool replace) { ostringstream oss; @@ -85,7 +44,7 @@ int Cluster::insert_replace(SqlDB *db, bool replace) char * sql_name; char * sql_xml; - // Update the Cluster + // Update the Group sql_name = db->escape_str(name.c_str()); @@ -101,7 +60,7 @@ int Cluster::insert_replace(SqlDB *db, bool replace) goto error_body; } - if(replace) + if ( replace ) { oss << "REPLACE"; } @@ -130,31 +89,22 @@ error_name: return -1; } -/* ************************************************************************ */ -/* Cluster :: Misc */ -/* ************************************************************************ */ - -ostream& operator<<(ostream& os, Cluster& cluster) -{ - string cluster_str; - - os << cluster.to_xml(cluster_str); - - return os; -} - /* ------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------ */ -string& Cluster::to_xml(string& xml) const +string& Group::to_xml(string& xml) const { ostringstream oss; + string collection_xml; + + ObjectCollection::to_xml(collection_xml); oss << - "" << + "" << "" << oid << "" << "" << name << "" << - ""; + collection_xml << + ""; xml = oss.str(); @@ -164,16 +114,28 @@ string& Cluster::to_xml(string& xml) const /* ------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------ */ -int Cluster::from_xml(const string& xml) +int Group::from_xml(const string& xml) { int rc = 0; + vector content; // Initialize the internal XML object update_from_str(xml); // Get class base attributes - rc += xpath(oid, "/CLUSTER/ID", -1); - rc += xpath(name,"/CLUSTER/NAME", "not_found"); + rc += xpath(oid, "/GROUP/ID", -1); + rc += xpath(name,"/GROUP/NAME", "not_found"); + + // Get associated classes + ObjectXML::get_nodes("/GROUP/USERS", content); + + if( content.size() < 1 ) + { + return -1; + } + + // Set of IDs + rc += ObjectCollection::from_xml_node(content[0]); if (rc != 0) { @@ -182,3 +144,7 @@ int Cluster::from_xml(const string& xml) return 0; } + +/* ------------------------------------------------------------------------ */ +/* ------------------------------------------------------------------------ */ + diff --git a/src/group/GroupPool.cc b/src/group/GroupPool.cc new file mode 100644 index 0000000000..0cf7670d49 --- /dev/null +++ b/src/group/GroupPool.cc @@ -0,0 +1,160 @@ +/* -------------------------------------------------------------------------- */ +/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ +/* */ +/* Licensed under the Apache License, Version 2.0 (the "License"); you may */ +/* not use this file except in compliance with the License. You may obtain */ +/* a copy of the License at */ +/* */ +/* http://www.apache.org/licenses/LICENSE-2.0 */ +/* */ +/* Unless required by applicable law or agreed to in writing, software */ +/* distributed under the License is distributed on an "AS IS" BASIS, */ +/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ +/* See the License for the specific language governing permissions and */ +/* limitations under the License. */ +/* -------------------------------------------------------------------------- */ + +#include "GroupPool.h" +#include "Nebula.h" +#include "NebulaLog.h" + +#include + +/* -------------------------------------------------------------------------- */ +/* There are two default groups boostrapped by the core: */ +/* - oneadmin can not be removed */ +/* - users to place regular users by default */ +/* The first 100 group IDs are reserved for system groups. Regular ones start */ +/* from ID 100 */ +/* -------------------------------------------------------------------------- */ + +const string GroupPool::ONEADMIN_NAME = "oneadmin"; +const int GroupPool::ONEADMIN_ID = 0; + +const string GroupPool::USERS_NAME = "users"; +const int GroupPool::USERS_ID = 1; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +GroupPool::GroupPool(SqlDB * db):PoolSQL(db, Group::table) +{ + ostringstream oss; + string error_str; + + if (get_lastOID() == -1) //lastOID is set in PoolSQL::init_cb + { + int rc; + Group * group; + + // Build the default oneadmins & users group + group = new Group(ONEADMIN_ID, ONEADMIN_NAME); + + rc = PoolSQL::allocate(group, error_str); + + if( rc < 0 ) + { + goto error_groups; + } + + group = new Group(USERS_ID, USERS_NAME); + + rc = PoolSQL::allocate(group, error_str); + + if(rc < 0) + { + goto error_groups; + } + + set_update_lastOID(99); + } + + return; + +error_groups: + oss << "Error trying to create default group: " << error_str; + NebulaLog::log("GROUP",Log::ERROR,oss); + + throw runtime_error(oss.str()); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int GroupPool::allocate(string name, int * oid, string& error_str) +{ + Group * group; + ostringstream oss; + + if ( name.empty() ) + { + goto error_name; + } + + // Check for duplicates + group = get(name, false); + + if( group != 0 ) + { + goto error_duplicated; + } + + // Build a new Group object + group = new Group(-1, name); + + // Insert the Object in the pool + *oid = PoolSQL::allocate(group, error_str); + + return *oid; + +error_name: + oss << "NAME cannot be empty."; + goto error_common; + +error_duplicated: + oss << "NAME is already taken by GROUP " << group->get_oid() << "."; + +error_common: + *oid = -1; + error_str = oss.str(); + + return *oid; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int GroupPool::drop(PoolObjectSQL * objsql, string& error_msg) +{ + Group * group = static_cast(objsql); + + int rc; + + // Return error if the group is a default one. + if( group->get_oid() < 100 ) + { + error_msg = "System Groups (ID < 100) cannot be deleted."; + NebulaLog::log("GROUP", Log::ERROR, error_msg); + return -2; + } + + if( group->get_collection_size() > 0 ) + { + ostringstream oss; + oss << "Group " << group->get_oid() << " is not empty."; + error_msg = oss.str(); + NebulaLog::log("GROUP", Log::ERROR, error_msg); + + return -3; + } + + rc = group->drop(db); + + if( rc != 0 ) + { + error_msg = "SQL DB error"; + rc = -1; + } + + return rc; +} diff --git a/src/cluster/SConstruct b/src/group/SConstruct similarity index 93% rename from src/cluster/SConstruct rename to src/group/SConstruct index 9112f8fbba..d9a3e06b8a 100644 --- a/src/cluster/SConstruct +++ b/src/group/SConstruct @@ -1,4 +1,4 @@ -# SConstruct for src/cluster +# SConstruct for src/group # -------------------------------------------------------------------------- # # Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) # @@ -18,12 +18,12 @@ Import('env') -lib_name='nebula_cluster' +lib_name='nebula_group' # Sources to generate the library source_files=[ - 'ClusterPool.cc', - 'Cluster.cc' + 'GroupPool.cc', + 'Group.cc' ] # Build library diff --git a/src/group/test/GroupPoolTest.cc b/src/group/test/GroupPoolTest.cc new file mode 100644 index 0000000000..7731a636d4 --- /dev/null +++ b/src/group/test/GroupPoolTest.cc @@ -0,0 +1,233 @@ +/* -------------------------------------------------------------------------- */ +/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ +/* */ +/* Licensed under the Apache License, Version 2.0 (the "License"); you may */ +/* not use this file except in compliance with the License. You may obtain */ +/* a copy of the License at */ +/* */ +/* http://www.apache.org/licenses/LICENSE-2.0 */ +/* */ +/* Unless required by applicable law or agreed to in writing, software */ +/* distributed under the License is distributed on an "AS IS" BASIS, */ +/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ +/* See the License for the specific language governing permissions and */ +/* limitations under the License. */ +/* -------------------------------------------------------------------------- */ + +#include +#include +#include + +#include "GroupPool.h" +#include "PoolTest.h" + +using namespace std; + +const int uids[] = {0,1,2}; +const string names[] = {"First name", "Second name"}; + +const string xmls[] = +{ + "100First name", + "101Second name" +}; + +const string group_xml_dump = + "0oneadmin1users100group_a102group_c103group_d"; + +/* ************************************************************************* */ +/* ************************************************************************* */ + + +#include "NebulaTest.h" + +class NebulaTestGroup: public NebulaTest +{ +public: + NebulaTestGroup():NebulaTest() + { + NebulaTest::the_tester = this; + + need_group_pool= true; + } +}; + +class GroupPoolTest : public PoolTest +{ + CPPUNIT_TEST_SUITE (GroupPoolTest); + + // Not all tests from PoolTest can be used. Because + // of the initial default groups added to the DB, the + // oid_assignment would fail. + CPPUNIT_TEST (get_from_cache); + CPPUNIT_TEST (get_from_db); + CPPUNIT_TEST (wrong_get); + CPPUNIT_TEST (drop_and_get); + + CPPUNIT_TEST (duplicates); + CPPUNIT_TEST (dump); + + CPPUNIT_TEST_SUITE_END (); + +protected: + + NebulaTestGroup * tester; + GroupPool * gpool; + + + + void bootstrap(SqlDB* db) + { + // setUp overwritten + }; + + PoolSQL* create_pool(SqlDB* db) + { + // setUp overwritten + return gpool; + }; + + int allocate(int index) + { + int oid; + string err; + + return gpool->allocate(names[index], &oid, err); + }; + + void check(int index, PoolObjectSQL* obj) + { + Group * group = static_cast(obj); + + CPPUNIT_ASSERT( obj != 0 ); + + string xml_str = ""; + string name = group->get_name(); + + CPPUNIT_ASSERT( name == names[index] ); + + // Get the xml + group->to_xml(xml_str); + +// A little help for debugging +/* + if( xml_str != xmls[index] ) + { + cout << endl << xml_str << endl << "========" + << endl << xmls[index]; + } +//*/ + CPPUNIT_ASSERT( xml_str == xmls[index]); + }; + +private: + + +public: + GroupPoolTest() + { + xmlInitParser(); + }; + + ~GroupPoolTest() + { + xmlCleanupParser(); + }; + + void setUp() + { + create_db(); + + tester = new NebulaTestGroup(); + + Nebula& neb = Nebula::instance(); + neb.start(); + + gpool = neb.get_gpool(); + + pool = gpool; + }; + + void tearDown() + { + delete_db(); + + delete tester; + }; + + /* ********************************************************************* */ + /* ********************************************************************* */ + + void duplicates() + { + int rc, oid; + string err; + GroupPool * gpool = static_cast(pool); + + // Allocate a group + rc = gpool->allocate(names[0], &oid, err); + CPPUNIT_ASSERT( oid == 100 ); + CPPUNIT_ASSERT( oid == rc ); + + // Try to allocate twice the same group, should fail + rc = gpool->allocate(names[0], &oid, err); + CPPUNIT_ASSERT( rc == -1 ); + CPPUNIT_ASSERT( oid == rc ); + + // Try again, this time with different uid. Should fail, groups can't + // repeat names + rc = gpool->allocate(names[0], &oid, err); + CPPUNIT_ASSERT( rc == -1 ); + CPPUNIT_ASSERT( oid == rc ); + } + + /* ********************************************************************* */ + + void dump() + { + Group * group; + int oid, rc; + ostringstream oss; + string err; + + // Allocate some groups + rc = gpool->allocate("group_a", &oid, err); + CPPUNIT_ASSERT( rc == 100 ); + + rc = gpool->allocate("group_b", &oid, err); + CPPUNIT_ASSERT( rc == 101 ); + + rc = gpool->allocate("group_c", &oid, err); + CPPUNIT_ASSERT( rc == 102 ); + + rc = gpool->allocate("group_d", &oid, err); + CPPUNIT_ASSERT( rc == 103 ); + + // Drop one of them + group = gpool->get(101, false); + CPPUNIT_ASSERT( group != 0 ); + + rc = gpool->drop(group, err); + CPPUNIT_ASSERT( rc == 0 ); + + // dump the pool + rc = gpool->dump(oss,""); +/* + if( oss.str() != group_xml_dump ) + { + cout << endl << oss.str() << endl << "========" + << endl << group_xml_dump; + } +//*/ + CPPUNIT_ASSERT( oss.str() == group_xml_dump ); + + } +}; + +/* ************************************************************************* */ +/* ************************************************************************* */ + +int main(int argc, char ** argv) +{ + return PoolTest::main(argc, argv, GroupPoolTest::suite()); +} diff --git a/src/cluster/test/SConstruct b/src/group/test/SConstruct similarity index 94% rename from src/cluster/test/SConstruct rename to src/group/test/SConstruct index 3f31210fa3..d7ed958024 100644 --- a/src/cluster/test/SConstruct +++ b/src/group/test/SConstruct @@ -17,7 +17,6 @@ Import('env') env.Prepend(LIBS=[ - 'nebula_cluster', 'nebula_host', 'nebula_pool', 'nebula_template', @@ -29,7 +28,6 @@ env.Prepend(LIBS=[ ### TODO: delete not needed 'nebula_core_test', 'nebula_host', - 'nebula_cluster', 'nebula_xml', 'nebula_vmm', 'nebula_im', @@ -40,6 +38,7 @@ env.Prepend(LIBS=[ 'nebula_template', 'nebula_vm', 'nebula_vmtemplate', + 'nebula_group', 'nebula_vnm', 'nebula_image', 'nebula_pool', @@ -53,4 +52,4 @@ env.Prepend(LIBS=[ 'crypto' ]) -env.Program('test','ClusterPoolTest.cc') +env.Program('test','GroupPoolTest.cc') diff --git a/src/host/Host.cc b/src/host/Host.cc index 43e1cf74c6..992f0d87d3 100644 --- a/src/host/Host.cc +++ b/src/host/Host.cc @@ -22,25 +22,24 @@ #include "Host.h" #include "NebulaLog.h" +#include "Nebula.h" /* ************************************************************************ */ /* Host :: Constructor/Destructor */ /* ************************************************************************ */ Host::Host( - int id, + int id, const string& _hostname, const string& _im_mad_name, const string& _vmm_mad_name, - const string& _tm_mad_name, - const string& _cluster): - PoolObjectSQL(id,_hostname,-1,table), + const string& _tm_mad_name): + PoolObjectSQL(id,_hostname,-1,-1,table), state(INIT), im_mad_name(_im_mad_name), vmm_mad_name(_vmm_mad_name), tm_mad_name(_tm_mad_name), - last_monitored(0), - cluster(_cluster) + last_monitored(0) { obj_template = new HostTemplate; } @@ -59,11 +58,11 @@ Host::~Host() const char * Host::table = "host_pool"; -const char * Host::db_names = "oid, name, body, state, last_mon_time, cluster"; +const char * Host::db_names = "oid, name, body, state, last_mon_time"; const char * Host::db_bootstrap = "CREATE TABLE IF NOT EXISTS host_pool (" "oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, state INTEGER, " - "last_mon_time INTEGER, cluster VARCHAR(128), UNIQUE(name))"; + "last_mon_time INTEGER, UNIQUE(name))"; /* ------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------ */ @@ -105,7 +104,6 @@ int Host::insert_replace(SqlDB *db, bool replace) string xml_body; char * sql_hostname; - char * sql_cluster; char * sql_xml; // Update the Host @@ -117,13 +115,6 @@ int Host::insert_replace(SqlDB *db, bool replace) goto error_hostname; } - sql_cluster = db->escape_str(cluster.c_str()); - - if ( sql_cluster == 0 ) - { - goto error_cluster; - } - sql_xml = db->escape_str(to_xml(xml_body).c_str()); if ( sql_xml == 0 ) @@ -147,20 +138,16 @@ int Host::insert_replace(SqlDB *db, bool replace) << "'" << sql_hostname << "'," << "'" << sql_xml << "'," << state << "," - << last_monitored << "," - << "'" << sql_cluster << "')"; + << last_monitored << ")"; rc = db->exec(oss); db->free_str(sql_hostname); - db->free_str(sql_cluster); db->free_str(sql_xml); return rc; error_body: - db->free_str(sql_cluster); -error_cluster: db->free_str(sql_hostname); error_hostname: return -1; @@ -200,18 +187,6 @@ int Host::update_info(string &parse_str) /* Host :: Misc */ /* ************************************************************************ */ -ostream& operator<<(ostream& os, Host& host) -{ - string host_str; - - os << host.to_xml(host_str); - - return os; -} - -/* ------------------------------------------------------------------------ */ -/* ------------------------------------------------------------------------ */ - string& Host::to_xml(string& xml) const { string template_xml; @@ -227,7 +202,6 @@ string& Host::to_xml(string& xml) const "" << vmm_mad_name << "" << "" << tm_mad_name << "" << "" << last_monitored << "" << - "" << cluster << "" << host_share.to_xml(share_xml) << obj_template->to_xml(template_xml) << ""; @@ -260,7 +234,6 @@ int Host::from_xml(const string& xml) rc += xpath(tm_mad_name, "/HOST/TM_MAD", "not_found"); rc += xpath(last_monitored, "/HOST/LAST_MON_TIME", 0); - rc += xpath(cluster, "/HOST/CLUSTER", "not_found"); state = static_cast( int_state ); diff --git a/src/host/HostPool.cc b/src/host/HostPool.cc index 785facd3e3..ec6edb511f 100644 --- a/src/host/HostPool.cc +++ b/src/host/HostPool.cc @@ -23,7 +23,7 @@ #include "HostPool.h" #include "HostHook.h" #include "NebulaLog.h" -#include "ClusterPool.h" +#include "GroupPool.h" /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -135,7 +135,7 @@ HostPool::HostPool(SqlDB* db, /* -------------------------------------------------------------------------- */ int HostPool::allocate ( - int * oid, + int * oid, const string& hostname, const string& im_mad_name, const string& vmm_mad_name, @@ -174,12 +174,7 @@ int HostPool::allocate ( // Build a new Host object - host = new Host(-1, - hostname, - im_mad_name, - vmm_mad_name, - tm_mad_name, - ClusterPool::DEFAULT_CLUSTER_NAME); + host = new Host(-1, hostname, im_mad_name, vmm_mad_name, tm_mad_name); // Insert the Object in the pool diff --git a/src/host/test/HostPoolTest.cc b/src/host/test/HostPoolTest.cc index e2ce49be0f..2b63af6a50 100644 --- a/src/host/test/HostPoolTest.cc +++ b/src/host/test/HostPoolTest.cc @@ -33,7 +33,7 @@ const string xmls[] = { "0Host one0" "im_madvmm_madtm_mad" - "0default" + "0" "000" "000" "000" @@ -42,7 +42,7 @@ const string xmls[] = "1Second host0" "im_madvmm_madtm_mad" - "0default" + "0" "000" "000" "000" @@ -54,34 +54,34 @@ const string xmls[] = const string xml_dump = "0a0im_madvmm_madtm_mad0" - "default00000000000000" "1a name0im_madvmm_madtm_mad0default0000000" "000000002a_name0im_madvmm_madtm_mad0defaulttm_mad000000000000003another " "name0im_madvmm_mad" - "tm_mad0defaulttm_mad000000000000004host0im_madvmm_madtm_mad" - "0default" + "0" "000" "0000" "000vmm_madtm_mad0" - "default00000000000000" "1a name0im_madvmm_madtm_mad0default0000000" "000000002a_name0im_madvmm_madtm_mad0defaulttm_mad000000000000003another " "name0im_madvmm_mad" - "tm_mad0defaulttm_mad00000000000Host one0im_madvmm_madtm_mad0default0000000000000"; - -const string cluster_default = - "0default"; - -const string cluster_xml_dump = - "0default1cluster_a3cluster_c4cluster_d"; + "0Host one0im_madvmm_madtm_mad00000000000000"; const string host_0_cluster = "0Host one0im_madvmm_madtm_mad0cluster_a0000000000000"; diff --git a/src/host/test/NebulaTestHost.h b/src/host/test/NebulaTestHost.h index 6d4be3f1f3..a390432727 100644 --- a/src/host/test/NebulaTestHost.h +++ b/src/host/test/NebulaTestHost.h @@ -29,6 +29,7 @@ public: need_vm_pool = true; need_host_pool = true; need_user_pool = true; + need_group_pool = true; need_vnet_pool = true; need_image_pool= true; @@ -82,29 +83,6 @@ public: return new HostPool(db, host_hooks, hook_location); } - - // ----------------------------------------------------------- - // Managers - // ----------------------------------------------------------- - - HookManager* create_hm(VirtualMachinePool * vmpool) - { - map mad_value; - VectorAttribute * mad; - vector hm_mads; - - ostringstream oss; - - // we need the full path (i.e, starting with '/') - // for the dummy executable - oss << getenv("PWD") << "/../../hm_mad/test/dummy"; - mad_value.insert(make_pair("EXECUTABLE",oss.str())); - - mad = new VectorAttribute("HM_MAD",mad_value); - hm_mads.push_back(mad); - - return new HookManager(hm_mads,vmpool); - } }; #endif /*NEBULA_TEST_H_*/ diff --git a/src/host/test/SConstruct b/src/host/test/SConstruct index c839508487..9f12682dc5 100644 --- a/src/host/test/SConstruct +++ b/src/host/test/SConstruct @@ -21,7 +21,6 @@ Import('env') env.Prepend(LIBS=[ 'nebula_core_test', 'nebula_host', - 'nebula_cluster', 'nebula_xml', 'nebula_vmm', 'nebula_im', @@ -32,6 +31,7 @@ env.Prepend(LIBS=[ 'nebula_template', 'nebula_vm', 'nebula_vmtemplate', + 'nebula_group', 'nebula_vnm', 'nebula_image', 'nebula_pool', diff --git a/src/image/Image.cc b/src/image/Image.cc index 58d6cda259..928d371b3c 100644 --- a/src/image/Image.cc +++ b/src/image/Image.cc @@ -34,11 +34,10 @@ /* Image :: Constructor/Destructor */ /* ************************************************************************ */ -Image::Image(int _uid, - const string& _user_name, +Image::Image(int _uid, + int _gid, ImageTemplate * _image_template): - PoolObjectSQL(-1,"",_uid,table), - user_name(_user_name), + PoolObjectSQL(-1,"",_uid,_gid,table), type(OS), regtime(time(0)), source("-"), @@ -69,11 +68,11 @@ Image::~Image() const char * Image::table = "image_pool"; -const char * Image::db_names = "oid, name, body, uid, public"; +const char * Image::db_names = "oid, name, body, uid, gid, public"; const char * Image::db_bootstrap = "CREATE TABLE IF NOT EXISTS image_pool (" "oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, uid INTEGER, " - "public INTEGER, UNIQUE(name,uid) )"; + "gid INTEGER, public INTEGER, UNIQUE(name,uid) )"; /* ------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------ */ @@ -121,7 +120,7 @@ int Image::insert(SqlDB *db, string& error_str) TO_UPPER(public_attr); - public_img = (public_attr == "YES"); + public_obj = (public_attr == "YES"); // ------------ PERSISTENT -------------------- @@ -135,7 +134,7 @@ int Image::insert(SqlDB *db, string& error_str) // An image cannot be public and persistent simultaneously - if ( public_img && persistent_img ) + if ( public_obj && persistent_img ) { goto error_public_and_persistent; } @@ -295,7 +294,8 @@ int Image::insert_replace(SqlDB *db, bool replace) << "'" << sql_name << "'," << "'" << sql_xml << "'," << uid << "," - << public_img << ")"; + << gid << "," + << public_obj << ")"; rc = db->exec(oss); @@ -314,18 +314,6 @@ error_name: /* Image :: Misc */ /* ************************************************************************ */ -ostream& operator<<(ostream& os, Image& image) -{ - string image_str; - - os << image.to_xml(image_str); - - return os; -} - -/* ------------------------------------------------------------------------ */ -/* ------------------------------------------------------------------------ */ - string& Image::to_xml(string& xml) const { string template_xml; @@ -335,10 +323,10 @@ string& Image::to_xml(string& xml) const "" << "" << oid << "" << "" << uid << "" << - "" << user_name << "" << + "" << gid << "" << "" << name << "" << "" << type << "" << - "" << public_img << "" << + "" << public_obj << "" << "" << persistent_img << "" << "" << regtime << "" << "" << source << "" << @@ -369,11 +357,11 @@ int Image::from_xml(const string& xml) // Get class base attributes rc += xpath(oid, "/IMAGE/ID", -1); rc += xpath(uid, "/IMAGE/UID", -1); - rc += xpath(user_name, "/IMAGE/USERNAME", "not_found"); + rc += xpath(gid, "/IMAGE/GID", -1); rc += xpath(name, "/IMAGE/NAME", "not_found"); rc += xpath(int_type, "/IMAGE/TYPE", 0); - rc += xpath(public_img, "/IMAGE/PUBLIC", 0); + rc += xpath(public_obj, "/IMAGE/PUBLIC", 0); rc += xpath(persistent_img, "/IMAGE/PERSISTENT", 0); rc += xpath(regtime, "/IMAGE/REGTIME", 0); @@ -457,6 +445,7 @@ int Image::disk_attribute( VectorAttribute * disk, { disk->replace("CLONE","NO"); disk->replace("SAVE","YES"); + disk->replace("PERSISTENT","YES"); } else { diff --git a/src/image/ImageManagerDriver.cc b/src/image/ImageManagerDriver.cc index 3e2b5baaae..b1723b2e57 100644 --- a/src/image/ImageManagerDriver.cc +++ b/src/image/ImageManagerDriver.cc @@ -229,13 +229,15 @@ void ImageManagerDriver::protocol( else if ( action == "RM" ) { int rc; + string tmp_error; source = image->get_source(); - rc = ipool->drop(image); + rc = ipool->drop(image, tmp_error); if ( rc < 0 ) { + image->unlock(); NebulaLog::log("ImM",Log::ERROR,"Image could not be removed from DB"); } diff --git a/src/image/ImagePool.cc b/src/image/ImagePool.cc index b59c8470a9..19313b552d 100644 --- a/src/image/ImagePool.cc +++ b/src/image/ImagePool.cc @@ -56,7 +56,7 @@ ImagePool::ImagePool(SqlDB * db, int ImagePool::allocate ( int uid, - string user_name, + int gid, ImageTemplate* img_template, int * oid, string& error_str) @@ -66,7 +66,7 @@ int ImagePool::allocate ( string name; ostringstream oss; - img = new Image(uid, user_name, img_template); + img = new Image(uid, gid, img_template); // Check name img->get_template_attribute("NAME", name); @@ -85,9 +85,22 @@ int ImagePool::allocate ( } // --------------------------------------------------------------------- - // Insert the Object in the pool + // Insert the Object in the pool & Register the image in the repository // --------------------------------------------------------------------- *oid = PoolSQL::allocate(img, error_str); + + if ( *oid != -1 ) + { + Nebula& nd = Nebula::instance(); + ImageManager * imagem = nd.get_imagem(); + + if ( imagem->register_image(*oid) == -1 ) + { + error_str = "Failed to copy image to repository. " + "Image left in ERROR state."; + return -1; + } + } return *oid; diff --git a/src/image/test/ImagePoolTest.cc b/src/image/test/ImagePoolTest.cc index c801177e94..d7745bd474 100644 --- a/src/image/test/ImagePoolTest.cc +++ b/src/image/test/ImagePoolTest.cc @@ -24,7 +24,6 @@ using namespace std; const int uids[] = {0,1,2}; -const string user_names[] = {"A user","B user","C user"}; const string names[] = {"Image one", "Second Image", "The third image"}; @@ -50,21 +49,38 @@ const string templates[] = const string xmls[] = { - "00A userImage one0010000000000-40", + "001Image one0010000000000-40", - "11B userSecond Image0100000000000-40", + "111Second Image0100000000000-40", - "02C userThe third image0000000000000-40" + "021The third image0000000000000-40" }; // This xml dump result has the STIMEs modified to 0000000000 const string xml_dump = -"00A userImage one0010000000000-4011B userSecond Image0100000000000-4022C userThe third image0000000000000-40"; +"001Image one0010000000000-40111Second Image0100000000000-40221The third image0000000000000-40"; const string xml_dump_where = -"00A userImage one0010000000000-4011B userSecond Image0100000000000-40"; +"001Image one0010000000000-40111Second Image0100000000000-40"; + + +/* ************************************************************************* */ +/* ************************************************************************* */ + +#include "NebulaTest.h" + +class NebulaTestImage: public NebulaTest +{ +public: + NebulaTestImage():NebulaTest() + { + NebulaTest::the_tester = this; + + need_image_pool = true; + need_imagem = true; + } +}; -const string replacement = "0000000000"; class ImagePoolFriend : public ImagePool { @@ -90,7 +106,7 @@ public: if( rc == 0 ) { - return ImagePool::allocate(uid, user_names[uid], img_template, oid, err); + return ImagePool::allocate(uid, 1, img_template, oid, err); } else { @@ -137,16 +153,18 @@ class ImagePoolTest : public PoolTest protected: + NebulaTestImage * tester; + ImagePool * ipool; + void bootstrap(SqlDB* db) { - ImagePool::bootstrap(db); + // setUp overwritten }; PoolSQL* create_pool(SqlDB* db) { - ImagePoolFriend * imp = - new ImagePoolFriend(db, "OS", "hd"); - return imp; + // setUp overwritten + return ipool; }; int allocate(int index) @@ -167,7 +185,7 @@ protected: // Get the xml and replace the REGTIME to 0, so we can compare // it. ((Image*)obj)->to_xml(xml_str); - xml_str.replace( xml_str.find("")+9, 10, replacement); + fix_regtimes(xml_str); /* if( xml_str != xmls[index] ) @@ -185,7 +203,26 @@ public: ~ImagePoolTest(){xmlCleanupParser();}; + void setUp() + { + create_db(); + tester = new NebulaTestImage(); + + Nebula& neb = Nebula::instance(); + neb.start(); + + ipool = neb.get_ipool(); + + pool = ipool; + }; + + void tearDown() + { + delete_db(); + + delete tester; + }; /* ********************************************************************* */ void names_initialization() @@ -742,18 +779,18 @@ public: i++; } - bool success; + int success; // img 0 is not public. img = imp->get( 0, false ); CPPUNIT_ASSERT( img != 0 ); success = img->publish(false); - CPPUNIT_ASSERT( success == true ); + CPPUNIT_ASSERT( success == 0 ); CPPUNIT_ASSERT( img->isPublic() == false ); success = img->publish(true); - CPPUNIT_ASSERT( success == true ); + CPPUNIT_ASSERT( success == 0 ); CPPUNIT_ASSERT( img->isPublic() == true ); } @@ -763,7 +800,7 @@ public: void persistence() { int oid; - bool success; + int success; ImagePoolFriend * imp = static_cast(pool); Image * img; @@ -819,33 +856,33 @@ public: // make it persistent success = img->persistent(true); - CPPUNIT_ASSERT( success == true ); + CPPUNIT_ASSERT( success == 0 ); CPPUNIT_ASSERT( img->isPersistent() == true ); // it isn't public, try to unpublish success = img->publish(false); - CPPUNIT_ASSERT( success == true ); + CPPUNIT_ASSERT( success == 0 ); CPPUNIT_ASSERT( img->isPublic() == false ); // try to publish, should fail because it is persistent success = img->publish(true); - CPPUNIT_ASSERT( success == false ); + CPPUNIT_ASSERT( success == -1 ); CPPUNIT_ASSERT( img->isPublic() == false ); // make it non-persistent success = img->persistent(false); - CPPUNIT_ASSERT( success == true ); + CPPUNIT_ASSERT( success == 0 ); CPPUNIT_ASSERT( img->isPersistent() == false ); // it isn't public, try to unpublish success = img->publish(false); - CPPUNIT_ASSERT( success == true ); + CPPUNIT_ASSERT( success == 0 ); CPPUNIT_ASSERT( img->isPublic() == false ); // try to publish, now it should be possible success = img->publish(true); - CPPUNIT_ASSERT( success == true ); + CPPUNIT_ASSERT( success == 0 ); CPPUNIT_ASSERT( img->isPublic() == true ); } @@ -868,17 +905,14 @@ public: CPPUNIT_ASSERT(rc == 0); string result = oss.str(); - - result.replace(157, 10, replacement); - result.replace(1076, 10, replacement); - result.replace(1535, 10, replacement); + fix_regtimes(result); /* if( result != xml_dump ) { cout << endl << result << endl << xml_dump << endl; } -*/ +//*/ CPPUNIT_ASSERT( result == xml_dump ); } @@ -904,15 +938,14 @@ public: CPPUNIT_ASSERT(rc == 0); string result = oss.str(); - result.replace(157, 10, replacement); - result.replace(1076, 10, replacement); - + fix_regtimes(result); +/* if( result != xml_dump_where ) { cout << endl << result << endl << xml_dump_where << endl; } - +//*/ CPPUNIT_ASSERT( result == xml_dump_where ); } diff --git a/src/image/test/SConstruct b/src/image/test/SConstruct index 4d5bc99d00..8827054f90 100644 --- a/src/image/test/SConstruct +++ b/src/image/test/SConstruct @@ -17,20 +17,30 @@ Import('env') env.Prepend(LIBS=[ - 'nebula_image', +### TODO: delete not needed + 'nebula_core_test', + 'nebula_host', + 'nebula_xml', + 'nebula_vmm', + 'nebula_im', + 'nebula_rm', + 'nebula_tm', 'nebula_um', - 'nebula_vm', - 'nebula_hm', - 'nebula_vnm', - 'nebula_authm', - 'nebula_template', - 'nebula_pool', 'nebula_mad', + 'nebula_template', + 'nebula_vm', + 'nebula_vmtemplate', + 'nebula_group', + 'nebula_vnm', + 'nebula_image', + 'nebula_pool', + 'nebula_hm', + 'nebula_authm', 'nebula_common', - 'nebula_core', + 'nebula_lcm', + 'nebula_dm', 'nebula_sql', 'nebula_log', - 'nebula_xml', 'crypto' ]) diff --git a/src/lcm/test/LifeCycleManagerTest.cc b/src/lcm/test/LifeCycleManagerTest.cc index 23672f7c21..33ec6ea6ed 100644 --- a/src/lcm/test/LifeCycleManagerTest.cc +++ b/src/lcm/test/LifeCycleManagerTest.cc @@ -22,6 +22,7 @@ using namespace std; const int uids[] = {123, 261, 123}; +const int gids[] = {150, 164, 175}; const string names[] = {"VM one", "Second VM", "VM 3"}; @@ -185,7 +186,7 @@ private: if( rc == 0 ) { - return vmpool->allocate(uids[index], "username", vm_template, &oid, + return vmpool->allocate(uids[index], gids[index], vm_template, &oid, err, false); } else diff --git a/src/lcm/test/NebulaTestLCM.h b/src/lcm/test/NebulaTestLCM.h index f7e06af4ea..0261c51618 100644 --- a/src/lcm/test/NebulaTestLCM.h +++ b/src/lcm/test/NebulaTestLCM.h @@ -29,6 +29,7 @@ public: need_vm_pool = true; need_host_pool = true; need_user_pool = true; + need_group_pool = true; need_vnet_pool = true; need_image_pool= true; diff --git a/src/lcm/test/SConstruct b/src/lcm/test/SConstruct index 5fbcbc1687..41597fac76 100644 --- a/src/lcm/test/SConstruct +++ b/src/lcm/test/SConstruct @@ -21,7 +21,6 @@ Import('env') env.Prepend(LIBS=[ 'nebula_core_test', 'nebula_host', - 'nebula_cluster', 'nebula_vmm', 'nebula_im', 'nebula_rm', @@ -31,9 +30,9 @@ env.Prepend(LIBS=[ 'nebula_template', 'nebula_vm', 'nebula_vmtemplate', + 'nebula_group', 'nebula_vnm', 'nebula_image', - 'nebula_pool', 'nebula_xml', 'nebula_hm', 'nebula_authm', @@ -42,6 +41,7 @@ env.Prepend(LIBS=[ 'nebula_log', 'nebula_lcm', 'nebula_dm', + 'nebula_pool', 'crypto' ]) diff --git a/src/mad/test/dummy b/src/mad/test/dummy new file mode 100755 index 0000000000..8db81aaf4d --- /dev/null +++ b/src/mad/test/dummy @@ -0,0 +1,26 @@ +#!/bin/bash + +# -------------------------------------------------------------------------- # +# 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. # +#--------------------------------------------------------------------------- # + +#echo "MAD started" >> mad.log + +while read COMMAND ARG1 ARG2 ARG3 +do +# echo "$COMMAND $ARG1 $ARG2 $ARG3" >> mad.log + + echo "$COMMAND SUCCESS" +done diff --git a/src/nebula/Nebula.cc b/src/nebula/Nebula.cc index a96eb6e10e..251afffc46 100644 --- a/src/nebula/Nebula.cc +++ b/src/nebula/Nebula.cc @@ -243,9 +243,9 @@ void Nebula::start() VirtualMachinePool::bootstrap(db); HostPool::bootstrap(db); VirtualNetworkPool::bootstrap(db); + GroupPool::bootstrap(db); UserPool::bootstrap(db); ImagePool::bootstrap(db); - ClusterPool::bootstrap(db); VMTemplatePool::bootstrap(db); } } @@ -275,6 +275,8 @@ void Nebula::start() vnpool = new VirtualNetworkPool(db,mac_prefix,size); + gpool = new GroupPool(db); + upool = new UserPool(db); nebula_configuration->get("DEFAULT_IMAGE_TYPE", default_image_type); @@ -285,8 +287,6 @@ void Nebula::start() default_image_type, default_device_prefix); - cpool = new ClusterPool(db); - tpool = new VMTemplatePool(db); } catch (exception&) @@ -447,16 +447,7 @@ void Nebula::start() nebula_configuration->get("PORT", rm_port); - rm = new RequestManager( - vmpool, - hpool, - vnpool, - upool, - ipool, - cpool, - tpool, - rm_port, - log_location + "one_xmlrpc.log"); + rm = new RequestManager(rm_port, log_location + "one_xmlrpc.log"); } catch (bad_alloc&) { @@ -616,6 +607,7 @@ void Nebula::bootstrap() oss << "CREATE TABLE pool_control (tablename VARCHAR(32) PRIMARY KEY, " "last_oid BIGINT UNSIGNED)"; + db->exec(oss); oss.str(""); diff --git a/src/nebula/SConstruct b/src/nebula/SConstruct index 3cd71f38a4..93b154eb77 100644 --- a/src/nebula/SConstruct +++ b/src/nebula/SConstruct @@ -41,12 +41,12 @@ env.Prepend(LIBS=[ 'nebula_dm', 'nebula_tm', 'nebula_um', + 'nebula_group', 'nebula_authm', 'nebula_mad', 'nebula_template', 'nebula_image', 'nebula_pool', - 'nebula_cluster', 'nebula_host', 'nebula_vnm', 'nebula_vm', diff --git a/src/oca/java/src/org/opennebula/client/PoolElement.java b/src/oca/java/src/org/opennebula/client/PoolElement.java index fe364f9b63..72ea4e6b69 100644 --- a/src/oca/java/src/org/opennebula/client/PoolElement.java +++ b/src/oca/java/src/org/opennebula/client/PoolElement.java @@ -134,6 +134,50 @@ public abstract class PoolElement { return state != null ? Integer.parseInt( state ) : -1; } + /** + * Returns the owner User's ID, or -1 if the element doesn't have one. + * + * @return the owner User's ID, or -1 if the element doesn't have one. + */ + public int uid() + { + String uid_str = xpath("UID"); + int uid_int = -1; + + if ( uid_str != null ) + { + try + { + uid_int = Integer.parseInt( uid_str ); + } + catch (NumberFormatException e) {} + } + + return uid_int; + } + + /** + * Returns the element group's ID, or -1 if the element doesn't have one. + * + * @return the element group's ID, or -1 if the element doesn't have one. + */ + public int gid() + { + String gid_str = xpath("GID"); + int gid_int = -1; + + if ( gid_str != null ) + { + try + { + gid_int = Integer.parseInt( gid_str ); + } + catch (NumberFormatException e) {} + } + + return gid_int; + } + /** * Evaluates an XPath expression and returns the result as a String. * If the internal xml representation is not built, returns null. The @@ -141,7 +185,8 @@ public abstract class PoolElement { * * @param expression The XPath expression. * @return The String that is the result of evaluating the - * expression and converting the result to a String. Null if + * expression and converting the result to a String. An empty String is + * returned if the expression is not a valid path; null if * the internal xml representation is not built. */ public String xpath(String expression) diff --git a/src/oca/java/src/org/opennebula/client/cluster/Cluster.java b/src/oca/java/src/org/opennebula/client/cluster/Cluster.java deleted file mode 100644 index 8bf6b9647d..0000000000 --- a/src/oca/java/src/org/opennebula/client/cluster/Cluster.java +++ /dev/null @@ -1,198 +0,0 @@ -/******************************************************************************* - * 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.cluster; - -import org.opennebula.client.Client; -import org.opennebula.client.OneResponse; -import org.opennebula.client.PoolElement; -import org.opennebula.client.host.Host; -import org.w3c.dom.Node; - -/** - * This class represents an OpenNebula cluster. - * It also offers static XML-RPC call wrappers. - */ -public class Cluster extends PoolElement -{ - - private static final String METHOD_PREFIX = "cluster."; - private static final String ALLOCATE = METHOD_PREFIX + "allocate"; - private static final String INFO = METHOD_PREFIX + "info"; - private static final String DELETE = METHOD_PREFIX + "delete"; - private static final String ADD = METHOD_PREFIX + "add"; - private static final String REMOVE = METHOD_PREFIX + "remove"; - - - /** - * Creates a new Image representation. - * @param id The image id. - * @param client XML-RPC Client. - */ - public Cluster(int id, Client client) - { - super(id, client); - } - - /** - * @see PoolElement - */ - protected Cluster(Node xmlElement, Client client) - { - super(xmlElement, client); - } - - - // ================================= - // Static XML-RPC methods - // ================================= - - - /** - * Allocates a new Cluster in OpenNebula. - * - * @param client XML-RPC Client. - * @param name Name for the cluster we want to add. - * @return If successful the message contains the associated - * id generated for this Cluster. - */ - public static OneResponse allocate(Client client, String name) - { - return client.call(ALLOCATE, name); - } - - /** - * Retrieves the information of the given Cluster. - * - * @param client XML-RPC Client. - * @param id The cluster id for the cluster to retrieve the information from - * @return If successful the message contains the string - * with the information returned by OpenNebula. - */ - public static OneResponse info(Client client, int id) - { - return client.call(INFO, id); - } - - /** - * Deletes a cluster from OpenNebula. - * - * @param client XML-RPC Client. - * @param id The cluster id of the target cluster we want to delete. - * @return A encapsulated response. - */ - public static OneResponse delete(Client client, int id) - { - return client.call(DELETE, id); - } - - /** - * Adds a host to a cluster. - * - * @param client XML-RPC Client. - * @param id The cluster id of the cluster where the host will be assigned. - * @param hid The host id (hid) of the host. - * @return If an error occurs the error message contains the reason. - */ - public static OneResponse add(Client client, int id, int hid) - { - return client.call(ADD, hid, id); - } - - /** - * Removes a host from its cluster. - * - * @param client XML-RPC Client. - * @param hid The host id (hid) of the host. - * @return If an error occurs the error message contains the reason. - */ - public static OneResponse remove(Client client, int hid) - { - return client.call(REMOVE, hid); - } - - - // ================================= - // Instanced object XML-RPC methods - // ================================= - - - /** - * Retrieves the information of the Cluster. - * - * @return If successful the message contains the string - * with the information returned by OpenNebula. - */ - public OneResponse info() - { - OneResponse response = info(client, id); - super.processInfo(response); - return response; - } - - /** - * Deletes the cluster from OpenNebula. - * - * @return A encapsulated response. - */ - public OneResponse delete() - { - return delete(client, id); - } - - /** - * Adds a host to the cluster. - * - * @param hid The host id (hid) of the host. - * @return If an error occurs the error message contains the reason. - */ - public OneResponse add(int hid) - { - return add(client, id, hid); - } - - /** - * Adds a host to the cluster. - * - * @param host The Host to add. - * @return If an error occurs the error message contains the reason. - */ - public OneResponse add(Host host) - { - return add(client, id, host.id()); - } - - /** - * Removes a host from its cluster. - * - * @param hid The host id (hid) of the host. - * @return If an error occurs the error message contains the reason. - */ - public OneResponse remove(int hid) - { - return remove(client, hid); - } - - /** - * Removes a host from its cluster. - * - * @param host The Host to remove. - * @return If an error occurs the error message contains the reason. - */ - public OneResponse remove(Host host) - { - return remove(client, host.id()); - } -} diff --git a/src/oca/java/src/org/opennebula/client/group/Group.java b/src/oca/java/src/org/opennebula/client/group/Group.java new file mode 100644 index 0000000000..f3f511233d --- /dev/null +++ b/src/oca/java/src/org/opennebula/client/group/Group.java @@ -0,0 +1,140 @@ +/******************************************************************************* + * 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.group; + + +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 group. + * It also offers static XML-RPC call wrappers. + */ +public class Group extends PoolElement{ + + private static final String METHOD_PREFIX = "group."; + private static final String ALLOCATE = METHOD_PREFIX + "allocate"; + private static final String INFO = METHOD_PREFIX + "info"; + private static final String DELETE = METHOD_PREFIX + "delete"; + + + /** + * Creates a new Group representation. + * + * @param id The group id (hid) of the machine. + * @param client XML-RPC Client. + */ + public Group(int id, Client client) + { + super(id, client); + } + + /** + * @see PoolElement + */ + protected Group(Node xmlElement, Client client) + { + super(xmlElement, client); + } + + + // ================================= + // Static XML-RPC methods + // ================================= + + /** + * Allocates a new group in OpenNebula + * + * @param client XML-RPC Client. + * @param name Name for the new group. + * @return If successful the message contains the associated + * id generated for this group. + */ + public static OneResponse allocate(Client client, String name) + { + return client.call(ALLOCATE, name); + } + + /** + * Retrieves the information of the given group. + * + * @param client XML-RPC Client. + * @param id The group id. + * @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 group from OpenNebula. + * + * @param client XML-RPC Client. + * @param id The group id. + * @return A encapsulated response. + */ + public static OneResponse delete(Client client, int id) + { + return client.call(DELETE, id); + } + + // ================================= + // Instanced object XML-RPC methods + // ================================= + + /** + * Loads the xml representation of the group. + * The info is also stored internally. + * + * @see Group#info(Client, int) + */ + public OneResponse info() + { + OneResponse response = info(client, id); + super.processInfo(response); + return response; + } + + /** + * Deletes the group from OpenNebula. + * + * @see Group#delete(Client, int) + */ + public OneResponse delete() + { + return delete(client, id); + } + + // ================================= + // Helpers + // ================================= + + /** + * Returns whether or not the user is part of this group + * + * @param uid The user ID. + * @return Whether or not the user is part of this group. + */ + public boolean contains(int uid) + { + String res = xpath("USERS/ID[.="+uid+"]"); + return res != null && res.equals(""+uid); + } +} diff --git a/src/oca/java/src/org/opennebula/client/cluster/ClusterPool.java b/src/oca/java/src/org/opennebula/client/group/GroupPool.java similarity index 68% rename from src/oca/java/src/org/opennebula/client/cluster/ClusterPool.java rename to src/oca/java/src/org/opennebula/client/group/GroupPool.java index 737f7466ef..bfdc346305 100644 --- a/src/oca/java/src/org/opennebula/client/cluster/ClusterPool.java +++ b/src/oca/java/src/org/opennebula/client/group/GroupPool.java @@ -1,23 +1,24 @@ /******************************************************************************* * 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.cluster; +package org.opennebula.client.group; import java.util.AbstractList; import java.util.Iterator; + import org.opennebula.client.Client; import org.opennebula.client.OneResponse; import org.opennebula.client.Pool; @@ -25,36 +26,32 @@ import org.opennebula.client.PoolElement; import org.w3c.dom.Node; /** - * This class represents an OpenNebula Cluster pool. + * This class represents an OpenNebula group pool. * It also offers static XML-RPC call wrappers. */ -public class ClusterPool extends Pool implements Iterable -{ - private static final String ELEMENT_NAME = "CLUSTER"; - private static final String INFO_METHOD = "clusterpool.info"; +public class GroupPool extends Pool implements Iterable{ + + private static final String ELEMENT_NAME = "GROUP"; + private static final String INFO_METHOD = "grouppool.info"; /** - * Creates a new Image pool - * + * Creates a new group pool * @param client XML-RPC Client. */ - public ClusterPool(Client client) + public GroupPool(Client client) { super(ELEMENT_NAME, client); } - /* (non-Javadoc) - * @see org.opennebula.client.Pool#factory(org.w3c.dom.Node) - */ @Override public PoolElement factory(Node node) { - return new Cluster(node, client); + return new Group(node, client); } /** - * Returns the Cluster pool information. - * + * Retrieves all the hosts in the pool. + * * @param client XML-RPC Client. * @return If successful the message contains the string * with the information returned by OpenNebula. @@ -65,9 +62,9 @@ public class ClusterPool extends Pool implements Iterable } /** - * Loads the xml representation of the Cluster pool. - * - * @see ClusterPool#info(Client) + * Loads the xml representation of the group pool. + * + * @see GroupPool#info(Client) */ public OneResponse info() { @@ -76,18 +73,18 @@ public class ClusterPool extends Pool implements Iterable return response; } - public Iterator iterator() + public Iterator iterator() { - AbstractList ab = new AbstractList() + AbstractList ab = new AbstractList() { public int size() { return getLength(); } - public Cluster get(int index) + public Group get(int index) { - return (Cluster) item(index); + return (Group) item(index); } }; diff --git a/src/oca/java/src/org/opennebula/client/host/Host.java b/src/oca/java/src/org/opennebula/client/host/Host.java index e4a8d08fa3..2b5cf12cec 100644 --- a/src/oca/java/src/org/opennebula/client/host/Host.java +++ b/src/oca/java/src/org/opennebula/client/host/Host.java @@ -227,14 +227,4 @@ public class Host extends PoolElement{ { return state() != 4; } - - /** - * Returns the name of the cluster this host is assigned to. - * - * @return The name of the cluster this host is assigned to. - */ - public String getCluster() - { - return xpath("CLUSTER"); - } } diff --git a/src/oca/java/src/org/opennebula/client/image/Image.java b/src/oca/java/src/org/opennebula/client/image/Image.java index 2f9f04e4c5..00d72212bf 100644 --- a/src/oca/java/src/org/opennebula/client/image/Image.java +++ b/src/oca/java/src/org/opennebula/client/image/Image.java @@ -32,9 +32,9 @@ public class Image extends PoolElement private static final String INFO = METHOD_PREFIX + "info"; private static final String DELETE = METHOD_PREFIX + "delete"; private static final String UPDATE = METHOD_PREFIX + "update"; - private static final String RMATTR = METHOD_PREFIX + "rmattr"; private static final String ENABLE = METHOD_PREFIX + "enable"; private static final String PUBLISH = METHOD_PREFIX + "publish"; + private static final String CHOWN = METHOD_PREFIX + "chown"; private static final String[] IMAGE_STATES = {"INIT", "READY", "USED", "DISABLED"}; @@ -110,31 +110,16 @@ public class Image extends PoolElement } /** - * Modifies an image attribute. + * Replaces the template contents. * * @param client XML-RPC Client. * @param id The image id of the target image we want to modify. - * @param att_name The name of the attribute to update. - * @param att_val The new value for the attribute. + * @param new_template New template contents * @return If successful the message contains the image id. */ - public static OneResponse update(Client client, int id, - String att_name, String att_val) + public static OneResponse update(Client client, int id, String new_template) { - return client.call(UPDATE, id, att_name, att_val); - } - - /** - * Removes an image attribute. - * - * @param client XML-RPC Client. - * @param id The image id of the target image we want to modify. - * @param att_name The name of the attribute to remove. - * @return If successful the message contains the image id. - */ - public static OneResponse rmattr(Client client, int id, String att_name) - { - return client.call(RMATTR, id, att_name); + return client.call(UPDATE, id, new_template); } /** @@ -163,6 +148,19 @@ public class Image extends PoolElement return client.call(PUBLISH, id, publish); } + /** + * Changes the owner/group + * + * @param client XML-RPC Client. + * @param id The image id of the target image we want to modify. + * @param uid The new owner user ID. Set it to -1 to leave the current one. + * @param gid The new group ID. Set it to -1 to leave the current one. + * @return If an error occurs the error message contains the reason. + */ + public static OneResponse chown(Client client, int id, int uid, int gid) + { + return client.call(CHOWN, id, uid, gid); + } // ================================= // Instanced object XML-RPC methods @@ -192,26 +190,14 @@ public class Image extends PoolElement } /** - * Modifies an image attribute. + * Replaces the template contents. * - * @param att_name The name of the attribute to update. - * @param att_val The new value for the attribute. + * @param new_template New template contents * @return If successful the message contains the image id. */ - public OneResponse update(String att_name, String att_val) + public OneResponse update(String new_template) { - return update(client, id, att_name, att_val); - } - - /** - * Removes an image attribute. - * - * @param att_name The name of the attribute to remove. - * @return If successful the message contains the image id. - */ - public OneResponse rmattr(String att_name) - { - return rmattr(client, id, att_name); + return update(client, id, new_template); } /** @@ -276,6 +262,40 @@ public class Image extends PoolElement return publish(false); } + /** + * Changes the owner/group + * + * @param uid The new owner user ID. Set it to -1 to leave the current one. + * @param gid The new group ID. Set it to -1 to leave the current one. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chown(int uid, int gid) + { + return chown(client, id, uid, gid); + } + + /** + * Changes the owner + * + * @param uid The new owner user ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chown(int uid) + { + return chown(uid, -1); + } + + /** + * Changes the group + * + * @param gid The new group ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chgrp(int gid) + { + return chown(-1, gid); + } + // ================================= // Helpers // ================================= diff --git a/src/oca/java/src/org/opennebula/client/template/Template.java b/src/oca/java/src/org/opennebula/client/template/Template.java index acdb2530c5..2dc52b3ae5 100644 --- a/src/oca/java/src/org/opennebula/client/template/Template.java +++ b/src/oca/java/src/org/opennebula/client/template/Template.java @@ -32,8 +32,9 @@ public class Template extends PoolElement 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"; + private static final String CHOWN = METHOD_PREFIX + "chown"; + private static final String INSTANTIATE = METHOD_PREFIX + "instantiate"; /** * Creates a new Template representation. @@ -97,31 +98,16 @@ public class Template extends PoolElement } /** - * Modifies a template attribute. + * Replaces the template contents. * * @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. + * @param new_template New template contents. * @return If successful the message contains the template id. */ - public static OneResponse update(Client client, int id, - String att_name, String att_val) + public static OneResponse update(Client client, int id, String new_template) { - 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); + return client.call(UPDATE, id, new_template); } /** @@ -137,6 +123,32 @@ public class Template extends PoolElement return client.call(PUBLISH, id, publish); } + /** + * Changes the owner/group + * + * @param client XML-RPC Client. + * @param id The template id of the target template we want to modify. + * @param uid The new owner user ID. Set it to -1 to leave the current one. + * @param gid The new group ID. Set it to -1 to leave the current one. + * @return If an error occurs the error message contains the reason. + */ + public static OneResponse chown(Client client, int id, int uid, int gid) + { + return client.call(CHOWN, id, uid, gid); + } + + /** + * Creates a VM instance from a Template + * + * @param client XML-RPC Client. + * @param id The template id of the target template. + * @param name A string containing the name of the VM instance, can be empty. + * @return If successful the message contains the VM Instance ID. + */ + public static OneResponse instantiate(Client client, int id, String name) + { + return client.call(INSTANTIATE, id, name); + } // ================================= // Instanced object XML-RPC methods @@ -166,26 +178,14 @@ public class Template extends PoolElement } /** - * Modifies a template attribute. + * Replaces the template contents. * - * @param att_name The name of the attribute to update. - * @param att_val The new value for the attribute. + * @param new_template New template contents. * @return If successful the message contains the template id. */ - public OneResponse update(String att_name, String att_val) + public OneResponse update(String new_template) { - 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); + return update(client, id, new_template); } /** @@ -219,6 +219,61 @@ public class Template extends PoolElement return publish(false); } + /** + * Changes the owner/group + * + * @param uid The new owner user ID. Set it to -1 to leave the current one. + * @param gid The new group ID. Set it to -1 to leave the current one. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chown(int uid, int gid) + { + return chown(client, id, uid, gid); + } + + /** + * Changes the owner + * + * @param uid The new owner user ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chown(int uid) + { + return chown(uid, -1); + } + + /** + * Changes the group + * + * @param gid The new group ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chgrp(int gid) + { + return chown(-1, gid); + } + + /** + * Creates a VM instance from a Template + * + * @param name A string containing the name of the VM instance, can be empty. + * @return If successful the message contains the VM Instance ID. + */ + public OneResponse instantiate(String name) + { + return instantiate(client, id, name); + } + + /** + * Creates a VM instance from a Template + * + * @return If successful the message contains the VM Instance ID. + */ + public OneResponse instantiate() + { + return instantiate(client, id, ""); + } + // ================================= // Helpers // ================================= diff --git a/src/oca/java/src/org/opennebula/client/user/User.java b/src/oca/java/src/org/opennebula/client/user/User.java index 40c153045b..adf73f0f5f 100644 --- a/src/oca/java/src/org/opennebula/client/user/User.java +++ b/src/oca/java/src/org/opennebula/client/user/User.java @@ -32,6 +32,9 @@ public class User extends PoolElement{ private static final String INFO = METHOD_PREFIX + "info"; private static final String DELETE = METHOD_PREFIX + "delete"; private static final String PASSWD = METHOD_PREFIX + "passwd"; + private static final String CHGRP = METHOD_PREFIX + "chgrp"; + private static final String ADDGROUP = METHOD_PREFIX + "addgroup"; + private static final String DELGROUP = METHOD_PREFIX + "delgroup"; /** * Creates a new User representation. @@ -111,6 +114,45 @@ public class User extends PoolElement{ return client.call(PASSWD, id, password); } + /** + * Changes the main group of the given user + * + * @param client XML-RPC Client. + * @param id The user id (uid) of the target user we want to modify. + * @param gid The new group ID. + * @return If an error occurs the error message contains the reason. + */ + public static OneResponse chgrp(Client client, int id, int gid) + { + return client.call(CHGRP, id, gid); + } + + /** + * Adds this user to a secondary group + * + * @param client XML-RPC Client. + * @param id The user id (uid) of the target user we want to modify. + * @param gid The new group ID. + * @return If an error occurs the error message contains the reason. + */ + public static OneResponse addgroup(Client client, int id, int gid) + { + return client.call(ADDGROUP, id, gid); + } + + /** + * Removes this user from a secondary group + * + * @param client XML-RPC Client. + * @param id The user id (uid) of the target user we want to modify. + * @param gid The new group ID. + * @return If an error occurs the error message contains the reason. + */ + public static OneResponse delgroup(Client client, int id, int gid) + { + return client.call(DELGROUP, id, gid); + } + // ================================= // Instanced object XML-RPC methods // ================================= @@ -150,6 +192,39 @@ public class User extends PoolElement{ return passwd(client, id, password); } + /** + * Changes the main group of the given user + * + * @param gid The new group ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chgrp(int gid) + { + return chgrp(client, id, gid); + } + + /** + * Adds this user to a secondary group + * + * @param gid The new group ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse addgroup(int gid) + { + return addgroup(client, id, gid); + } + + /** + * Removes this user from a secondary group + * + * @param gid The new group ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse delgroup(int gid) + { + return delgroup(client, id, gid); + } + // ================================= // Helpers // ================================= @@ -164,4 +239,16 @@ public class User extends PoolElement{ String enabled = xpath("ENABLED"); return enabled != null && enabled.equals("1"); } + + /** + * Returns whether or not the user is part of the group + * + * @param gid The group ID. + * @return whether or not the user is part of the group + */ + public boolean isPartOf(int gid) + { + String res = xpath("GROUPS/ID[.="+gid+"]"); + return res != null && res.equals(""+gid); + } } diff --git a/src/oca/java/src/org/opennebula/client/vm/VirtualMachine.java b/src/oca/java/src/org/opennebula/client/vm/VirtualMachine.java index 692a5a2a8c..b15db02bdb 100644 --- a/src/oca/java/src/org/opennebula/client/vm/VirtualMachine.java +++ b/src/oca/java/src/org/opennebula/client/vm/VirtualMachine.java @@ -35,6 +35,7 @@ public class VirtualMachine extends PoolElement{ private static final String ACTION = METHOD_PREFIX + "action"; private static final String MIGRATE = METHOD_PREFIX + "migrate"; private static final String SAVEDISK = METHOD_PREFIX + "savedisk"; + private static final String CHOWN = METHOD_PREFIX + "chown"; private static final String[] VM_STATES = { @@ -198,6 +199,19 @@ public class VirtualMachine extends PoolElement{ return client.call(INFO, id); } + /** + * Changes the owner/group + * + * @param client XML-RPC Client. + * @param id The virtual machine id (vid) of the target instance. + * @param uid The new owner user ID. Set it to -1 to leave the current one. + * @param gid The new group ID. Set it to -1 to leave the current one. + * @return If an error occurs the error message contains the reason. + */ + public static OneResponse chown(Client client, int id, int uid, int gid) + { + return client.call(CHOWN, id, uid, gid); + } // ================================= // Instanced object XML-RPC methods @@ -281,6 +295,40 @@ public class VirtualMachine extends PoolElement{ return client.call(SAVEDISK, id ,diskId, imageName); } + /** + * Changes the owner/group + * + * @param uid The new owner user ID. Set it to -1 to leave the current one. + * @param gid The new group ID. Set it to -1 to leave the current one. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chown(int uid, int gid) + { + return chown(client, id, uid, gid); + } + + /** + * Changes the owner + * + * @param uid The new owner user ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chown(int uid) + { + return chown(uid, -1); + } + + /** + * Changes the group + * + * @param gid The new group ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chgrp(int gid) + { + return chown(-1, gid); + } + // ================================= // Helpers // ================================= diff --git a/src/oca/java/src/org/opennebula/client/vnet/VirtualNetwork.java b/src/oca/java/src/org/opennebula/client/vnet/VirtualNetwork.java index bf7bb97e08..8a13cffdd2 100644 --- a/src/oca/java/src/org/opennebula/client/vnet/VirtualNetwork.java +++ b/src/oca/java/src/org/opennebula/client/vnet/VirtualNetwork.java @@ -34,6 +34,7 @@ public class VirtualNetwork extends PoolElement{ private static final String PUBLISH = METHOD_PREFIX + "publish"; private static final String ADDLEASES = METHOD_PREFIX + "addleases"; private static final String RMLEASES = METHOD_PREFIX + "rmleases"; + private static final String CHOWN = METHOD_PREFIX + "chown"; /** @@ -138,6 +139,20 @@ public class VirtualNetwork extends PoolElement{ return client.call(RMLEASES, id, template); } + /** + * Changes the owner/group + * + * @param client XML-RPC Client. + * @param id The virtual network id (nid) of the target network. + * @param uid The new owner user ID. Set it to -1 to leave the current one. + * @param gid The new group ID. Set it to -1 to leave the current one. + * @return If an error occurs the error message contains the reason. + */ + public static OneResponse chown(Client client, int id, int uid, int gid) + { + return client.call(CHOWN, id, uid, gid); + } + // ================================= // Instanced object XML-RPC methods // ================================= @@ -242,6 +257,40 @@ public class VirtualNetwork extends PoolElement{ return rmLeases(client, id, lease_template); } + /** + * Changes the owner/group + * + * @param uid The new owner user ID. Set it to -1 to leave the current one. + * @param gid The new group ID. Set it to -1 to leave the current one. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chown(int uid, int gid) + { + return chown(client, id, uid, gid); + } + + /** + * Changes the owner + * + * @param uid The new owner user ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chown(int uid) + { + return chown(uid, -1); + } + + /** + * Changes the group + * + * @param gid The new group ID. + * @return If an error occurs the error message contains the reason. + */ + public OneResponse chgrp(int gid) + { + return chown(-1, gid); + } + // ================================= // Helpers // ================================= diff --git a/src/oca/java/test/ClusterTest.java b/src/oca/java/test/ClusterTest.java deleted file mode 100644 index 7431a1cb85..0000000000 --- a/src/oca/java/test/ClusterTest.java +++ /dev/null @@ -1,166 +0,0 @@ -/******************************************************************************* - * 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.cluster.Cluster; -import org.opennebula.client.cluster.ClusterPool; -import org.opennebula.client.host.Host; - - -public class ClusterTest -{ - - private static Cluster cluster; - private static ClusterPool clusterPool; - - private static Host host; - - private static Client client; - - private static OneResponse res; - private static String name = "new_test_cluster"; - private static int hid = -1; - - /** - * @throws java.lang.Exception - */ - @BeforeClass - public static void setUpBeforeClass() throws Exception - { - client = new Client(); - clusterPool = new ClusterPool(client); - - res = Host.allocate(client, "new_test_host", - "im_dummy", "vmm_dummy", "tm_dummy"); - try{ - hid = Integer.parseInt( res.getMessage() ); - }catch(NumberFormatException e) - { - System.err.println("Test initilization failed (setUpBeforeClass)."); - } - host = new Host(hid, client); - } - - /** - * @throws java.lang.Exception - */ - @AfterClass - public static void tearDownAfterClass() throws Exception - { - } - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception - { - res = Cluster.allocate(client, name); - - int clid = Integer.parseInt(res.getMessage()); - cluster = new Cluster(clid, client); - } - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception - { - cluster.delete(); - } - - @Test - public void allocate() - { - String allocate_name = "allocation_test"; - res = Cluster.allocate(client, allocate_name); - assertTrue( !res.isError() ); - - clusterPool.info(); - - boolean found = false; - for(Cluster c : clusterPool) - { - found = found || c.getName().equals(allocate_name); - } - - assertTrue( found ); - } - - @Test - public void update() - { - res = cluster.info(); - assertTrue( !res.isError() ); - -// assertTrue( cluster.getId().equals("1") ); -// assertTrue( cluster.id() == 1 ); - assertTrue( cluster.getName().equals(name) ); - } - - @Test - public void addHost() - { - res = cluster.add(hid); - assertTrue( !res.isError() ); - - res = host.info(); - assertTrue( !res.isError() ); - assertTrue( host.getCluster().equals(name) ); - } - - @Test - public void removeHost() - { - assertTrue( hid > -1 ); - - res = cluster.remove(hid); - assertTrue( !res.isError() ); - - res = host.info(); - assertTrue( !res.isError() ); - - assertTrue( host.getCluster().equals("default") ); - } - - @Test - public void attributes() - { - res = cluster.info(); - assertTrue( !res.isError() ); - -// assertTrue( cluster.xpath("ID").equals("1") ); - assertTrue( cluster.xpath("NAME").equals(name) ); - } - - @Test - public void delete() - { - res = cluster.delete(); - assertTrue( !res.isError() ); - - res = cluster.info(); - assertTrue( res.isError() ); - } -} diff --git a/src/oca/java/test/GroupTest.java b/src/oca/java/test/GroupTest.java new file mode 100644 index 0000000000..1bbd7078ea --- /dev/null +++ b/src/oca/java/test/GroupTest.java @@ -0,0 +1,224 @@ +/******************************************************************************* + * 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.*; + +import java.util.Hashtable; + +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.group.*; +import org.opennebula.client.user.User; + +public class GroupTest +{ + + private static Group group; + private static GroupPool groupPool; + + private static Client client; + + private static OneResponse res; + + private static String group_name = "test_group"; + + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception + { + client = new Client(); + groupPool = new GroupPool(client); + } + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception + { + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception + { + res = Group.allocate(client, group_name); + + int group_id = res.isError() ? -1 : Integer.parseInt(res.getMessage()); + group = new Group(group_id, client); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception + { + group.delete(); + } + + @Test + public void allocate() + { + group.delete(); + + res = Group.allocate(client, group_name); + assertTrue( !res.isError() ); + + int group_id = res.isError() ? -1 : Integer.parseInt(res.getMessage()); + group = new Group(group_id, client); + + + groupPool.info(); + + boolean found = false; + for(Group img : groupPool) + { + found = found || img.getName().equals(group_name); + } + + assertTrue( found ); + } + + @Test + public void info() + { + res = group.info(); + assertTrue( !res.isError() ); + + assertTrue( group.id() >= 100 ); + assertTrue( group.getName().equals(group_name) ); + } + + @Test + public void delete() + { + res = group.delete(); + assertTrue( !res.isError() ); + + res = group.info(); + assertTrue( res.isError() ); + + res = groupPool.info(); + assertTrue( !res.isError() ); + + boolean found = false; + for(Group g : groupPool) + { + found = found || g.getName().equals(group_name); + } + + assertTrue( !found ); + } + + @Test + public void userGroupRelations() + { + Hashtable users = new Hashtable(); + Hashtable groups = new Hashtable(); + + // Create all users and groups. Add user_* to corresponding group_* + String[] names = {"a", "b", "c", "d"}; + for(String name : names) + { + res = User.allocate(client, "user_"+name, "password"); + assertTrue( !res.isError() ); + + users.put( name, + new User(Integer.parseInt(res.getMessage()), client ) + ); + + res = Group.allocate(client, "group_"+name); + assertTrue( !res.isError() ); + + groups.put( name, + new Group(Integer.parseInt(res.getMessage()), client ) + ); + + users.get(name).addgroup( groups.get(name).id() ); + } + + // Add all users to group_b + for( User u : users.values() ) + { + u.addgroup( groups.get("b").id() ); + } + + // Change user_c & _d main group + users.get("c").chgrp( groups.get("d").id() ); + users.get("d").chgrp( groups.get("c").id() ); + + + // Check cross-references so far + for( User u : users.values() ) + { + assertTrue( !u.info().isError() ); + } + + for( Group g : groups.values() ) + { + assertTrue( !g.info().isError() ); + } + + assertTrue( users.get("a").isPartOf( groups.get("a").id() ) ); + assertTrue( users.get("a").isPartOf( groups.get("b").id() ) ); + assertFalse( users.get("a").isPartOf( groups.get("c").id() ) ); + assertFalse( users.get("a").isPartOf( groups.get("d").id() ) ); + + assertFalse( users.get("b").isPartOf( groups.get("a").id() ) ); + assertTrue( users.get("b").isPartOf( groups.get("b").id() ) ); + assertFalse( users.get("b").isPartOf( groups.get("c").id() ) ); + assertFalse( users.get("b").isPartOf( groups.get("d").id() ) ); + + assertFalse( users.get("c").isPartOf( groups.get("a").id() ) ); + assertTrue( users.get("c").isPartOf( groups.get("b").id() ) ); + assertTrue( users.get("c").isPartOf( groups.get("c").id() ) ); + assertTrue( users.get("c").isPartOf( groups.get("d").id() ) ); + + assertFalse( users.get("d").isPartOf( groups.get("a").id() ) ); + assertTrue( users.get("d").isPartOf( groups.get("b").id() ) ); + assertTrue( users.get("d").isPartOf( groups.get("c").id() ) ); + assertTrue( users.get("d").isPartOf( groups.get("d").id() ) ); + + assertTrue( groups.get("a").contains( users.get("a").id() ) ); + assertFalse( groups.get("a").contains( users.get("b").id() ) ); + assertFalse( groups.get("a").contains( users.get("c").id() ) ); + assertFalse( groups.get("a").contains( users.get("d").id() ) ); + + assertTrue( groups.get("b").contains( users.get("a").id() ) ); + assertTrue( groups.get("b").contains( users.get("b").id() ) ); + assertTrue( groups.get("b").contains( users.get("c").id() ) ); + assertTrue( groups.get("b").contains( users.get("d").id() ) ); + + assertFalse( groups.get("c").contains( users.get("a").id() ) ); + assertFalse( groups.get("c").contains( users.get("b").id() ) ); + assertTrue( groups.get("c").contains( users.get("c").id() ) ); + assertTrue( groups.get("c").contains( users.get("d").id() ) ); + assertFalse( groups.get("d").contains( users.get("a").id() ) ); + assertFalse( groups.get("d").contains( users.get("b").id() ) ); + assertTrue( groups.get("d").contains( users.get("c").id() ) ); + assertTrue( groups.get("d").contains( users.get("d").id() ) ); + } + +} diff --git a/src/oca/java/test/ImageTest.java b/src/oca/java/test/ImageTest.java index b0acbdfde3..1480564dcc 100644 --- a/src/oca/java/test/ImageTest.java +++ b/src/oca/java/test/ImageTest.java @@ -43,7 +43,8 @@ public class ImageTest return "NAME = \"test_img_" + cont + "\"\n" + "PATH = /etc/hosts\n" + - "ATT1 = \"val1\""; + "ATT1 = \"VAL1\"\n" + + "ATT2 = \"VAL2\""; } /** @@ -122,34 +123,26 @@ public class ImageTest @Test public void update() { - // Update an existing att. - res = image.update("ATT1", "new_val_1"); + res = image.info(); assertTrue( !res.isError() ); + assertTrue( image.xpath("TEMPLATE/ATT1").equals( "VAL1" ) ); + assertTrue( image.xpath("TEMPLATE/ATT2").equals( "VAL2" ) ); + + String new_template = "ATT2 = NEW_VAL\n" + + "ATT3 = VAL3"; + + res = image.update(new_template); + assertTrue( !res.isError() ); + + res = image.info(); assertTrue( !res.isError() ); - assertTrue( image.xpath("TEMPLATE/ATT1").equals("new_val_1") ); - - // Create a new att. - res = image.update("ATT2", "new_val_2"); - assertTrue( !res.isError() ); - - res = image.info(); - assertTrue( !res.isError() ); - assertTrue( image.xpath("TEMPLATE/ATT2").equals("new_val_2") ); + assertTrue( image.xpath("TEMPLATE/ATT1").equals( "" ) ); + assertTrue( image.xpath("TEMPLATE/ATT2").equals( "NEW_VAL" ) ); + assertTrue( image.xpath("TEMPLATE/ATT3").equals( "VAL3" ) ); } - @Test - public void rmattr() - { - res = image.rmattr("ATT1"); - assertTrue( !res.isError() ); - - res = image.info(); - assertTrue( !res.isError() ); - - assertTrue( image.xpath("ATT1").equals("") ); - } // TODO // @Test @@ -203,13 +196,13 @@ public class ImageTest assertTrue( image.xpath("NAME").equals("test_img_"+cont) ); } -// @Test + @Test public void delete() { res = image.delete(); assertTrue( !res.isError() ); - res = image.info(); - assertTrue( res.isError() ); +// res = image.info(); +// assertTrue( res.isError() ); } } diff --git a/src/oca/java/test/TemplateTest.java b/src/oca/java/test/TemplateTest.java index 9d97769798..3513a85ecc 100644 --- a/src/oca/java/test/TemplateTest.java +++ b/src/oca/java/test/TemplateTest.java @@ -22,7 +22,9 @@ import org.junit.BeforeClass; import org.junit.Test; import org.opennebula.client.Client; import org.opennebula.client.OneResponse; +import org.opennebula.client.group.Group; import org.opennebula.client.template.*; +import org.opennebula.client.user.User; import org.opennebula.client.vm.VirtualMachine; @@ -41,7 +43,8 @@ public class TemplateTest private static String template_str = "NAME = \"" + name + "\"\n" + - "ATT1 = \"val1\""; + "ATT1 = \"VAL1\"\n" + + "ATT2 = \"VAL2\""; /** * @throws java.lang.Exception @@ -119,33 +122,24 @@ public class TemplateTest @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("") ); + assertTrue( template.xpath("TEMPLATE/ATT1").equals( "VAL1" ) ); + assertTrue( template.xpath("TEMPLATE/ATT2").equals( "VAL2" ) ); + + String new_template = "ATT2 = NEW_VAL\n" + + "ATT3 = VAL3"; + + res = template.update(new_template); + assertTrue( !res.isError() ); + + + res = template.info(); + assertTrue( !res.isError() ); + assertTrue( template.xpath("TEMPLATE/ATT1").equals( "" ) ); + assertTrue( template.xpath("TEMPLATE/ATT2").equals( "NEW_VAL" ) ); + assertTrue( template.xpath("TEMPLATE/ATT3").equals( "VAL3" ) ); } @Test @@ -191,11 +185,64 @@ public class TemplateTest @Test public void allocateFromTemplate() { - template.info(); + res = template.info(); assertTrue( !res.isError() ); res = VirtualMachine.allocateFromTemplate(client, template); assertTrue( !res.isError() ); assertTrue( res.getMessage().equals("0") ); } + + @Test + public void chown() + { + // Create a new User and Group + res = User.allocate(client, "template_test_user", "password"); + assertTrue( !res.isError() ); + + int uid = Integer.parseInt(res.getMessage()); + + res = Group.allocate(client, "template_test_group"); + assertTrue( !res.isError() ); + + int gid = Integer.parseInt(res.getMessage()); + + res = template.info(); + assertTrue( !res.isError() ); + + assertTrue( template.uid() == 0 ); + assertTrue( template.gid() == 0 ); + + res = template.chown(uid, gid); + assertTrue( !res.isError() ); + + res = template.info(); + assertTrue( !res.isError() ); + + assertTrue( template.uid() == uid ); + assertTrue( template.gid() == gid ); + + res = template.chgrp(0); + + res = template.info(); + assertTrue( !res.isError() ); + + assertTrue( template.uid() == uid ); + assertTrue( template.gid() == 0 ); + } + + @Test + public void instantiate() + { + res = template.instantiate("new_vm_name"); + assertTrue( !res.isError() ); + + int vm_id = Integer.parseInt(res.getMessage()); + VirtualMachine vm = new VirtualMachine(vm_id, client); + + res = vm.info(); + assertTrue( !res.isError() ); + + assertTrue( vm.getName().equals( "new_vm_name" ) ); + } } diff --git a/src/oca/java/test/all_tests.sh b/src/oca/java/test/all_tests.sh index 4b01299520..163a923e51 100755 --- a/src/oca/java/test/all_tests.sh +++ b/src/oca/java/test/all_tests.sh @@ -17,11 +17,11 @@ 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 TemplateTest \ No newline at end of file +./test.sh TemplateTest +./test.sh GroupTest \ No newline at end of file diff --git a/src/oca/ruby/OpenNebula.rb b/src/oca/ruby/OpenNebula.rb index f051799ae7..6f1ffa281e 100644 --- a/src/oca/ruby/OpenNebula.rb +++ b/src/oca/ruby/OpenNebula.rb @@ -35,10 +35,10 @@ require 'OpenNebula/User' require 'OpenNebula/UserPool' require 'OpenNebula/Host' require 'OpenNebula/HostPool' -require 'OpenNebula/Cluster' -require 'OpenNebula/ClusterPool' require 'OpenNebula/Template' require 'OpenNebula/TemplatePool' +require 'OpenNebula/Group' +require 'OpenNebula/GroupPool' module OpenNebula diff --git a/src/oca/ruby/OpenNebula/Cluster.rb b/src/oca/ruby/OpenNebula/Group.rb similarity index 54% rename from src/oca/ruby/OpenNebula/Cluster.rb rename to src/oca/ruby/OpenNebula/Group.rb index 24915fe6b1..aa6ff79291 100644 --- a/src/oca/ruby/OpenNebula/Cluster.rb +++ b/src/oca/ruby/OpenNebula/Group.rb @@ -17,33 +17,31 @@ require 'OpenNebula/Pool' module OpenNebula - class Cluster < PoolElement + class Group < PoolElement # --------------------------------------------------------------------- # Constants and Class Methods # --------------------------------------------------------------------- - CLUSTER_METHODS = { - :info => "cluster.info", - :allocate => "cluster.allocate", - :delete => "cluster.delete", - :addhost => "cluster.add", - :removehost => "cluster.remove", + GROUP_METHODS = { + :info => "group.info", + :allocate => "group.allocate", + :delete => "group.delete" } - # Creates a Cluster description with just its identifier - # this method should be used to create plain Cluster objects. + # Creates a Group description with just its identifier + # this method should be used to create plain Group objects. # +id+ the id of the user # # Example: - # cluster = Cluster.new(User.build_xml(3),rpc_client) + # group = Group.new(Group.build_xml(3),rpc_client) # - def Cluster.build_xml(pe_id=nil) + def Group.build_xml(pe_id=nil) if pe_id - user_xml = "#{pe_id}" + group_xml = "#{pe_id}" else - user_xml = "" + group_xml = "" end - XMLElement.build_xml(user_xml,'CLUSTER') + XMLElement.build_xml(group_xml,'GROUP') end # --------------------------------------------------------------------- @@ -56,48 +54,44 @@ module OpenNebula end # --------------------------------------------------------------------- - # XML-RPC Methods for the User Object + # XML-RPC Methods for the Group Object # --------------------------------------------------------------------- - - # Retrieves the information of the given Cluster. + + # Retrieves the information of the given Group. def info() - super(CLUSTER_METHODS[:info], 'CLUSTER') + super(GROUP_METHODS[:info], 'GROUP') end - # Allocates a new Cluster in OpenNebula + # Allocates a new Group in OpenNebula # - # +clustername+ A string containing the name of the Cluster. - def allocate(clustername) - super(CLUSTER_METHODS[:allocate], clustername) + # +groupname+ A string containing the name of the Group. + def allocate(groupname) + super(GROUP_METHODS[:allocate], groupname) end - # Deletes the Cluster + # Deletes the Group def delete() - super(CLUSTER_METHODS[:delete]) + super(GROUP_METHODS[:delete]) end - # Add a host to the cluster - # - # +host_id+ ID of the Host to be added to the Cluster - def add_host(host_id) - return Error.new('ID not defined') if !@pe_id + # --------------------------------------------------------------------- + # Helpers to get information + # --------------------------------------------------------------------- - rc = @client.call(CLUSTER_METHODS[:addhost], host_id.to_i, @pe_id) - rc = nil if !OpenNebula.is_error?(rc) - - return rc + # Returns whether or not the user with id 'uid' is part of this group + def contains(uid) + return self["USERS/ID[.=#{uid}]"] != nil end - # Remove a host from the cluster - # - # +host_id+ ID of the Host to be removed from the Cluster - def remove_host(host_id) - return Error.new('ID not defined') if !@pe_id + # Returns an array with the numeric user ids + def user_ids + array = Array.new - rc = @client.call(CLUSTER_METHODS[:removehost], host_id.to_i) - rc = nil if !OpenNebula.is_error?(rc) + self.each("USERS/ID") do |id| + array << id.text.to_i + end - return rc + return array end end end diff --git a/src/oca/ruby/OpenNebula/ClusterPool.rb b/src/oca/ruby/OpenNebula/GroupPool.rb similarity index 86% rename from src/oca/ruby/OpenNebula/ClusterPool.rb rename to src/oca/ruby/OpenNebula/GroupPool.rb index 7c1cab6e31..591889bd4f 100644 --- a/src/oca/ruby/OpenNebula/ClusterPool.rb +++ b/src/oca/ruby/OpenNebula/GroupPool.rb @@ -17,36 +17,36 @@ require 'OpenNebula/Pool' module OpenNebula - class ClusterPool < Pool + class GroupPool < Pool # --------------------------------------------------------------------- # Constants and Class attribute accessors # --------------------------------------------------------------------- - CLUSTER_POOL_METHODS = { - :info => "clusterpool.info" + GROUP_POOL_METHODS = { + :info => "grouppool.info" } # --------------------------------------------------------------------- # Class constructor & Pool Methods # --------------------------------------------------------------------- - + # +client+ a Client object that represents a XML-RPC connection def initialize(client) - super('CLUSTER_POOL','CLUSTER',client) + super('GROUP_POOL','GROUP',client) end # Factory method to create User objects def factory(element_xml) - OpenNebula::Cluster.new(element_xml,@client) + OpenNebula::Group.new(element_xml,@client) end # --------------------------------------------------------------------- # XML-RPC Methods for the User Object # --------------------------------------------------------------------- - - # Retrieves all the Clusters in the pool. + + # Retrieves all the Groups in the pool. def info() - super(CLUSTER_POOL_METHODS[:info]) + super(GROUP_POOL_METHODS[:info]) end end end \ No newline at end of file diff --git a/src/oca/ruby/OpenNebula/Host.rb b/src/oca/ruby/OpenNebula/Host.rb index 40b8f36c1f..173d772111 100644 --- a/src/oca/ruby/OpenNebula/Host.rb +++ b/src/oca/ruby/OpenNebula/Host.rb @@ -121,12 +121,6 @@ module OpenNebula SHORT_HOST_STATES[state_str] end - # Returns the cluster of the Host - def cluster - self['CLUSTER'] - end - - private def set_enabled(enabled) return Error.new('ID not defined') if !@pe_id diff --git a/src/oca/ruby/OpenNebula/Image.rb b/src/oca/ruby/OpenNebula/Image.rb index 224f7b2d27..0b49d943cc 100644 --- a/src/oca/ruby/OpenNebula/Image.rb +++ b/src/oca/ruby/OpenNebula/Image.rb @@ -26,11 +26,11 @@ module OpenNebula :info => "image.info", :allocate => "image.allocate", :update => "image.update", - :rmattr => "image.rmattr", :enable => "image.enable", :publish => "image.publish", :persistent => "image.persistent", - :delete => "image.delete" + :delete => "image.delete", + :chown => "image.chown" } IMAGE_STATES=%w{INIT READY USED DISABLED LOCKED ERROR} @@ -92,20 +92,11 @@ module OpenNebula super(IMAGE_METHODS[:allocate],description) end - # Modifies an image attribute + # Replaces the template contents # - # +name+ Name of the attribute to be changed - # - # +value+ New value for the attribute - def update(name, value) - super(IMAGE_METHODS[:update], name, value) - end - - # Deletes an Image attribute - # - # +name+ Name of the attribute to be deleted - def remove_attr(name) - do_rm_attr(name) + # +new_template+ New template contents + def update(new_template) + super(IMAGE_METHODS[:update], new_template) end # Enables an Image @@ -142,7 +133,14 @@ module OpenNebula def delete() super(IMAGE_METHODS[:delete]) end - + + # Changes the owner/group + # uid:: _Integer_ the new owner id. Set to -1 to leave the current one + # gid:: _Integer_ the new group id. Set to -1 to leave the current one + # [return] nil in case of success or an Error object + def chown(uid, gid) + super(IMAGE_METHODS[:chown], uid, gid) + end ####################################################################### # Helpers to get Image information @@ -178,6 +176,12 @@ module OpenNebula SHORT_IMAGE_TYPES[type_str] end + # Returns the group identifier + # [return] _Integer_ the element's group ID + def gid + self['GID'].to_i + end + private def set_enabled(enabled) @@ -206,15 +210,5 @@ module OpenNebula return rc end - - def do_rm_attr(name) - return Error.new('ID not defined') if !@pe_id - - rc = @client.call(IMAGE_METHODS[:rmattr], @pe_id, name) - rc = nil if !OpenNebula.is_error?(rc) - - return rc - end - end end diff --git a/src/oca/ruby/OpenNebula/Pool.rb b/src/oca/ruby/OpenNebula/Pool.rb index fa82de6cb2..30fa180c51 100644 --- a/src/oca/ruby/OpenNebula/Pool.rb +++ b/src/oca/ruby/OpenNebula/Pool.rb @@ -148,13 +148,12 @@ module OpenNebula # Calls to the corresponding update method to modify # the object's template # xml_method:: _String_ the name of the XML-RPC method - # name:: _String_ the name of the property to be modified - # value:: _String_ the new value of the property to be modified + # new_template:: _String_ the new template contents # [return] nil in case of success or an Error object - def update(xml_method, name, value) + def update(xml_method, new_template) return Error.new('ID not defined') if !@pe_id - rc = @client.call(xml_method,@pe_id, name, value) + rc = @client.call(xml_method,@pe_id, new_template) rc = nil if !OpenNebula.is_error?(rc) return rc @@ -173,6 +172,21 @@ module OpenNebula return rc end + # Calls to the corresponding chown method to modify + # the object's owner and group + # xml_method:: _String_ the name of the XML-RPC method + # uid:: _Integer_ the new owner id. Set to -1 to leave the current one + # gid:: _Integer_ the new group id. Set to -1 to leave the current one + # [return] nil in case of success or an Error object + def chown(xml_method, uid, gid) + return Error.new('ID not defined') if !@pe_id + + rc = @client.call(xml_method,@pe_id, uid, gid) + rc = nil if !OpenNebula.is_error?(rc) + + return rc + end + public # Creates new element specifying its id diff --git a/src/oca/ruby/OpenNebula/Template.rb b/src/oca/ruby/OpenNebula/Template.rb index 5c8b758da6..ffb099edd4 100644 --- a/src/oca/ruby/OpenNebula/Template.rb +++ b/src/oca/ruby/OpenNebula/Template.rb @@ -23,11 +23,12 @@ module OpenNebula # --------------------------------------------------------------------- TEMPLATE_METHODS = { :allocate => "template.allocate", + :instantiate => "template.instantiate", :info => "template.info", :update => "template.update", - :rmattr => "template.rmattr", :publish => "template.publish", - :delete => "template.delete" + :delete => "template.delete", + :chown => "template.chown" } # Creates a Template description with just its identifier @@ -77,20 +78,25 @@ module OpenNebula super(TEMPLATE_METHODS[:delete]) end - # Modifies a template attribute + # Creates a VM instance from a Template # - # +name+ Name of the attribute to be changed - # - # +value+ New value for the attribute - def update(name, value) - super(TEMPLATE_METHODS[:update], name, value) + # +name+ A string containing the name of the VM instance. + # [return] The new VM Instance ID, or an Error object + def instantiate(name="") + return Error.new('ID not defined') if !@pe_id + + rc = @client.call(TEMPLATE_METHODS[:instantiate], @pe_id, name) + + return rc end - # Deletes a template attribute + # Replaces the template contents # - # +name+ Name of the attribute to be deleted - def remove_attr(name) - do_rm_attr(name) + # +new_template+ New template contents + def update(new_template) + return Error.new('ID not defined') if !@pe_id + + super(TEMPLATE_METHODS[:update], new_template) end # Publishes the Template, to be used by other users @@ -103,6 +109,28 @@ module OpenNebula set_publish(false) end + # Changes the owner/group + # uid:: _Integer_ the new owner id. Set to -1 to leave the current one + # gid:: _Integer_ the new group id. Set to -1 to leave the current one + # [return] nil in case of success or an Error object + def chown(uid, gid) + super(TEMPLATE_METHODS[:chown], uid, gid) + end + + # --------------------------------------------------------------------- + # Helpers to get Template information + # --------------------------------------------------------------------- + + # Returns the group identifier + # [return] _Integer_ the element's group ID + def gid + self['GID'].to_i + end + + def owner_id + self['UID'].to_i + end + private def set_publish(published) @@ -113,14 +141,5 @@ module OpenNebula 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 diff --git a/src/oca/ruby/OpenNebula/User.rb b/src/oca/ruby/OpenNebula/User.rb index 071447c6e5..6e7c5555b9 100644 --- a/src/oca/ruby/OpenNebula/User.rb +++ b/src/oca/ruby/OpenNebula/User.rb @@ -25,7 +25,10 @@ module OpenNebula :info => "user.info", :allocate => "user.allocate", :delete => "user.delete", - :passwd => "user.passwd" + :passwd => "user.passwd", + :chgrp => "user.chgrp", + :addgroup => "user.addgroup", + :delgroup => "user.delgroup" } # Creates a User description with just its identifier @@ -89,5 +92,66 @@ module OpenNebula return rc end + # Changes the main group + # gid:: _Integer_ the new group id. Set to -1 to leave the current one + # [return] nil in case of success or an Error object + def chgrp(gid) + return Error.new('ID not defined') if !@pe_id + + rc = @client.call(USER_METHODS[:chgrp],@pe_id, gid) + rc = nil if !OpenNebula.is_error?(rc) + + return rc + end + + # Adds a secondary group + # gid:: _Integer_ the new group id. + # [return] nil in case of success or an Error object + def addgroup(gid) + return Error.new('ID not defined') if !@pe_id + + rc = @client.call(USER_METHODS[:addgroup], @pe_id, gid) + rc = nil if !OpenNebula.is_error?(rc) + + return rc + end + + # Deletes a secondary group. Fails if the group is the main one + # gid:: _Integer_ the group id. + # [return] nil in case of success or an Error object + def delgroup(gid) + return Error.new('ID not defined') if !@pe_id + + rc = @client.call(USER_METHODS[:delgroup], @pe_id, gid) + rc = nil if !OpenNebula.is_error?(rc) + + return rc + end + + # --------------------------------------------------------------------- + # Helpers to get User information + # --------------------------------------------------------------------- + + # Returns the group identifier + # [return] _Integer_ the element's group ID + def gid + self['GID'].to_i + end + + # Returns whether or not the user is part of the group 'gid' + def is_part_of(gid) + return self["GROUPS/ID[.=#{gid}]"] != nil + end + + # Returns an array with the numeric group ids + def group_ids + array = Array.new + + self.each("GROUPS/ID") do |id| + array << id.text.to_i + end + + return array + end end end diff --git a/src/oca/ruby/OpenNebula/VirtualMachine.rb b/src/oca/ruby/OpenNebula/VirtualMachine.rb index 29effeefc2..c2292bc6a4 100644 --- a/src/oca/ruby/OpenNebula/VirtualMachine.rb +++ b/src/oca/ruby/OpenNebula/VirtualMachine.rb @@ -27,7 +27,8 @@ module OpenNebula :action => "vm.action", :migrate => "vm.migrate", :deploy => "vm.deploy", - :savedisk => "vm.savedisk" + :savedisk => "vm.savedisk", + :chown => "vm.chown" } VM_STATE=%w{INIT PENDING HOLD ACTIVE STOPPED SUSPENDED DONE FAILED} @@ -224,6 +225,14 @@ module OpenNebula return rc end + # Changes the owner/group + # uid:: _Integer_ the new owner id. Set to -1 to leave the current one + # gid:: _Integer_ the new group id. Set to -1 to leave the current one + # [return] nil in case of success or an Error object + def chown(uid, gid) + super(VM_METHODS[:chown], uid, gid) + end + ####################################################################### # Helpers to get VirtualMachine information ####################################################################### @@ -259,6 +268,12 @@ module OpenNebula short_state_str end + # Returns the group identifier + # [return] _Integer_ the element's group ID + def gid + self['GID'].to_i + end + private def action(name) return Error.new('ID not defined') if !@pe_id diff --git a/src/oca/ruby/OpenNebula/VirtualNetwork.rb b/src/oca/ruby/OpenNebula/VirtualNetwork.rb index b12a5d8d69..030c7036d3 100644 --- a/src/oca/ruby/OpenNebula/VirtualNetwork.rb +++ b/src/oca/ruby/OpenNebula/VirtualNetwork.rb @@ -27,7 +27,8 @@ module OpenNebula :publish => "vn.publish", :delete => "vn.delete", :addleases => "vn.addleases", - :rmleases => "vn.rmleases" + :rmleases => "vn.rmleases", + :chown => "vn.chown" } # Creates a VirtualNetwork description with just its identifier @@ -111,6 +112,24 @@ module OpenNebula return rc end + # Changes the owner/group + # uid:: _Integer_ the new owner id. Set to -1 to leave the current one + # gid:: _Integer_ the new group id. Set to -1 to leave the current one + # [return] nil in case of success or an Error object + def chown(uid, gid) + super(VN_METHODS[:chown], uid, gid) + end + + # --------------------------------------------------------------------- + # Helpers to get VirtualNetwork information + # --------------------------------------------------------------------- + + # Returns the group identifier + # [return] _Integer_ the element's group ID + def gid + self['GID'].to_i + end + private def set_publish(published) return Error.new('ID not defined') if !@pe_id diff --git a/src/oca/ruby/test/ClusterPool_spec.rb b/src/oca/ruby/test/ClusterPool_spec.rb deleted file mode 100644 index fd30f0fdb3..0000000000 --- a/src/oca/ruby/test/ClusterPool_spec.rb +++ /dev/null @@ -1,61 +0,0 @@ -$: << '../' - -require 'OpenNebula' -require 'helpers/MockClient' - -module OpenNebula - - describe "Cluster using NOKOGIRI" do - before(:all) do - NOKOGIRI=true - - client = MockClient.new() - @cluster_pool = ClusterPool.new(client) - end - - it "should update the CLUSTER_POOL info" do - rc = @cluster_pool.info() - rc.nil?.should eql(true) - end - - it "should iterate the USER_POOL elements and get info from them" do - rc = @cluster_pool.each{ |cluster| - cluster.class.to_s.should eql("OpenNebula::Cluster") - if cluster.id == 0 - cluster.name.should eql('default') - elsif cluster.id == 1 - cluster.name.should eql('Red') - elsif cluster.id == 2 - cluster.name.should eql('Black') - end - } - end - end - - describe "Cluster using REXML" do - before(:all) do - NOKOGIRI=false - - client = MockClient.new() - @cluster_pool = ClusterPool.new(client) - end - - it "should update the CLUSTER_POOL info" do - rc = @cluster_pool.info() - rc.nil?.should eql(true) - end - - it "should iterate the CLUSTER_POOL elements and get info from them" do - rc = @cluster_pool.each{ |cluster| - cluster.class.to_s.should eql("OpenNebula::Cluster") - if cluster.id == 0 - cluster.name.should eql('default') - elsif cluster.id == 1 - cluster.name.should eql('Red') - elsif cluster.id == 2 - cluster.name.should eql('Black') - end - } - end - end -end \ No newline at end of file diff --git a/src/oca/ruby/test/Cluster_spec.rb b/src/oca/ruby/test/Cluster_spec.rb deleted file mode 100644 index bb2a30889a..0000000000 --- a/src/oca/ruby/test/Cluster_spec.rb +++ /dev/null @@ -1,189 +0,0 @@ -$: << '../' - -require 'OpenNebula' -require 'helpers/MockClient' - -module OpenNebula - - describe "Cluster using NOKOGIRI" do - before(:all) do - NOKOGIRI=true - - @xml = Cluster.build_xml(5) - - client = MockClient.new() - @cluster = Cluster.new(@xml,client) - end - - it "should create a Nokogiri Node" do - @xml.class.to_s.should eql('Nokogiri::XML::NodeSet') - end - - it "should allocate the new CLUSTER" do - @cluster.allocate(nil) - - @cluster.id.should eql(5) - end - - it "should update the CLUSTER info" do - @cluster.info() - - @cluster.id.should eql(5) - @cluster.name.should eql('Production') - end - - it "should delete the CLUSTER" do - rc = @cluster.delete() - - rc.should eql(nil) - end - - it "should add a host to the CLUSTER" do - rc = @cluster.add_host(nil) - - rc.should eql(nil) - end - - it "should remove a host from the CLUSTER" do - rc = @cluster.remove_host(nil) - - rc.should eql(nil) - end - - it "should access an attribute using []" do - @cluster['ID'].should eql('5') - @cluster['NAME'].should eql('Production') - end - end - - describe "Cluster using REXML" do - before(:all) do - NOKOGIRI=false - - @xml = Cluster.build_xml(5) - - client = MockClient.new() - @cluster = Cluster.new(@xml,client) - end - - it "should create a REXML Element" do - @xml.class.to_s.should eql('REXML::Element') - end - - it "should allocate the new CLUSTER" do - @cluster.allocate(nil) - - @cluster.id.should eql(5) - end - - it "should update the CLUSTER info" do - @cluster.info() - - @cluster.id.should eql(5) - @cluster.name.should eql('Production') - end - - it "should delete the CLUSTER" do - rc = @cluster.delete() - - rc.should eql(nil) - end - - it "should add a host to the CLUSTER" do - rc = @cluster.add_host(nil) - - rc.should eql(nil) - end - - it "should remove a host from the CLUSTER" do - rc = @cluster.remove_host(nil) - - rc.should eql(nil) - end - - it "should access an attribute using []" do - @cluster['ID'].should eql('5') - @cluster['NAME'].should eql('Production') - end - end - - - describe "Cluster using NOKOGIRI without id" do - before(:all) do - NOKOGIRI=true - - @xml = Cluster.build_xml() - - client = MockClient.new() - @cluster = Cluster.new(@xml,client) - end - - it "should create a Nokogiri Node" do - @xml.class.to_s.should eql('Nokogiri::XML::NodeSet') - end - - it "should get Error getting info" do - rc = @cluster.info() - - OpenNebula.is_error?(rc).should eql(true) - end - - it "should get Error deleting the CLUSTER" do - rc = @cluster.delete() - - OpenNebula.is_error?(rc).should eql(true) - end - - it "should add a host to the CLUSTER" do - rc = @cluster.add_host(nil) - - OpenNebula.is_error?(rc).should eql(true) - end - - it "should remove a host from the CLUSTER" do - rc = @cluster.remove_host(nil) - - OpenNebula.is_error?(rc).should eql(true) - end - end - - describe "User using REXML without id" do - before(:all) do - NOKOGIRI=false - - @xml = Cluster.build_xml() - - client = MockClient.new() - @cluster = Cluster.new(@xml,client) - end - - it "should create a REXML Element" do - @xml.class.to_s.should eql('REXML::Element') - end - - it "should get Error getting info" do - rc = @cluster.info() - - OpenNebula.is_error?(rc).should eql(true) - end - - it "should get Error deleting the CLUSTER" do - rc = @cluster.delete() - - OpenNebula.is_error?(rc).should eql(true) - end - - it "should add a host to the CLUSTER" do - rc = @cluster.add_host(nil) - - OpenNebula.is_error?(rc).should eql(true) - end - - it "should remove a host from the CLUSTER" do - rc = @cluster.remove_host(nil) - - OpenNebula.is_error?(rc).should eql(true) - end - end - -end \ No newline at end of file diff --git a/src/oca/ruby/test/fixtures/cluster.xml b/src/oca/ruby/test/fixtures/cluster.xml deleted file mode 100644 index 96bd351ce3..0000000000 --- a/src/oca/ruby/test/fixtures/cluster.xml +++ /dev/null @@ -1,4 +0,0 @@ - - 5 - Production - \ No newline at end of file diff --git a/src/oca/ruby/test/fixtures/clusterpool.xml b/src/oca/ruby/test/fixtures/clusterpool.xml deleted file mode 100644 index 628d454004..0000000000 --- a/src/oca/ruby/test/fixtures/clusterpool.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - 0 - default - - - 1 - Red - - - 2 - Black - - \ No newline at end of file diff --git a/src/oca/ruby/test/helpers/MockClient.rb b/src/oca/ruby/test/helpers/MockClient.rb index d119eb552a..fd7a7bf5a9 100644 --- a/src/oca/ruby/test/helpers/MockClient.rb +++ b/src/oca/ruby/test/helpers/MockClient.rb @@ -36,16 +36,6 @@ class MockClient return File.read("fixtures/user.xml") when "one.user.delete" return nil - when "one.cluster.allocate" - return 5 - when "one.cluster.info" - return File.read("fixtures/cluster.xml") - when "one.cluster.delete" - return nil - when "one.cluster.addhost" - return nil - when "one.cluster.removehost" - return nil when "one.vnpool.info" return File.read("fixtures/vnetpool.xml") when "one.vmpool.info" @@ -54,8 +44,6 @@ class MockClient return File.read("fixtures/hostpool.xml") when "one.userpool.info" return File.read("fixtures/userpool.xml") - when "one.clusterpool.info" - return File.read("fixtures/clusterpool.xml") end end end \ No newline at end of file diff --git a/src/onedb/1.rb b/src/onedb/1.rb index a4aaf2a854..29239ee339 100644 --- a/src/onedb/1.rb +++ b/src/onedb/1.rb @@ -36,12 +36,22 @@ class Migrator < MigratorBase # Create new user_pool @db.run "CREATE TABLE user_pool (oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, UNIQUE(name));" + user_group_ids = "" + # Read each entry in the old user_pool, and insert into new user_pool @db.fetch("SELECT * FROM old_user_pool") do |row| oid = row[:oid] + + if( oid == 0 ) + gid = 0 + else + gid = 1 + user_group_ids += "#{oid}" + end + name = row[:user_name] - body = "#{oid}#{name}#{row[:password]}#{row[:enabled]}" + body = "#{oid}#{gid}#{name}#{row[:password]}#{row[:enabled]}#{gid}" @db.run "INSERT INTO user_pool VALUES(#{oid},'#{name}','#{body}');" end @@ -49,6 +59,54 @@ class Migrator < MigratorBase # Delete old user_pool @db.run "DROP TABLE old_user_pool" + ######################################################################## + # Hosts + ######################################################################## + + # 2.2 Schema + # CREATE TABLE host_pool (oid INTEGER PRIMARY KEY,host_name VARCHAR(256), state INTEGER,im_mad VARCHAR(128),vm_mad VARCHAR(128),tm_mad VARCHAR(128),last_mon_time INTEGER, cluster VARCHAR(128), template TEXT, UNIQUE(host_name)); + # CREATE TABLE host_shares(hid INTEGER PRIMARY KEY,disk_usage INTEGER, mem_usage INTEGER, cpu_usage INTEGER,max_disk INTEGER, max_mem INTEGER, max_cpu INTEGER,free_disk INTEGER, free_mem INTEGER, free_cpu INTEGER,used_disk INTEGER, used_mem INTEGER, used_cpu INTEGER,running_vms INTEGER); + + # Move table + @db.run "ALTER TABLE host_pool RENAME TO old_host_pool;" + + # Create new table + @db.run "CREATE TABLE host_pool (oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, state INTEGER, last_mon_time INTEGER, cid INTEGER, UNIQUE(name));" + + cluster_host_ids = Hash.new + + # Read each entry in the old table, and insert into new table + @db.fetch("SELECT * FROM old_host_pool") do |row| + oid = row[:oid] + name = row[:host_name] + state = row[:state] + last_mon_time = row[:last_mon_time] + cluster = row[:cluster] + + # OpenNebula 2.X stored the cluster name, we need the cluster ID + cluster_id = 0 + @db.fetch("SELECT oid FROM cluster_pool WHERE cluster_name='#{cluster}'") do |cluster_row| + cluster_id = cluster_row[:oid] + + cluster_host_ids[cluster_id] = "" if cluster_host_ids[cluster_id] == nil + cluster_host_ids[cluster_id] += "#{oid}" + end + + # There is one host share for each host + host_share = "" + @db.fetch("SELECT * FROM host_shares WHERE hid=#{oid}") do |share| + host_share = "#{share[:disk_usage]}#{share[:mem_usage]}#{share[:cpu_usage]}#{share[:max_disk]}#{share[:max_mem]}#{share[:max_cpu]}#{share[:free_disk]}#{share[:free_mem]}#{share[:free_cpu]}#{share[:used_disk]}#{share[:used_mem]}#{share[:used_cpu]}#{share[:running_vms]}" + end + + body = "#{oid}#{name}#{state}#{row[:im_mad]}#{row[:vm_mad]}#{row[:tm_mad]}#{last_mon_time}#{cluster_id}#{host_share}#{row[:template]}" + + @db.run "INSERT INTO host_pool VALUES(#{oid},'#{name}','#{body}', #{state}, #{last_mon_time}, #{cluster_id});" + end + + # Delete old table + @db.run "DROP TABLE old_host_pool" + @db.run "DROP TABLE host_shares" + ######################################################################## # Clusters ######################################################################## @@ -67,7 +125,12 @@ class Migrator < MigratorBase oid = row[:oid] name = row[:cluster_name] - body = "#{oid}#{name}" + hids = "" + if cluster_host_ids[oid] != nil + hids = cluster_host_ids[oid] + end + + body = "#{oid}#{name}#{hids}" @db.run "INSERT INTO cluster_pool VALUES(#{oid},'#{name}','#{body}');" end @@ -75,43 +138,6 @@ class Migrator < MigratorBase # Delete old table @db.run "DROP TABLE old_cluster_pool" - ######################################################################## - # Hosts - ######################################################################## - - # 2.2 Schema - # CREATE TABLE host_pool (oid INTEGER PRIMARY KEY,host_name VARCHAR(256), state INTEGER,im_mad VARCHAR(128),vm_mad VARCHAR(128),tm_mad VARCHAR(128),last_mon_time INTEGER, cluster VARCHAR(128), template TEXT, UNIQUE(host_name)); - # CREATE TABLE host_shares(hid INTEGER PRIMARY KEY,disk_usage INTEGER, mem_usage INTEGER, cpu_usage INTEGER,max_disk INTEGER, max_mem INTEGER, max_cpu INTEGER,free_disk INTEGER, free_mem INTEGER, free_cpu INTEGER,used_disk INTEGER, used_mem INTEGER, used_cpu INTEGER,running_vms INTEGER); - - # Move table - @db.run "ALTER TABLE host_pool RENAME TO old_host_pool;" - - # Create new table - @db.run "CREATE TABLE host_pool (oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, state INTEGER, last_mon_time INTEGER, cluster VARCHAR(128), UNIQUE(name));" - - # Read each entry in the old table, and insert into new table - @db.fetch("SELECT * FROM old_host_pool") do |row| - oid = row[:oid] - name = row[:host_name] - state = row[:state] - last_mon_time = row[:last_mon_time] - cluster = row[:cluster] - - # There is one host share for each host - host_share = "" - @db.fetch("SELECT * FROM host_shares WHERE hid=#{oid}") do |share| - host_share = "#{share[:disk_usage]}#{share[:mem_usage]}#{share[:cpu_usage]}#{share[:max_disk]}#{share[:max_mem]}#{share[:max_cpu]}#{share[:free_disk]}#{share[:free_mem]}#{share[:free_cpu]}#{share[:used_disk]}#{share[:used_mem]}#{share[:used_cpu]}#{share[:running_vms]}" - end - - body = "#{oid}#{name}#{state}#{row[:im_mad]}#{row[:vm_mad]}#{row[:tm_mad]}#{last_mon_time}#{cluster}#{host_share}#{row[:template]}" - - @db.run "INSERT INTO host_pool VALUES(#{oid},'#{name}','#{body}', #{state}, #{last_mon_time}, '#{cluster}');" - end - - # Delete old table - @db.run "DROP TABLE old_host_pool" - @db.run "DROP TABLE host_shares" - ######################################################################## # Images ######################################################################## @@ -123,22 +149,21 @@ class Migrator < MigratorBase @db.run "ALTER TABLE image_pool RENAME TO old_image_pool;" # Create new table - @db.run "CREATE TABLE image_pool (oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, uid INTEGER, public INTEGER, UNIQUE(name,uid) );" + @db.run "CREATE TABLE image_pool (oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, uid INTEGER, gid INTEGER, public INTEGER, UNIQUE(name,uid) );" # Read each entry in the old table, and insert into new table @db.fetch("SELECT * FROM old_image_pool") do |row| oid = row[:oid] name = row[:name] uid = row[:uid] + gid = (uid == 0) ? 0 : 1 public = row[:public] - username = get_username(uid) - # In OpenNebula 2.0 Image States go from 0 to 3, in 3.0 go # from 0 to 5, but the meaning is the same for states 0 to 3 - body = "#{oid}#{row[:uid]}#{username}#{name}#{row[:type]}#{public}#{row[:persistent]}#{row[:regtime]}#{row[:source]}#{row[:state]}#{row[:running_vms]}#{row[:template]}" + body = "#{oid}#{row[:uid]}#{gid}#{name}#{row[:type]}#{public}#{row[:persistent]}#{row[:regtime]}#{row[:source]}#{row[:state]}#{row[:running_vms]}#{row[:template]}" - @db.run "INSERT INTO image_pool VALUES(#{oid},'#{name}','#{body}', #{uid}, #{public});" + @db.run "INSERT INTO image_pool VALUES(#{oid},'#{name}','#{body}', #{uid}, #{gid}, #{public});" end # Delete old table @@ -157,7 +182,7 @@ class Migrator < MigratorBase @db.run "ALTER TABLE history RENAME TO old_history;" # Create new tables - @db.run "CREATE TABLE vm_pool (oid INTEGER PRIMARY KEY, name TEXT, body TEXT, uid INTEGER, last_poll INTEGER, state INTEGER, lcm_state INTEGER);" + @db.run "CREATE TABLE vm_pool (oid INTEGER PRIMARY KEY, name TEXT, body TEXT, uid INTEGER, gid INTEGER, last_poll INTEGER, state INTEGER, lcm_state INTEGER);" @db.run "CREATE TABLE history (vid INTEGER, seq INTEGER, body TEXT, PRIMARY KEY(vid,seq));" @@ -177,21 +202,20 @@ class Migrator < MigratorBase oid = row[:oid] name = row[:name] uid = row[:uid] + gid = (uid == 0) ? 0 : 1 last_poll = row[:last_poll] state = row[:state] lcm_state = row[:lcm_state] - username = get_username(uid) - # If the VM has History items, the last one is included in the XML history = "" @db.fetch("SELECT body FROM history WHERE vid=#{oid} AND seq=(SELECT MAX(seq) FROM history WHERE vid=#{oid})") do |history_row| history = history_row[:body] end - body = "#{oid}#{uid}#{username}#{name}#{last_poll}#{state}#{lcm_state}#{row[:stime]}#{row[:etime]}#{row[:deploy_id]}#{row[:memory]}#{row[:cpu]}#{row[:net_tx]}#{row[:net_rx]}#{row[:template]}#{history}" + body = "#{oid}#{uid}#{gid}#{name}#{last_poll}#{state}#{lcm_state}#{row[:stime]}#{row[:etime]}#{row[:deploy_id]}#{row[:memory]}#{row[:cpu]}#{row[:net_tx]}#{row[:net_rx]}#{row[:template]}#{history}" - @db.run "INSERT INTO vm_pool VALUES(#{oid},'#{name}','#{body}', #{uid}, #{last_poll}, #{state}, #{lcm_state});" + @db.run "INSERT INTO vm_pool VALUES(#{oid},'#{name}','#{body}', #{uid}, #{gid}, #{last_poll}, #{state}, #{lcm_state});" end @@ -213,7 +237,7 @@ class Migrator < MigratorBase @db.run "ALTER TABLE leases RENAME TO old_leases;" # Create new tables - @db.run "CREATE TABLE network_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body TEXT, uid INTEGER, public INTEGER, UNIQUE(name,uid));" + @db.run "CREATE TABLE network_pool (oid INTEGER PRIMARY KEY, name VARCHAR(128), body TEXT, uid INTEGER, gid INTEGER, public INTEGER, UNIQUE(name,uid));" @db.run "CREATE TABLE leases (oid INTEGER, ip BIGINT, body TEXT, PRIMARY KEY(oid,ip));" # Read each entry in the old table, and insert into new table @@ -221,16 +245,15 @@ class Migrator < MigratorBase oid = row[:oid] name = row[:name] uid = row[:uid] + gid = (uid == 0) ? 0 : 1 public = row[:public] - username = get_username(uid) - # is stored in the DB, but it is not used to rebuild # the VirtualNetwork object, and it is generated each time the # network is listed. So setting it to 0 is safe - body = "#{oid}#{uid}#{username}#{name}#{row[:type]}#{row[:bridge]}#{public}0#{row[:template]}" + body = "#{oid}#{uid}#{gid}#{name}#{row[:type]}#{row[:bridge]}#{public}0#{row[:template]}" - @db.run "INSERT INTO network_pool VALUES(#{oid},'#{name}','#{body}', #{uid}, #{public});" + @db.run "INSERT INTO network_pool VALUES(#{oid},'#{name}','#{body}', #{uid}, #{gid}, #{public});" end # Read each entry in the old table, and insert into new table @@ -253,7 +276,12 @@ class Migrator < MigratorBase ######################################################################## @db.run "CREATE TABLE db_versioning (oid INTEGER PRIMARY KEY, version INTEGER, timestamp INTEGER, comment VARCHAR(256));" - @db.run "CREATE TABLE template_pool (oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, uid INTEGER, public INTEGER);" + @db.run "CREATE TABLE template_pool (oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, uid INTEGER, gid INTEGER, public INTEGER);" + + # The group pool has two default ones + @db.run "CREATE TABLE group_pool (oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, uid INTEGER, UNIQUE(name));" + @db.run "INSERT INTO group_pool VALUES(0,'oneadmin','00oneadmin0',0);" + @db.run "INSERT INTO group_pool VALUES(1,'users','10users#{user_group_ids}',0);" # New pool_control table contains the last_oid used, must be rebuilt @db.run "CREATE TABLE pool_control (tablename VARCHAR(32) PRIMARY KEY, last_oid BIGINT UNSIGNED)" @@ -266,16 +294,10 @@ class Migrator < MigratorBase end end + # First 100 group Ids are reserved for system groups. + # Regular ones start from ID 100 + @db.run "INSERT INTO pool_control (tablename, last_oid) VALUES ('group_pool', 99);" + return true end - - def get_username(uid) - username = "" - - @db.fetch("SELECT name FROM user_pool WHERE oid=#{uid}") do |user| - username = user[:name] - end - - return username - end end diff --git a/src/pool/ObjectCollection.cc b/src/pool/ObjectCollection.cc new file mode 100644 index 0000000000..ec8da0934c --- /dev/null +++ b/src/pool/ObjectCollection.cc @@ -0,0 +1,105 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "ObjectCollection.h" + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int ObjectCollection::from_xml_node(const xmlNodePtr node) +{ + ObjectXML xml(node); + int rc = 0; + int id; + + vector values; + vector::iterator it; + istringstream iss; + + string xpath_expr = "/" + collection_name + "/ID"; + + values = xml[xpath_expr.c_str()]; + + for ( it = values.begin() ; it < values.end(); it++ ) + { + iss.str(*it); + iss >> dec >> id; + + if ( iss.fail() ) + { + rc = -1; + } + else + { + collection_set.insert(id); + } + } + + return rc; +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +string& ObjectCollection::to_xml(string& xml) const +{ + ostringstream oss; + set::iterator it; + + oss << "<" << collection_name << ">"; + + for ( it = collection_set.begin(); it != collection_set.end(); it++ ) + { + oss << "" << *it << ""; + } + + oss << ""; + + xml = oss.str(); + + return xml; +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int ObjectCollection::add_collection_id(int id) +{ + pair::iterator,bool> ret; + + ret = collection_set.insert(id); + + if( !ret.second ) + { + return -1; + } + + return 0; +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int ObjectCollection::del_collection_id(int id) +{ + if( collection_set.erase(id) != 1 ) + { + return -1; + } + + return 0; +}; + diff --git a/src/pool/PoolObjectSQL.cc b/src/pool/PoolObjectSQL.cc index 3d87a55280..07684932b3 100644 --- a/src/pool/PoolObjectSQL.cc +++ b/src/pool/PoolObjectSQL.cc @@ -162,3 +162,40 @@ void PoolObjectSQL::set_template_error_message(const string& message) /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ +int PoolObjectSQL::replace_template(const string& tmpl_str, string& error) +{ + Template * new_tmpl = get_new_template(); + char * error_msg = 0; + + if ( new_tmpl == 0 ) + { + error = "Can not allocate a new template"; + return -1; + } + + if ( new_tmpl->parse(tmpl_str, &error_msg) != 0 ) + { + ostringstream oss; + + oss << "Parse error"; + + if (error_msg != 0) + { + oss << ": " << error_msg; + } + + error = oss.str(); + + return -1; + } + + delete obj_template; + + obj_template = new_tmpl; + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + diff --git a/src/pool/PoolSQL.cc b/src/pool/PoolSQL.cc index 4e953a138e..6575e06f9d 100644 --- a/src/pool/PoolSQL.cc +++ b/src/pool/PoolSQL.cc @@ -140,12 +140,16 @@ int PoolSQL::allocate( return rc; } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void PoolSQL::update_lastOID() { // db->escape_str is not used for 'table' since its name can't be set in // any way by the user, it is hardcoded. ostringstream oss; + oss << "REPLACE INTO pool_control (tablename, last_oid) VALUES (" << "'" << table << "'," << lastOID << ")"; diff --git a/src/pool/SConstruct b/src/pool/SConstruct index 734ce963e5..a64ea0a7bb 100644 --- a/src/pool/SConstruct +++ b/src/pool/SConstruct @@ -23,7 +23,8 @@ lib_name='nebula_pool' # Sources to generate the library source_files=[ 'PoolSQL.cc', - 'PoolObjectSQL.cc' + 'PoolObjectSQL.cc', + 'ObjectCollection.cc' ] # Build library diff --git a/src/pool/test/SConstruct b/src/pool/test/SConstruct index 085b413a2b..ec0c4d763e 100644 --- a/src/pool/test/SConstruct +++ b/src/pool/test/SConstruct @@ -23,6 +23,7 @@ env.Append(LIBPATH=[ env.Prepend(LIBS=[ 'nebula_pool', + 'nebula_template', 'nebula_xml', 'nebula_common', 'nebula_log', diff --git a/src/pool/test/TestPoolSQL.h b/src/pool/test/TestPoolSQL.h index 0ef0b23cf8..d9eac8a5c2 100644 --- a/src/pool/test/TestPoolSQL.h +++ b/src/pool/test/TestPoolSQL.h @@ -30,7 +30,7 @@ class TestObjectSQL : public PoolObjectSQL { public: //OBJECT ATTRIBUTES - TestObjectSQL(int n=-1, string t="default"):PoolObjectSQL(-1,"",0,0),number(n),text(t){}; + TestObjectSQL(int n=-1, string t="default"):PoolObjectSQL(-1,"",0,0,0),number(n),text(t){}; ~TestObjectSQL(){}; diff --git a/src/rm/Request.cc b/src/rm/Request.cc new file mode 100644 index 0000000000..a204af1e4a --- /dev/null +++ b/src/rm/Request.cc @@ -0,0 +1,296 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "Request.h" +#include "Nebula.h" + + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void Request::execute( + xmlrpc_c::paramList const& _paramList, + xmlrpc_c::value * const _retval) +{ + retval = _retval; + session = xmlrpc_c::value_string (_paramList.getString(0)); + + Nebula& nd = Nebula::instance(); + UserPool* upool = nd.get_upool(); + + NebulaLog::log("ReM",Log::DEBUG, method_name + " method invoked"); + + if ( upool->authenticate(session, uid, gid) == false ) + { + failure_response(AUTHENTICATION, authenticate_error()); + } + else + { + request_execute(_paramList); + } +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +bool Request::basic_authorization(int oid) +{ + PoolObjectSQL * object; + + bool pub; + int ouid; + + if ( uid == 0 ) + { + return true; + } + + if ( oid == -1 ) + { + ouid = 0; + pub = false; + } + else + { + object = pool->get(oid,true); + + if ( object == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),oid)); + return false; + } + + ouid = object->get_uid(); + pub = object->isPublic(); + + object->unlock(); + } + + AuthRequest ar(uid); + + ar.add_auth(auth_object, oid, auth_op, ouid, pub); + + if (UserPool::authorize(ar) == -1) + { + failure_response(AUTHORIZATION, authorization_error(ar.message)); + + return false; + } + + return true; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void Request::failure_response(ErrorCode ec, const string& str_val) +{ + vector arrayData; + + arrayData.push_back(xmlrpc_c::value_boolean(false)); + arrayData.push_back(xmlrpc_c::value_string(str_val)); + arrayData.push_back(xmlrpc_c::value_int(ec)); + + xmlrpc_c::value_array arrayresult(arrayData); + + *retval = arrayresult; + + NebulaLog::log("ReM",Log::ERROR,str_val); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void Request::success_response(int id) +{ + vector arrayData; + + arrayData.push_back(xmlrpc_c::value_boolean(true)); + arrayData.push_back(xmlrpc_c::value_int(id)); + arrayData.push_back(xmlrpc_c::value_int(SUCCESS)); + + + xmlrpc_c::value_array arrayresult(arrayData); + + *retval = arrayresult; +} + +/* -------------------------------------------------------------------------- */ + +void Request::success_response(const string& val) +{ + vector arrayData; + + arrayData.push_back(xmlrpc_c::value_boolean(true)); + arrayData.push_back(xmlrpc_c::value_string(val)); + arrayData.push_back(xmlrpc_c::value_int(SUCCESS)); + + xmlrpc_c::value_array arrayresult(arrayData); + + *retval = arrayresult; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +string Request::object_name(AuthRequest::Object ob) +{ + switch (ob) + { + case AuthRequest::VM: + return "virtual machine"; + case AuthRequest::HOST: + return "host"; + case AuthRequest::NET: + return "virtual network"; + case AuthRequest::IMAGE: + return "image"; + case AuthRequest::USER: + return "user"; + case AuthRequest::TEMPLATE: + return "virtual machine template"; + case AuthRequest::GROUP: + return "group"; + default: + return "-"; + } +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +string Request::authorization_error (const string &message) +{ + ostringstream oss; + + oss << "[" << method_name << "]" << " User [" << uid << "] not authorized" + << " to perform action on " << object_name(auth_object) << "."; + + + if ( !message.empty() ) + { + oss << message ; + } + + return oss.str(); +} + +/* -------------------------------------------------------------------------- */ + +string Request::authenticate_error() +{ + ostringstream oss; + + oss << "[" << method_name << "]" << " User couldn't be authenticated," << + " aborting call."; + + return oss.str(); +} + +/* -------------------------------------------------------------------------- */ + +string Request::get_error (const string &object, + int id) +{ + ostringstream oss; + + oss << "[" << method_name << "]" << " Error getting " << + object; + + if ( id != -1 ) + { + oss << " [" << id << "]."; + } + else + { + oss << " Pool."; + } + + return oss.str(); +} +/* -------------------------------------------------------------------------- */ + +string Request::request_error (const string &err_desc, const string &err_detail) +{ + ostringstream oss; + + oss << "[" << method_name << "]" << err_desc; + + if (!err_detail.empty()) + { + oss << ". " << err_detail; + } + + return oss.str(); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +string Request::allocate_error (AuthRequest::Object obj, const string& error) +{ + ostringstream oss; + + oss << "[" << method_name << "]" << " Error allocating a new " + << object_name(obj) << "."; + + if (!error.empty()) + { + oss << " " << error; + } + + return oss.str(); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +string Request::allocate_error (const string& error) +{ + ostringstream oss; + + oss << "[" << method_name << "]" << " Error allocating a new " + << object_name(auth_object) << "."; + + if (!error.empty()) + { + oss << " " << error; + } + + return oss.str(); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +string Request::allocate_error (char *error) +{ + ostringstream oss; + + oss << "Parse error"; + + if ( error != 0 ) + { + oss << ": " << error; + free(error); + } + else + { + oss << "."; + } + + return allocate_error(oss.str()); +} diff --git a/src/rm/RequestManager.cc b/src/rm/RequestManager.cc index 9f2c9f64f4..e8fca245bf 100644 --- a/src/rm/RequestManager.cc +++ b/src/rm/RequestManager.cc @@ -18,6 +18,22 @@ #include "NebulaLog.h" #include +#include "RequestManagerPoolInfoFilter.h" +#include "RequestManagerPoolInfo.h" +#include "RequestManagerInfo.h" +#include "RequestManagerDelete.h" +#include "RequestManagerPublish.h" +#include "RequestManagerAllocate.h" +#include "RequestManagerUpdateTemplate.h" +#include "RequestManagerChown.h" + +#include "RequestManagerVirtualNetwork.h" +#include "RequestManagerVirtualMachine.h" +#include "RequestManagerVMTemplate.h" +#include "RequestManagerHost.h" +#include "RequestManagerImage.h" +#include "RequestManagerUser.h" + #include #include #include @@ -213,219 +229,160 @@ void RequestManager::do_action( void RequestManager::register_xml_methods() { - xmlrpc_c::methodPtr vm_allocate(new - RequestManager::VirtualMachineAllocate(vmpool,vnpool,ipool,tpool,upool)); - - xmlrpc_c::methodPtr vm_deploy(new - RequestManager::VirtualMachineDeploy(vmpool,hpool,upool)); - - xmlrpc_c::methodPtr vm_migrate(new - RequestManager::VirtualMachineMigrate(vmpool,hpool,upool)); - - xmlrpc_c::methodPtr vm_action(new - RequestManager::VirtualMachineAction(vmpool,upool)); + // User Methods + xmlrpc_c::methodPtr user_change_password(new UserChangePassword()); + xmlrpc_c::methodPtr user_add_group(new UserAddGroup()); + xmlrpc_c::methodPtr user_del_group(new UserDelGroup()); - xmlrpc_c::methodPtr vm_savedisk(new - RequestManager::VirtualMachineSaveDisk(vmpool,upool,ipool)); + // VMTemplate Methods + xmlrpc_c::methodPtr template_instantiate(new VMTemplateInstantiate()); - xmlrpc_c::methodPtr vm_info(new - RequestManager::VirtualMachineInfo(vmpool,upool)); + // VirtualMachine Methods + xmlrpc_c::methodPtr vm_deploy(new VirtualMachineDeploy()); + xmlrpc_c::methodPtr vm_migrate(new VirtualMachineMigrate()); + xmlrpc_c::methodPtr vm_action(new VirtualMachineAction()); + xmlrpc_c::methodPtr vm_savedisk(new VirtualMachineSaveDisk()); - xmlrpc_c::methodPtr vm_pool_info(new - RequestManager::VirtualMachinePoolInfo(vmpool,upool)); + // VirtualNetwork Methods + xmlrpc_c::methodPtr vn_addleases(new VirtualNetworkAddLeases()); + xmlrpc_c::methodPtr vn_rmleases(new VirtualNetworkRemoveLeases()); - xmlrpc_c::methodPtr template_allocate(new - RequestManager::TemplateAllocate(tpool,upool)); + // Update Template Methods + xmlrpc_c::methodPtr image_update(new ImageUpdateTemplate()); + xmlrpc_c::methodPtr template_update(new TemplateUpdateTemplate()); + xmlrpc_c::methodPtr host_update(new HostUpdateTemplate()); - xmlrpc_c::methodPtr template_delete(new - RequestManager::TemplateDelete(tpool, upool)); + // Allocate Methods + xmlrpc_c::methodPtr vm_allocate(new VirtualMachineAllocate()); + xmlrpc_c::methodPtr image_allocate(new ImageAllocate()); + xmlrpc_c::methodPtr vn_allocate(new VirtualNetworkAllocate()); + xmlrpc_c::methodPtr group_allocate(new GroupAllocate()); + xmlrpc_c::methodPtr template_allocate(new TemplateAllocate()); + xmlrpc_c::methodPtr host_allocate(new HostAllocate()); + xmlrpc_c::methodPtr user_allocate(new UserAllocate()); - xmlrpc_c::methodPtr template_info(new - RequestManager::TemplateInfo(tpool, upool)); + // Publish Methods + xmlrpc_c::methodPtr template_publish(new TemplatePublish()); + xmlrpc_c::methodPtr vn_publish(new VirtualNetworkPublish()); + xmlrpc_c::methodPtr image_publish(new ImagePublish()); - xmlrpc_c::methodPtr template_update(new - RequestManager::TemplateUpdate(tpool, upool)); + // Delete Methods + xmlrpc_c::methodPtr host_delete(new HostDelete()); + xmlrpc_c::methodPtr template_delete(new TemplateDelete()); + xmlrpc_c::methodPtr group_delete(new GroupDelete()); + xmlrpc_c::methodPtr vn_delete(new VirtualNetworkDelete()); + xmlrpc_c::methodPtr user_delete(new UserDelete()); + xmlrpc_c::methodPtr image_delete(new ImageDelete()); - xmlrpc_c::methodPtr template_rm_attribute(new - RequestManager::TemplateRemoveAttribute(tpool, upool)); + // Info Methods + xmlrpc_c::methodPtr vm_info(new VirtualMachineInfo()); + xmlrpc_c::methodPtr host_info(new HostInfo()); + xmlrpc_c::methodPtr template_info(new TemplateInfo()); + xmlrpc_c::methodPtr group_info(new GroupInfo()); + xmlrpc_c::methodPtr vn_info(new VirtualNetworkInfo()); + xmlrpc_c::methodPtr user_info(new UserInfo()); + xmlrpc_c::methodPtr image_info(new ImageInfo()); - xmlrpc_c::methodPtr template_publish(new - RequestManager::TemplatePublish(tpool, upool)); + // PoolInfo Methods - xmlrpc_c::methodPtr template_pool_info(new - RequestManager::TemplatePoolInfo(tpool,upool)); + xmlrpc_c::methodPtr hostpool_info(new HostPoolInfo()); + xmlrpc_c::methodPtr grouppool_info(new GroupPoolInfo()); + xmlrpc_c::methodPtr userpool_info(new UserPoolInfo()); - xmlrpc_c::methodPtr host_allocate(new - RequestManager::HostAllocate(hpool,upool)); - - xmlrpc_c::methodPtr host_info(new - RequestManager::HostInfo(hpool, upool)); + // PoolInfo Methods with Filtering - xmlrpc_c::methodPtr hostpool_info(new - RequestManager::HostPoolInfo(hpool,upool)); - - xmlrpc_c::methodPtr host_delete(new - RequestManager::HostDelete(hpool,upool)); + xmlrpc_c::methodPtr vm_pool_info(new VirtualMachinePoolInfo()); + xmlrpc_c::methodPtr template_pool_info(new TemplatePoolInfo()); + xmlrpc_c::methodPtr vnpool_info(new VirtualNetworkPoolInfo()); + xmlrpc_c::methodPtr imagepool_info(new ImagePoolInfo()); - xmlrpc_c::methodPtr host_enable(new - RequestManager::HostEnable(hpool,upool)); + // Host Methods + xmlrpc_c::methodPtr host_enable(new HostEnable()); - xmlrpc_c::methodPtr cluster_allocate(new - RequestManager::ClusterAllocate(upool,cpool)); + // Image Methods + xmlrpc_c::methodPtr image_persistent(new ImagePersistent()); + xmlrpc_c::methodPtr image_enable(new ImageEnable()); - xmlrpc_c::methodPtr cluster_info(new - RequestManager::ClusterInfo(upool,cpool)); - - xmlrpc_c::methodPtr cluster_delete(new - RequestManager::ClusterDelete(upool,cpool)); - - xmlrpc_c::methodPtr cluster_add(new - RequestManager::ClusterAdd(hpool,upool,cpool)); - - xmlrpc_c::methodPtr cluster_remove(new - RequestManager::ClusterRemove(hpool,upool,cpool)); - - xmlrpc_c::methodPtr clusterpool_info(new - RequestManager::ClusterPoolInfo(upool,cpool)); - - xmlrpc_c::methodPtr vn_allocate(new - RequestManager::VirtualNetworkAllocate(vnpool,upool)); - - xmlrpc_c::methodPtr vn_info(new - RequestManager::VirtualNetworkInfo(vnpool,upool)); - - xmlrpc_c::methodPtr vnpool_info(new - RequestManager::VirtualNetworkPoolInfo(vnpool,upool)); - - xmlrpc_c::methodPtr vn_publish(new - RequestManager::VirtualNetworkPublish(vnpool, upool)); - - xmlrpc_c::methodPtr vn_delete(new - RequestManager::VirtualNetworkDelete(vnpool, upool)); - - xmlrpc_c::methodPtr vn_addleases(new - RequestManager::VirtualNetworkAddLeases(vnpool, upool)); - - xmlrpc_c::methodPtr vn_rmleases(new - RequestManager::VirtualNetworkRemoveLeases(vnpool, upool)); - - xmlrpc_c::methodPtr user_allocate(new - RequestManager::UserAllocate(upool)); - - xmlrpc_c::methodPtr user_delete(new - RequestManager::UserDelete(upool)); - - xmlrpc_c::methodPtr user_info(new - RequestManager::UserInfo(upool)); - - xmlrpc_c::methodPtr user_change_password(new - RequestManager::UserChangePassword(upool)); - - xmlrpc_c::methodPtr userpool_info(new - RequestManager::UserPoolInfo(upool)); - - xmlrpc_c::methodPtr image_allocate(new - RequestManager::ImageAllocate(ipool, upool)); - - xmlrpc_c::methodPtr image_delete(new - RequestManager::ImageDelete(ipool, upool)); - - xmlrpc_c::methodPtr image_info(new - RequestManager::ImageInfo(ipool, upool)); - - xmlrpc_c::methodPtr image_update(new - RequestManager::ImageUpdate(ipool, upool)); - - xmlrpc_c::methodPtr image_rm_attribute(new - RequestManager::ImageRemoveAttribute(ipool, upool)); - - xmlrpc_c::methodPtr image_publish(new - RequestManager::ImagePublish(ipool, upool)); - - xmlrpc_c::methodPtr image_persistent(new - RequestManager::ImagePersistent(ipool, upool)); - - xmlrpc_c::methodPtr image_enable(new - RequestManager::ImageEnable(ipool, upool)); - - xmlrpc_c::methodPtr imagepool_info(new - RequestManager::ImagePoolInfo(ipool, upool)); + // Chown Methods + xmlrpc_c::methodPtr vm_chown(new VirtualMachineChown()); + xmlrpc_c::methodPtr template_chown(new TemplateChown()); + xmlrpc_c::methodPtr vn_chown(new VirtualNetworkChown()); + xmlrpc_c::methodPtr image_chown(new ImageChown()); + xmlrpc_c::methodPtr user_chown(new UserChown()); /* VM related methods */ - - RequestManagerRegistry.addMethod("one.vm.allocate", vm_allocate); RequestManagerRegistry.addMethod("one.vm.deploy", vm_deploy); RequestManagerRegistry.addMethod("one.vm.action", vm_action); RequestManagerRegistry.addMethod("one.vm.migrate", vm_migrate); - RequestManagerRegistry.addMethod("one.vm.info", vm_info); RequestManagerRegistry.addMethod("one.vm.savedisk", vm_savedisk); + RequestManagerRegistry.addMethod("one.vm.allocate", vm_allocate); + RequestManagerRegistry.addMethod("one.vm.info", vm_info); + RequestManagerRegistry.addMethod("one.vm.chown", vm_chown); RequestManagerRegistry.addMethod("one.vmpool.info", vm_pool_info); /* VM Template related methods*/ - + RequestManagerRegistry.addMethod("one.template.update", template_update); + RequestManagerRegistry.addMethod("one.template.instantiate",template_instantiate); RequestManagerRegistry.addMethod("one.template.allocate",template_allocate); + RequestManagerRegistry.addMethod("one.template.publish", template_publish); 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.template.chown", template_chown); RequestManagerRegistry.addMethod("one.templatepool.info",template_pool_info); /* Host related methods*/ - - RequestManagerRegistry.addMethod("one.host.allocate", host_allocate); - RequestManagerRegistry.addMethod("one.host.info", host_info); - RequestManagerRegistry.addMethod("one.host.delete", host_delete); RequestManagerRegistry.addMethod("one.host.enable", host_enable); - + RequestManagerRegistry.addMethod("one.host.update", host_update); + RequestManagerRegistry.addMethod("one.host.allocate", host_allocate); + RequestManagerRegistry.addMethod("one.host.delete", host_delete); + RequestManagerRegistry.addMethod("one.host.info", host_info); + RequestManagerRegistry.addMethod("one.hostpool.info", hostpool_info); - /* Cluster related methods */ + /* Group related methods */ + RequestManagerRegistry.addMethod("one.group.allocate", group_allocate); + RequestManagerRegistry.addMethod("one.group.delete", group_delete); + RequestManagerRegistry.addMethod("one.group.info", group_info); - RequestManagerRegistry.addMethod("one.cluster.allocate", cluster_allocate); - RequestManagerRegistry.addMethod("one.cluster.info", cluster_info); - RequestManagerRegistry.addMethod("one.cluster.delete", cluster_delete); - RequestManagerRegistry.addMethod("one.cluster.add", cluster_add); - RequestManagerRegistry.addMethod("one.cluster.remove", cluster_remove); - - RequestManagerRegistry.addMethod("one.clusterpool.info", clusterpool_info); + RequestManagerRegistry.addMethod("one.grouppool.info", grouppool_info); /* Network related methods*/ - - RequestManagerRegistry.addMethod("one.vn.allocate", vn_allocate); - RequestManagerRegistry.addMethod("one.vn.info", vn_info); - RequestManagerRegistry.addMethod("one.vn.publish", vn_publish); - RequestManagerRegistry.addMethod("one.vn.delete", vn_delete); RequestManagerRegistry.addMethod("one.vn.addleases", vn_addleases); RequestManagerRegistry.addMethod("one.vn.rmleases", vn_rmleases); + RequestManagerRegistry.addMethod("one.vn.allocate", vn_allocate); + RequestManagerRegistry.addMethod("one.vn.publish", vn_publish); + RequestManagerRegistry.addMethod("one.vn.delete", vn_delete); + RequestManagerRegistry.addMethod("one.vn.info", vn_info); + RequestManagerRegistry.addMethod("one.vn.chown", vn_chown); RequestManagerRegistry.addMethod("one.vnpool.info", vnpool_info); /* User related methods*/ - RequestManagerRegistry.addMethod("one.user.allocate", user_allocate); RequestManagerRegistry.addMethod("one.user.delete", user_delete); RequestManagerRegistry.addMethod("one.user.info", user_info); + RequestManagerRegistry.addMethod("one.user.addgroup", user_add_group); + RequestManagerRegistry.addMethod("one.user.delgroup", user_del_group); RequestManagerRegistry.addMethod("one.user.passwd", user_change_password); + RequestManagerRegistry.addMethod("one.user.chgrp", user_chown); RequestManagerRegistry.addMethod("one.userpool.info", userpool_info); /* Image related methods*/ - + + RequestManagerRegistry.addMethod("one.image.persistent", image_persistent); + RequestManagerRegistry.addMethod("one.image.enable", image_enable); + RequestManagerRegistry.addMethod("one.image.update", image_update); RequestManagerRegistry.addMethod("one.image.allocate", image_allocate); + RequestManagerRegistry.addMethod("one.image.publish", image_publish); RequestManagerRegistry.addMethod("one.image.delete", image_delete); RequestManagerRegistry.addMethod("one.image.info", image_info); - RequestManagerRegistry.addMethod("one.image.update", image_update); - RequestManagerRegistry.addMethod("one.image.rmattr", image_rm_attribute); - RequestManagerRegistry.addMethod("one.image.publish", image_publish); - RequestManagerRegistry.addMethod("one.image.persistent", image_persistent); - RequestManagerRegistry.addMethod("one.image.enable", image_enable); + RequestManagerRegistry.addMethod("one.image.chown", image_chown); RequestManagerRegistry.addMethod("one.imagepool.info", imagepool_info); - }; /* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerAction.cc b/src/rm/RequestManagerAction.cc deleted file mode 100644 index dbeb091d30..0000000000 --- a/src/rm/RequestManagerAction.cc +++ /dev/null @@ -1,184 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::VirtualMachineAction::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - string action; - int vid; - int rc; - - int uid; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - Nebula& nd = Nebula::instance(); - DispatchManager * dm = nd.get_dm(); - - VirtualMachine * vm; - - ostringstream oss; - - const string method_name = "VirtualMachineAction"; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualMachineAction invoked"); - - session = xmlrpc_c::value_string(paramList.getString(0)); - action = xmlrpc_c::value_string(paramList.getString(1)); - vid = xmlrpc_c::value_int(paramList.getInt(2)); - - // Get the VM - vm = VirtualMachineAction::vmpool->get(vid,true); - - if ( vm == 0 ) - { - goto error_vm_get; - } - - uid = vm->get_uid(); - - vm->unlock(); - - //Authenticate the user - rc = VirtualMachineAction::upool->authenticate(session); - - if (rc == -1) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::VM,vid,AuthRequest::MANAGE,uid,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - if (action == "shutdown") - { - rc = dm->shutdown(vid); - } - else if (action == "hold") - { - rc = dm->hold(vid); - } - else if (action == "release") - { - rc = dm->release(vid); - } - else if (action == "stop") - { - rc = dm->stop(vid); - } - else if (action == "cancel") - { - rc = dm->cancel(vid); - } - else if (action == "suspend") - { - rc = dm->suspend(vid); - } - else if (action == "resume") - { - rc = dm->resume(vid); - } - else if (action == "restart") - { - rc = dm->restart(vid); - } - else if (action == "finalize") - { - rc = dm->finalize(vid); - } - else if (action == "resubmit") - { - rc = dm->resubmit(vid); - } - else - { - rc = -3; - } - - if (rc != 0) - { - goto error_operation; - } - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayresult = new xmlrpc_c::value_array(arrayData); - *retval = *arrayresult; - delete arrayresult; - return; - -error_operation: - if (rc == -1) - { - oss << "Virtual machine does not exist"; - } - else if ( rc == -2 ) - { - oss << "Wrong state to perform action"; - } - else if ( rc == -3 ) - { - oss << "Unknown action"; - } - goto error_common; - -error_vm_get: - oss.str(get_error(method_name, "VM", vid)); - goto error_common; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "VM", rc, vid)); - goto error_common; - -error_common: - arrayData.push_back(xmlrpc_c::value_boolean(false)); - arrayData.push_back(xmlrpc_c::value_string(oss.str())); - - xmlrpc_c::value_array arrayresult_error(arrayData); - - NebulaLog::log("ReM",Log::ERROR,oss); - - *retval = arrayresult_error; - - return; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerAllocate.cc b/src/rm/RequestManagerAllocate.cc index 2de7a853ac..551c156703 100644 --- a/src/rm/RequestManagerAllocate.cc +++ b/src/rm/RequestManagerAllocate.cc @@ -14,279 +14,226 @@ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ -#include "RequestManager.h" +#include "RequestManagerAllocate.h" #include "NebulaLog.h" #include "Nebula.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -void RequestManager::VirtualMachineAllocate::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) +bool RequestManagerAllocate::allocate_authorization(Template * tmpl) { - string session; - string str_template; - string error_str; - string user_name; - string template_id_str = "TEMPLATE_ID";; - - const string method_name = "VirtualMachineAllocate"; - - int vid, uid, tid; - int rc; - - ostringstream oss; - - vector arrayData; - 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; - vector vectors; - VectorAttribute * vector; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualMachineAllocate 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 = VirtualMachineAllocate::upool->authenticate(session); - - if (uid == -1) + if ( uid == 0 ) { - goto error_authenticate; + return true; } - //-------------------------------------------------------------------------- - // Authorize this request - //-------------------------------------------------------------------------- - vm_template = new VirtualMachineTemplate; + AuthRequest ar(uid); - rc = vm_template->parse(str_template,&error_msg); - - if ( rc != 0 ) + if ( tmpl == 0 ) + { + ar.add_auth(auth_object,-1,auth_op,uid,false); + } + else { - goto error_parse; + string t64; + + ar.add_auth(auth_object,tmpl->to_xml(t64),auth_op,uid,false); } - //-------------------------------------------------------------------------- - // 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 (UserPool::authorize(ar) == -1) + { + failure_response(AUTHORIZATION, authorization_error(ar.message)); + return false; } - 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(vectors[i]); - - if ( vector == 0 ) - { - continue; - } - - VirtualMachineAllocate::ipool->authorize_disk(vector,uid,&ar); - } - - vectors.clear(); - - num = vm_template->get("NIC",vectors); - - for(int i=0; i(vectors[i]); - - if ( vector == 0 ) - { - continue; - } - - VirtualMachineAllocate::vnpool->authorize_nic(vector,uid,&ar); - } - - 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) - { - goto error_authorize; - } - } - - //-------------------------------------------------------------------------- - // Get the User Name - //-------------------------------------------------------------------------- - - user = VirtualMachineAllocate::upool->get(uid,true); - - if ( user == 0 ) - { - goto error_user_get; - } - - user_name = user->get_name(); - - user->unlock(); - - //-------------------------------------------------------------------------- - // Allocate the VirtualMAchine - //-------------------------------------------------------------------------- - rc = VirtualMachineAllocate::vmpool->allocate(uid, - user_name, - vm_template, - &vid, - error_str, - false); - if ( rc < 0 ) - { - goto error_allocate; - } - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(vid)); - - // 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_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)); - - delete vm_template; - goto error_common; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "CREATE", "VM", uid, -1)); - delete vm_template; - 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 vm_template; - goto error_common; - -error_allocate: - oss << action_error(method_name, "CREATE", "VM", -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; + return true; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ + +bool VirtualMachineAllocate::allocate_authorization(Template * tmpl) +{ + if ( uid == 0 ) + { + return true; + } + + AuthRequest ar(uid); + string t64; + + VirtualMachineTemplate * ttmpl = static_cast(tmpl); + + ar.add_auth(auth_object,tmpl->to_xml(t64),auth_op,uid,false); + + VirtualMachine::set_auth_request(uid, ar, ttmpl); + + if (UserPool::authorize(ar) == -1) + { + failure_response(AUTHORIZATION, authorization_error(ar.message)); + return false; + } + + return true; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void RequestManagerAllocate::request_execute(xmlrpc_c::paramList const& params) +{ + Template * tmpl = 0; + + string error_str; + int rc, id; + + if ( do_template == true ) + { + char * error_msg = 0; + string str_tmpl = xmlrpc_c::value_string(params.getString(1)); + + tmpl = get_object_template(); + + rc = tmpl->parse(str_tmpl, &error_msg); + + if ( rc != 0 ) + { + failure_response(INTERNAL, allocate_error(error_msg)); + delete tmpl; + + return; + } + } + + if ( allocate_authorization(tmpl) == false ) + { + return; + } + + rc = pool_allocate(params, tmpl, id, error_str); + + if ( rc < 0 ) + { + failure_response(INTERNAL, allocate_error(error_str)); + return; + } + + success_response(id); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int VirtualMachineAllocate::pool_allocate(xmlrpc_c::paramList const& paramList, + Template * tmpl, + int& id, + string& error_str) +{ + VirtualMachineTemplate * ttmpl = static_cast(tmpl); + VirtualMachinePool * vmpool = static_cast(pool); + + return vmpool->allocate(uid, gid, ttmpl, &id, error_str, false); +} + + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int VirtualNetworkAllocate::pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str) +{ + VirtualNetworkPool * vpool = static_cast(pool); + VirtualNetworkTemplate * vtmpl=static_cast(tmpl); + + return vpool->allocate(uid, gid, vtmpl, &id, error_str); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int ImageAllocate::pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str) +{ + ImagePool * ipool = static_cast(pool); + ImageTemplate * itmpl = static_cast(tmpl); + + return ipool->allocate(uid, gid, itmpl, &id, error_str); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int TemplateAllocate::pool_allocate(xmlrpc_c::paramList const& _paramList, + Template * tmpl, + int& id, + string& error_str) +{ + VMTemplatePool * tpool = static_cast(pool); + + VirtualMachineTemplate * ttmpl=static_cast(tmpl); + + return tpool->allocate(uid, gid, ttmpl, &id, error_str); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int HostAllocate::pool_allocate(xmlrpc_c::paramList const& paramList, + Template * tmpl, + int& id, + string& error_str) +{ + string host = xmlrpc_c::value_string(paramList.getString(1)); + string im_mad = xmlrpc_c::value_string(paramList.getString(2)); + string vmm_mad = xmlrpc_c::value_string(paramList.getString(3)); + string tm_mad = xmlrpc_c::value_string(paramList.getString(4)); + + HostPool * hpool = static_cast(pool); + + return hpool->allocate(&id, host, im_mad, vmm_mad, tm_mad, error_str); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int UserAllocate::pool_allocate(xmlrpc_c::paramList const& paramList, + Template * tmpl, + int& id, + string& error_str) +{ + string uname = xmlrpc_c::value_string(paramList.getString(1)); + string passwd = xmlrpc_c::value_string(paramList.getString(2)); + + UserPool * upool = static_cast(pool); + int users_group = gid; + + if ( gid == GroupPool::ONEADMIN_ID ) + { + users_group = GroupPool::USERS_ID; + } + + return upool->allocate(&id,users_group,uname,passwd,true,error_str); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int GroupAllocate::pool_allocate(xmlrpc_c::paramList const& paramList, + Template * tmpl, + int& id, + string& error_str) +{ + string gname = xmlrpc_c::value_string(paramList.getString(1)); + + GroupPool * gpool = static_cast(pool); + + return gpool->allocate(gname, &id, error_str); +} + diff --git a/src/rm/RequestManagerCancel.cc b/src/rm/RequestManagerCancel.cc deleted file mode 100644 index bc8b3a223e..0000000000 --- a/src/rm/RequestManagerCancel.cc +++ /dev/null @@ -1,125 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 "Nebula.h" - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -void RequestManager::VirtualMachineCancel::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - // of the vid to retrieve the information for - int vid; - int uid; - - const string method_name = "VirtualMachineCancel"; - - VirtualMachine * vm; - - ostringstream oss; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - Nebula& nd = Nebula::instance(); - DispatchManager * dm = nd.get_dm(); - - Nebula::log("ReM",Log::DEBUG,"VirtualMachineCancel method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - vid = xmlrpc_c::value_int (paramList.getInt(1)); - - // Retrieve the VM from the vmpool - vm = VirtualMachineCancel::vmpool->get(vid,true); - - if ( vm == 0 ) - { - goto error_vm_get; - } - - uid = vm->get_uid(); - - vm->unlock(); - - //Authenticate the user - rc = VirtualMachineCancel::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::VM,vid,AuthRequest::MANAGE,uid,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - //Cancel the VM - dm->cancel(vid); - - // Send results to client - arrayData.push_back(xmlrpc_c::value_boolean(true)); - - arrayresult = new xmlrpc_c::value_array(arrayData); - - *retval = *arrayresult; - - delete arrayresult; - - return; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "VM", uid, vid)); - goto error_common; - -error_vm_get: - oss.str(get_error(method_name, "VM", vid)); - goto error_common; - -error_common: - arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE - arrayData.push_back(xmlrpc_c::value_string(oss.str())); - - Nebula::log("ReM",Log::ERROR,oss); - - xmlrpc_c::value_array arrayresult_error(arrayData); - - *retval = arrayresult_error; - - return; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerChown.cc b/src/rm/RequestManagerChown.cc new file mode 100644 index 0000000000..f2910aefe0 --- /dev/null +++ b/src/rm/RequestManagerChown.cc @@ -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 "RequestManagerChown.h" + +#include "NebulaLog.h" +#include "Nebula.h" + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void RequestManagerChown::request_execute(xmlrpc_c::paramList const& paramList) +{ + int oid = xmlrpc_c::value_int(paramList.getInt(1)); + int noid = xmlrpc_c::value_int(paramList.getInt(2)); + int ngid = xmlrpc_c::value_int(paramList.getInt(3)); + + Nebula& nd = Nebula::instance(); + GroupPool * gpool = nd.get_gpool(); + UserPool * upool = nd.get_upool(); + + PoolObjectSQL * object; + + if ( basic_authorization(oid) == false ) + { + return; + } + + // ------------- Check new user and group id's --------------------- + + if ( noid > -1 && upool->get(noid,false) == 0 ) + { + failure_response(NO_EXISTS, + get_error(object_name(AuthRequest::USER),noid)); + return; + } + + if ( ngid > -1 && gpool->get(ngid,false) == 0 ) + { + failure_response(NO_EXISTS, + get_error(object_name(AuthRequest::GROUP),ngid)); + return; + } + + // ------------- Update the object --------------------- + + object = pool->get(oid,true); + + if ( object == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),oid)); + return; + } + + if ( noid != -1 ) + { + object->set_uid(noid); + } + + if ( ngid != -1 ) + { + object->set_gid(ngid); + } + + pool->update(object); + + object->unlock(); + + success_response(oid); + + return; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void UserChown::request_execute(xmlrpc_c::paramList const& paramList) +{ + int oid = xmlrpc_c::value_int(paramList.getInt(1)); + int ngid = xmlrpc_c::value_int(paramList.getInt(2)); + int old_gid; + + string str; + + Nebula& nd = Nebula::instance(); + GroupPool * gpool = nd.get_gpool(); + UserPool * upool = static_cast(pool); + + User * user; + Group * group; + + if ( basic_authorization(oid) == false ) + { + return; + } + + // ------------- Check new primary group id for user --------------------- + + if ( ngid < 0 ) + { + failure_response(XML_RPC_API,request_error("Wrong group ID","")); + return; + } + else if ( gpool->get(ngid,false) == 0 ) + { + failure_response(NO_EXISTS, + get_error(object_name(AuthRequest::GROUP),ngid)); + return; + } + + // ------------- Change users primary group --------------------- + + user = upool->get(oid,true); + + if ( user == 0 ) + { + failure_response(NO_EXISTS, + get_error(object_name(AuthRequest::USER),oid)); + return; + } + + if ((old_gid = user->get_gid()) == ngid) + { + user->unlock(); + success_response(oid); + return; + } + + user->set_gid(ngid); + + user->add_group(ngid); + user->del_group(old_gid); + + upool->update(user); + + user->unlock(); + + // ------------- Updates new group with this new user --------------------- + + group = gpool->get(ngid, true); + + if( group == 0 ) + { + get_error(object_name(AuthRequest::GROUP),ngid); //TODO Rollback + return; + } + + group->add_user(oid); + + gpool->update(group); + + group->unlock(); + + // ------------- Updates old group removing the user --------------------- + + group = gpool->get(old_gid, true); + + if( group != 0 ) + { + group->del_user(oid); + + gpool->update(group); + + group->unlock(); + } + + success_response(oid); + + return; +} diff --git a/src/rm/RequestManagerClusterAdd.cc b/src/rm/RequestManagerClusterAdd.cc deleted file mode 100644 index 0ffe63f389..0000000000 --- a/src/rm/RequestManagerClusterAdd.cc +++ /dev/null @@ -1,155 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ClusterAdd::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int hid; - int clid; - int rc; - - const string method_name = "ClusterAdd"; - - Host * host; - Cluster * cluster; - - ostringstream oss; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"ClusterAdd method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - hid = xmlrpc_c::value_int (paramList.getInt(1)); - clid = xmlrpc_c::value_int (paramList.getInt(2)); - - //Authenticate the user - rc = ClusterAdd::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::HOST,hid,AuthRequest::MANAGE,0,false); - ar.add_auth(AuthRequest::CLUSTER,clid,AuthRequest::USE,0,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Check if cluster exists - cluster = ClusterAdd::cpool->get(clid,true); - - if ( cluster == 0 ) - { - goto error_cluster_get; - } - - // Check if host exists - host = ClusterAdd::hpool->get(hid,true); - - if ( host == 0 ) - { - goto error_host_get; - } - - // Set cluster - rc = host->set_cluster(cluster->get_name()); - - if ( rc != 0 ) - { - goto error_cluster_add; - } - - // Update the DB - ClusterAdd::hpool->update(host); - - host->unlock(); - - cluster->unlock(); - - // All nice, return success to the client - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - - // 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_authorize: - oss.str(authorization_error(method_name, "USE", "CLUSTER", rc, clid)); - goto error_common; - -error_host_get: - cluster->unlock(); - oss.str(get_error(method_name, "HOST", hid)); - goto error_common; - -error_cluster_get: - oss.str(get_error(method_name, "CLUSTER", clid)); - goto error_common; - -error_cluster_add: - host->unlock(); - cluster->unlock(); - oss.str(action_error(method_name, "USE", "CLUSTER", clid, rc)); - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerClusterAllocate.cc b/src/rm/RequestManagerClusterAllocate.cc deleted file mode 100644 index 54fff40ccc..0000000000 --- a/src/rm/RequestManagerClusterAllocate.cc +++ /dev/null @@ -1,118 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ClusterAllocate::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - string error_str; - - string clustername; - int id; - - const string method_name = "ClusterAllocate"; - - int rc; - ostringstream oss; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"ClusterAllocate method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - clustername = xmlrpc_c::value_string(paramList.getString(1)); - - //Authenticate the user - rc = ClusterAllocate::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::CLUSTER,-1,AuthRequest::CREATE,0,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Perform the allocation in the hostpool - rc = ClusterAllocate::cpool->allocate(&id, clustername, error_str); - - if ( rc == -1 ) - { - goto error_cluster_allocate; - } - - // All nice, return the new id to client - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - arrayData.push_back(xmlrpc_c::value_int(id)); - 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_authorize: - oss.str(authorization_error(method_name, "CREATE", "CLUSTER", rc, -1)); - goto error_common; - -error_cluster_allocate: - oss << action_error(method_name, "CREATE", "CLUSTER", -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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerClusterDelete.cc b/src/rm/RequestManagerClusterDelete.cc deleted file mode 100644 index a1a938faa4..0000000000 --- a/src/rm/RequestManagerClusterDelete.cc +++ /dev/null @@ -1,127 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ClusterDelete::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int clid; - Cluster * cluster; - ostringstream oss; - int rc; - - const string method_name = "ClusterDelete"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"ClusterDelete method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - clid = xmlrpc_c::value_int (paramList.getInt(1)); - - //Authenticate the user - rc = ClusterDelete::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::CLUSTER,clid,AuthRequest::DELETE,0,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Perform the deletion from the pool - cluster = ClusterDelete::cpool->get(clid,true); - - if ( cluster == 0 ) - { - goto error_cluster_get; - } - - rc = ClusterDelete::cpool->drop(cluster); - - cluster->unlock(); - - if ( rc != 0 ) - { - goto error_cluster_delete; - } - - // Return success - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - 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_authorize: - oss.str(authorization_error(method_name, "DELETE", "CLUSTER", rc, clid)); - goto error_common; - -error_cluster_get: - oss.str(get_error(method_name, "CLUSTER", clid)); - goto error_common; - -error_cluster_delete: - oss.str(action_error(method_name, "DELETE", "CLUSTER", clid, rc)); - goto error_common; - -error_common: - NebulaLog::log ("Rem",Log::ERROR,oss); - - arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE - arrayData.push_back(xmlrpc_c::value_string(oss.str())); - - xmlrpc_c::value_array arrayresult_error(arrayData); - - *retval = arrayresult_error; - - return; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerClusterInfo.cc b/src/rm/RequestManagerClusterInfo.cc deleted file mode 100644 index 137a4f3405..0000000000 --- a/src/rm/RequestManagerClusterInfo.cc +++ /dev/null @@ -1,105 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ClusterInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - Cluster * cluster; - ostringstream oss; - - int clid; - int rc; - - const string method_name = "ClusterInfo"; - - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"ClusterInfo method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - clid = xmlrpc_c::value_int (paramList.getInt(1)); - - //Authenticate the user - rc = ClusterInfo::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - // Get the cluster - cluster = ClusterInfo::cpool->get(clid,true); - - if ( cluster == 0 ) - { - goto error_cluster_get; - } - - oss << *cluster; - - cluster->unlock(); - - // All nice, return the cluster 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_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_cluster_get: - oss.str(get_error(method_name, "CLUSTER", clid)); - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerClusterPoolInfo.cc b/src/rm/RequestManagerClusterPoolInfo.cc deleted file mode 100644 index ece06d4274..0000000000 --- a/src/rm/RequestManagerClusterPoolInfo.cc +++ /dev/null @@ -1,97 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ClusterPoolInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - ostringstream oss; - int rc; - - const string method_name = "ClusterPoolInfo"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"ClusterPoolInfo method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - - //Authenticate the user - rc = ClusterPoolInfo::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - // Dump the pool - rc = ClusterPoolInfo::cpool->dump(oss, ""); - - if ( rc != 0 ) - { - goto error_dump; - } - - //All nice, return the 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_dump: - oss.str(get_error(method_name, "CLUSTER", -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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerClusterRemove.cc b/src/rm/RequestManagerClusterRemove.cc deleted file mode 100644 index 1fe7fa9b80..0000000000 --- a/src/rm/RequestManagerClusterRemove.cc +++ /dev/null @@ -1,134 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ClusterRemove::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int hid; - int rc; - - const string method_name = "ClusterRemove"; - - Host * host; - - ostringstream oss; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"ClusterRemove method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - hid = xmlrpc_c::value_int (paramList.getInt(1)); - - // Only oneadmin can delete clusters - rc = ClusterRemove::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::HOST,hid,AuthRequest::MANAGE,0,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Check if host exists - host = ClusterRemove::hpool->get(hid,true); - - if ( host == 0 ) - { - goto error_host_get; - } - - // Remove host from cluster - rc = ClusterRemove::cpool->set_default_cluster(host); - - if ( rc != 0 ) - { - goto error_cluster_remove; - } - - // Update the DB - ClusterRemove::hpool->update(host); - - host->unlock(); - - // All nice, return success to the client - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - - // 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_authorize: - oss.str(authorization_error(method_name, "MANAGE", "HOST", rc, -1)); - goto error_common; - -error_host_get: - oss.str(get_error(method_name, "HOST", hid)); - goto error_common; - -error_cluster_remove: - host->unlock(); - oss.str(action_error(method_name, "MANAGE", "HOST", hid, rc)); - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerDelete.cc b/src/rm/RequestManagerDelete.cc new file mode 100644 index 0000000000..f4a0ccb33f --- /dev/null +++ b/src/rm/RequestManagerDelete.cc @@ -0,0 +1,90 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "RequestManagerDelete.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void RequestManagerDelete::request_execute(xmlrpc_c::paramList const& paramList) +{ + int oid = xmlrpc_c::value_int(paramList.getInt(1)); + PoolObjectSQL * object; + set group_set; + string error_msg; + + if ( basic_authorization(oid) == false ) + { + return; + } + + object = pool->get(oid,true); + + if ( object == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),oid)); + return; + } + + if ( auth_object == AuthRequest::USER ) + { + User * user = static_cast(object); + group_set = user->get_groups(); + } + + int rc = pool->drop(object, error_msg); + + object->unlock(); + + if ( rc != 0 ) + { + failure_response(INTERNAL, + request_error("Can not delete "+object_name(auth_object),error_msg)); + return; + } + + if ( auth_object == AuthRequest::USER ) + { + Nebula& nd = Nebula::instance(); + GroupPool * gpool = nd.get_gpool(); + + Group * group; + + set::iterator it; + + for ( it = group_set.begin(); it != group_set.end(); it++ ) + { + group = gpool->get(*it, true); + + if( group == 0 ) + { + continue; + } + + group->del_user(oid); + gpool->update(group); + + group->unlock(); + } + } + + success_response(oid); + + return; +} + diff --git a/src/rm/RequestManagerDeploy.cc b/src/rm/RequestManagerDeploy.cc deleted file mode 100644 index 5c982e95b3..0000000000 --- a/src/rm/RequestManagerDeploy.cc +++ /dev/null @@ -1,203 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::VirtualMachineDeploy::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - int vid; - int hid; - int uid; - int rc; - - string hostname; - string vmm_mad; - string tm_mad; - string vmdir; - - const string method_name = "VirtualMachineDeploy"; - - VirtualMachine * vm; - Host * host; - - Nebula& nd = Nebula::instance(); - DispatchManager * dm = nd.get_dm(); - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - ostringstream oss; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualMachineDeploy invoked"); - - //Parse Arguments - session = xmlrpc_c::value_string(paramList.getString(0)); - vid = xmlrpc_c::value_int(paramList.getInt(1)); - hid = xmlrpc_c::value_int(paramList.getInt(2)); - - // ------------------------------------------------------------------------- - // Authenticate the user - // ------------------------------------------------------------------------- - rc = VirtualMachineDeploy::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - // ------------------------------------------------------------------------- - // Get user data - // ------------------------------------------------------------------------- - vm = VirtualMachineDeploy::vmpool->get(vid,true); - - if ( vm == 0 ) - { - goto error_vm_get; - } - - uid = vm->get_uid(); - - vm->unlock(); - - // ------------------------------------------------------------------------- - // Authorize the operation - // ------------------------------------------------------------------------- - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::VM,vid,AuthRequest::MANAGE,uid,false); - ar.add_auth(AuthRequest::HOST,hid,AuthRequest::USE,0,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // ------------------------------------------------------------------------- - // Get host info to deploy the VM - // ------------------------------------------------------------------------- - host = VirtualMachineDeploy::hpool->get(hid,true); - - if ( host == 0 ) - { - goto error_host_get; - } - - hostname = host->get_name(); - vmm_mad = host->get_vmm_mad(); - tm_mad = host->get_tm_mad(); - - nd.get_configuration_attribute("VM_DIR",vmdir); - - host->unlock(); - - // ------------------------------------------------------------------------- - // Deploy the VM - // ------------------------------------------------------------------------- - vm = VirtualMachineDeploy::vmpool->get(vid,true); - - if ( vm == 0 ) - { - goto error_vm_get; - } - - if ( vm->get_state() != VirtualMachine::PENDING ) - { - goto error_state; - } - - vm->add_history(hid,hostname,vmdir,vmm_mad,tm_mad); - - rc = VirtualMachineDeploy::vmpool->update_history(vm); - - if ( rc != 0 ) - { - goto error_history; - } - - vmpool->update(vm); //Insert last_seq in the DB - - dm->deploy(vm); - - vm->unlock(); - - // ------------------------------------------------------------------------- - // Results - // ------------------------------------------------------------------------- - arrayData.push_back(xmlrpc_c::value_boolean(true)); - - arrayresult = new xmlrpc_c::value_array(arrayData); - - *retval = *arrayresult; - - delete arrayresult; - - return; - -error_host_get: - oss.str(get_error(method_name, "HOST", hid)); - goto error_common; - -error_vm_get: - oss.str(get_error(method_name, "VM", vid)); - goto error_common; - -error_state: - oss << action_error(method_name, "MANAGE", "VM", vid, -1) - << ". Reason: VM in wrong state."; - goto error_common_lock; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "VM", rc, vid)); - goto error_common; - -error_history: - oss.str(action_error(method_name, "INSERT HISTORY", "VM", vid, rc)); - goto error_common_lock; - -error_common_lock: - vm->unlock(); - -error_common: - arrayData.push_back(xmlrpc_c::value_boolean(false)); - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerHost.cc b/src/rm/RequestManagerHost.cc new file mode 100644 index 0000000000..4bc013ff32 --- /dev/null +++ b/src/rm/RequestManagerHost.cc @@ -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. */ +/* -------------------------------------------------------------------------- */ + +#include "RequestManagerHost.h" +#include "Nebula.h" + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void HostEnable::request_execute(xmlrpc_c::paramList const& paramList) +{ + int id = xmlrpc_c::value_int(paramList.getInt(1)); + bool enable = xmlrpc_c::value_boolean(paramList.getBoolean(2)); + + Host * host; + + HostPool * hpool = static_cast(pool); + + string error_str; + + if ( basic_authorization(id) == false ) + { + return; + } + + host = hpool->get(id,true); + + if ( host == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),id)); + return; + } + + if ( enable == true) + { + host->enable(); + } + else + { + host->disable(); + } + + hpool->update(host); + + host->unlock(); + + success_response(id); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + diff --git a/src/rm/RequestManagerHostAllocate.cc b/src/rm/RequestManagerHostAllocate.cc deleted file mode 100644 index 2ed8eaf9b3..0000000000 --- a/src/rm/RequestManagerHostAllocate.cc +++ /dev/null @@ -1,128 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::HostAllocate::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - string hostname; - string im_mad_name; - string vmm_mad_name; - string tm_mad_name; - - string error_str; - - const string method_name = "HostAllocate"; - - int hid; - - int rc; - ostringstream oss; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"HostAllocate method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - hostname = xmlrpc_c::value_string(paramList.getString(1)); - im_mad_name = xmlrpc_c::value_string(paramList.getString(2)); - vmm_mad_name = xmlrpc_c::value_string(paramList.getString(3)); - tm_mad_name = xmlrpc_c::value_string(paramList.getString(4)); - - //Authenticate the user - rc = HostAllocate::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::HOST,-1,AuthRequest::CREATE,0,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Perform the allocation in the hostpool - rc = HostAllocate::hpool->allocate(&hid, - hostname, - im_mad_name, - vmm_mad_name, - tm_mad_name, - error_str); - if ( rc == -1 ) - { - goto error_host_allocate; - } - - // All nice, return the new hid to client - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - arrayData.push_back(xmlrpc_c::value_int(hid)); - 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_authorize: - oss.str(authorization_error(method_name, "CREATE", "HOST", rc, -1)); - goto error_common; - -error_host_allocate: - oss << action_error(method_name, "CREATE", "HOST", -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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerHostDelete.cc b/src/rm/RequestManagerHostDelete.cc deleted file mode 100644 index fa8bc3e968..0000000000 --- a/src/rm/RequestManagerHostDelete.cc +++ /dev/null @@ -1,128 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::HostDelete::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - // of the host to delete from the HostPool - int hid; - Host * host; - ostringstream oss; - int rc; - - const string method_name = "HostDelete"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"HostDelete method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - hid = xmlrpc_c::value_int (paramList.getInt(1)); - - //Authenticate the user - rc = HostDelete::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::HOST,hid,AuthRequest::DELETE,0,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Perform the deletion from the hostpool - host = HostDelete::hpool->get(hid,true); - - if ( host == 0 ) - { - goto error_host_get; - } - - rc = HostDelete::hpool->drop(host); - - host->unlock(); - - if ( rc != 0 ) - { - goto error_host_drop; - } - - // All nice, return the host info to the client - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - 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_authorize: - oss.str(authorization_error(method_name, "DELETE", "HOST", rc, hid)); - goto error_common; - -error_host_get: - oss.str(get_error(method_name, "HOST", hid)); - goto error_common; - -error_host_drop: - oss.str(action_error(method_name, "DELETE", "HOST", hid, rc)); - goto error_common; - -error_common: - NebulaLog::log ("Rem",Log::ERROR,oss); - - arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE - arrayData.push_back(xmlrpc_c::value_string(oss.str())); - - xmlrpc_c::value_array arrayresult_error(arrayData); - - *retval = arrayresult_error; - - return; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerHostEnable.cc b/src/rm/RequestManagerHostEnable.cc deleted file mode 100644 index 5e10757261..0000000000 --- a/src/rm/RequestManagerHostEnable.cc +++ /dev/null @@ -1,127 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::HostEnable::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int hid; - int rc; - bool enable; - Host * host; - ostringstream oss; - - const string method_name = "HostEnable"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"HostEnable method invoked"); - - // Get the parameters & host - session = xmlrpc_c::value_string(paramList.getString(0)); - hid = xmlrpc_c::value_int(paramList.getInt(1)); - enable = xmlrpc_c::value_boolean(paramList.getBoolean(2)); - - //Authenticate the user - rc = HostEnable::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::HOST,hid,AuthRequest::MANAGE,0,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - host = HostEnable::hpool->get(hid,true); - - if ( host == 0 ) - { - goto error_host_get; - } - - if ( enable == true) - { - host->enable(); - } - else - { - host->disable(); - } - - HostEnable::hpool->update(host); - - host->unlock(); - - //Result - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayresult = new xmlrpc_c::value_array(arrayData); - - *retval = *arrayresult; - - delete arrayresult; - - return; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "HOST", rc, hid)); - goto error_common; - -error_host_get: - oss.str(get_error(method_name, "HOST", hid)); - goto error_common; - -error_common: - NebulaLog::log("ReM",Log::ERROR,oss); - - arrayData.push_back(xmlrpc_c::value_boolean(false)); - arrayData.push_back(xmlrpc_c::value_string(oss.str())); - - xmlrpc_c::value_array arrayresult_error(arrayData); - - *retval = arrayresult_error; - - return; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerHostInfo.cc b/src/rm/RequestManagerHostInfo.cc deleted file mode 100644 index f78fbb4d6d..0000000000 --- a/src/rm/RequestManagerHostInfo.cc +++ /dev/null @@ -1,101 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::HostInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int hid; - int rc; - Host * host; - - ostringstream oss; - - const string method_name = "HostInfo"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"HostInfo method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - hid = xmlrpc_c::value_int (paramList.getInt(1)); - - //Authenticate the user - rc = HostInfo::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - // Get the host from the HostPool - host = HostInfo::hpool->get(hid,true); - - if ( host == 0 ) - { - goto error_host_get; - } - - oss << *host; - - host->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_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_host_get: - oss.str(get_error(method_name, "HOST", hid)); - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerHostPoolInfo.cc b/src/rm/RequestManagerHostPoolInfo.cc deleted file mode 100644 index bab4dfe4e3..0000000000 --- a/src/rm/RequestManagerHostPoolInfo.cc +++ /dev/null @@ -1,95 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::HostPoolInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - ostringstream oss; - int rc; - - const string method_name = "HostPoolInfo"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"HostPoolInfo method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - - //Authenticate the user - rc = HostPoolInfo::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - // Perform the allocation in the vmpool - rc = HostPoolInfo::hpool->dump(oss,""); - - if ( rc != 0 ) - { - goto error_dump; - } - - //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())); - - 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_dump: - oss.str(get_error(method_name, "HOST", -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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerImage.cc b/src/rm/RequestManagerImage.cc new file mode 100644 index 0000000000..25de63586e --- /dev/null +++ b/src/rm/RequestManagerImage.cc @@ -0,0 +1,109 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "RequestManagerImage.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void ImageEnable::request_execute(xmlrpc_c::paramList const& paramList) +{ + int id = xmlrpc_c::value_int(paramList.getInt(1)); + bool enable_flag = xmlrpc_c::value_boolean(paramList.getBoolean(2)); + int rc; + + string err_msg; + + Nebula& nd = Nebula::instance(); + ImageManager * imagem = nd.get_imagem(); + + if ( basic_authorization(id) == false ) + { + return; + } + + rc = imagem->enable_image(id,enable_flag); + + if( rc < 0 ) + { + if (enable_flag == true) + { + err_msg = "Could not enable image"; + } + else + { + err_msg = "Could not disable image"; + } + + failure_response(INTERNAL, request_error(err_msg,"")); + return; + } + + success_response(id); +} + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void ImagePersistent::request_execute(xmlrpc_c::paramList const& paramList) +{ + int id = xmlrpc_c::value_int(paramList.getInt(1)); + bool persistent_flag = xmlrpc_c::value_boolean(paramList.getBoolean(2)); + int rc; + + Image * image; + string err_msg; + + if ( basic_authorization(id) == false ) + { + return; + } + + image = static_cast(pool->get(id,true)); + + if ( image == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),id)); + return; + } + + rc = image->persistent(persistent_flag); + + if ( rc != 0 ) + { + if (persistent_flag == true) + { + err_msg = "Could not make image persistent"; + } + else + { + err_msg = "Could not make image non-persistent"; + } + + failure_response(INTERNAL,request_error(err_msg,"")); + + image->unlock(); + return; + } + + pool->update(image); + + image->unlock(); + + success_response(id); +} diff --git a/src/rm/RequestManagerImageAllocate.cc b/src/rm/RequestManagerImageAllocate.cc deleted file mode 100644 index 8e435f57c5..0000000000 --- a/src/rm/RequestManagerImageAllocate.cc +++ /dev/null @@ -1,200 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ImageAllocate::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - string str_template; - string error_str; - string user_name; - - ImageTemplate * img_template = 0; - User * user; - - int iid; - int uid; - int rc; - char * error_msg = 0; - - ostringstream oss; - - const string method_name = "ImageAllocate"; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - Nebula& nd = Nebula::instance(); - ImageManager * imagem = nd.get_imagem(); - - NebulaLog::log("ReM",Log::DEBUG,"ImageAllocate invoked"); - - session = xmlrpc_c::value_string(paramList.getString(0)); - str_template = xmlrpc_c::value_string(paramList.getString(1)); - str_template += "\n"; - - //-------------------------------------------------------------------------- - // Authenticate this request - //-------------------------------------------------------------------------- - uid = ImageAllocate::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - //-------------------------------------------------------------------------- - // Authorize this request - //-------------------------------------------------------------------------- - img_template = new ImageTemplate; - - rc = img_template->parse(str_template,&error_msg); - - if ( rc != 0 ) - { - goto error_parse; - } - - if ( uid != 0 ) - { - AuthRequest ar(uid); - string t64; - string pub; - string pub_name = "PUBLIC"; - - img_template->get(pub_name, pub); - transform (pub.begin(), pub.end(), pub.begin(),(int(*)(int))toupper); - - ar.add_auth(AuthRequest::IMAGE, - img_template->to_xml(t64), - AuthRequest::CREATE, - uid, - (pub == "YES")); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - //-------------------------------------------------------------------------- - // Get the User Name - //-------------------------------------------------------------------------- - - user = ImageAllocate::upool->get(uid,true); - - if ( user == 0 ) - { - goto error_user_get; - } - - user_name = user->get_name(); - - user->unlock(); - - //-------------------------------------------------------------------------- - // Allocate the Image - //-------------------------------------------------------------------------- - - rc = ImageAllocate::ipool->allocate(uid,user_name, - img_template,&iid, error_str); - - if ( rc < 0 ) - { - goto error_allocate; - } - - //-------------------------------------------------------------------------- - // Register the Image in the repository - //-------------------------------------------------------------------------- - if ( imagem->register_image(rc) == -1 ) - { - goto error_register; - } - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(iid)); - - // 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 img_template; - goto error_common; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "CREATE", "IMAGE", uid, -1)); - delete img_template; - goto error_common; - -error_parse: - oss << action_error(method_name, "PARSE", "IMAGE TEMPLATE",-2,rc); - if (error_msg != 0) - { - oss << ". Reason: " << error_msg; - free(error_msg); - } - - delete img_template; - goto error_common; - -error_allocate: - oss << action_error(method_name, "CREATE", "IMAGE", -2, 0); - oss << " " << error_str; - goto error_common; - -error_register: - oss << action_error(method_name, "CREATE", "IMAGE", -2, 0); - oss << " Failed to copy image to repository. Image left in ERROR state."; - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerImageDelete.cc b/src/rm/RequestManagerImageDelete.cc deleted file mode 100644 index 3a2c812f9d..0000000000 --- a/src/rm/RequestManagerImageDelete.cc +++ /dev/null @@ -1,147 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ImageDelete::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int iid; - int uid; - int rc; - - int image_owner; - bool is_public; - - Image * image; - - ostringstream oss; - - const string method_name = "ImageDelete"; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - Nebula& nd = Nebula::instance(); - ImageManager * imagem = nd.get_imagem(); - - NebulaLog::log("ReM",Log::DEBUG,"ImageDelete invoked"); - - session = xmlrpc_c::value_string(paramList.getString(0)); - iid = xmlrpc_c::value_int (paramList.getInt(1)); - - - // First, we need to authenticate the user - uid = ImageDelete::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - // Get image from the ImagePool - image = ImageDelete::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - image_owner = image->get_uid(); - is_public = image->isPublic(); - - image->unlock(); - - //Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::IMAGE, - iid, - AuthRequest::DELETE, - image_owner, - is_public); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Delete the Image from the repository - rc = imagem->delete_image(iid); - - if ( rc < 0 ) - { - goto error_delete; - } - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(iid)); - - // 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_image_get: - oss.str(get_error(method_name, "IMAGE", iid)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "DELETE", "IMAGE", uid, iid)); - goto error_common; - -error_delete: - oss << action_error(method_name, "DELETE", "IMAGE", iid, rc) - << ". Image is in use."; - image->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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerImageEnable.cc b/src/rm/RequestManagerImageEnable.cc deleted file mode 100644 index 41720e3bc9..0000000000 --- a/src/rm/RequestManagerImageEnable.cc +++ /dev/null @@ -1,154 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ImageEnable::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - string err_msg; - - int iid; - bool enable_flag; - int uid; - int rc; - - int image_owner; - bool is_public; - - Image * image; - - ostringstream oss; - - const string method_name = "ImageEnable"; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - Nebula& nd = Nebula::instance(); - ImageManager * imagem = nd.get_imagem(); - - NebulaLog::log("ReM",Log::DEBUG,"ImageEnable invoked"); - - session = xmlrpc_c::value_string (paramList.getString(0)); - iid = xmlrpc_c::value_int (paramList.getInt(1)); - enable_flag = xmlrpc_c::value_boolean(paramList.getBoolean(2)); - - // First, we need to authenticate the user - uid = ImageEnable::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - // Get image from the ImagePool - image = ImageEnable::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - image_owner = image->get_uid(); - is_public = image->isPublic(); - - image->unlock(); - - //Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::IMAGE, - iid, - AuthRequest::MANAGE, - image_owner, - is_public); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Enable the Image - rc = imagem->enable_image(iid,enable_flag); - - if ( rc < 0 ) - { - goto error_enable; - } - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(iid)); - - // 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_image_get: - oss.str(get_error(method_name, "IMAGE", iid)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "IMAGE", uid, iid)); - goto error_common; - -error_enable: - if (enable_flag == TRUE) - { - err_msg = "ENABLE"; - } else { - err_msg = "DISABLE"; - } - oss.str(action_error(method_name, err_msg, "IMAGE", iid, rc)); - image->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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerImageInfo.cc b/src/rm/RequestManagerImageInfo.cc deleted file mode 100644 index f8a1fdc64a..0000000000 --- a/src/rm/RequestManagerImageInfo.cc +++ /dev/null @@ -1,103 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ImageInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int iid; - int rc; // Requesting user id - Image * image; - - ostringstream oss; - - const string method_name = "ImageInfo"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"ImageInfo method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - iid = xmlrpc_c::value_int (paramList.getInt(1)); - - // Check if it is a valid user - rc = ImageInfo::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - // Get image from the ImagePool - image = ImageInfo::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - oss << *image; - - image->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_image_get: - oss.str(get_error(method_name, "IMAGE", iid)); - goto error_common; - -error_authenticate: - oss.str(authenticate_error(method_name)); - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerImagePersistent.cc b/src/rm/RequestManagerImagePersistent.cc deleted file mode 100644 index cc00ba7f3e..0000000000 --- a/src/rm/RequestManagerImagePersistent.cc +++ /dev/null @@ -1,157 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ImagePersistent::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int iid; - bool persistent_flag; - int uid; - - int image_owner; - bool is_public; - - Image * image; - - ostringstream oss; - - bool response; - - const string method_name = "ImagePersistent"; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - - NebulaLog::log("ReM",Log::DEBUG,"ImagePersistent invoked"); - - session = xmlrpc_c::value_string (paramList.getString(0)); - iid = xmlrpc_c::value_int (paramList.getInt(1)); - persistent_flag = xmlrpc_c::value_boolean(paramList.getBoolean(2)); - - // First, we need to authenticate the user - uid = ImagePersistent::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - // Get image from the ImagePool - image = ImagePersistent::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - image_owner = image->get_uid(); - is_public = image->isPublic(); - - image->unlock(); - - //Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::IMAGE, - iid, - AuthRequest::MANAGE, - image_owner, - is_public); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Get the image locked again - image = ImagePersistent::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - response = image->persistent(persistent_flag); - - if (!response) - { - goto error_persistent; - } - - ImagePersistent::ipool->update(image); - - image->unlock(); - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(iid)); - - // 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_image_get: - oss.str(get_error(method_name, "IMAGE", iid)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "IMAGE", uid, iid)); - goto error_common; - -error_persistent: - image->unlock(); - oss.str(action_error(method_name, "MANAGE", "IMAGE", iid, 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerImagePoolInfo.cc b/src/rm/RequestManagerImagePoolInfo.cc deleted file mode 100644 index a55d07e230..0000000000 --- a/src/rm/RequestManagerImagePoolInfo.cc +++ /dev/null @@ -1,124 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ImagePoolInfo::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 = "ImagePoolInfo"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"ImagePoolInfo 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 = ImagePoolInfo::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - /** Filter flag meaning table - * -2 :: All Images - * -1 :: User's Images AND public images belonging to any user - * >= 0 :: UID User's Images - **/ - 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 image pool dump - rc = ImagePoolInfo::ipool->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, "IMAGE", -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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerImagePublish.cc b/src/rm/RequestManagerImagePublish.cc deleted file mode 100644 index 08cc5dd403..0000000000 --- a/src/rm/RequestManagerImagePublish.cc +++ /dev/null @@ -1,159 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ImagePublish::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int iid; - bool publish_flag; - int uid; - - int image_owner; - bool is_public; - - Image * image; - - bool response; - - ostringstream oss; - - const string method_name = "ImagePublish"; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - - NebulaLog::log("ReM",Log::DEBUG,"ImagePublish invoked"); - - session = xmlrpc_c::value_string (paramList.getString(0)); - iid = xmlrpc_c::value_int (paramList.getInt(1)); - publish_flag = xmlrpc_c::value_boolean(paramList.getBoolean(2)); - - // First, we need to authenticate the user - uid = ImagePublish::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - // Get image from the ImagePool - image = ImagePublish::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - image_owner = image->get_uid(); - is_public = image->isPublic(); - - image->unlock(); - - //Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::IMAGE, - iid, - AuthRequest::MANAGE, - image_owner, - is_public); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Get the image locked again - image = ImagePublish::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - response = image->publish(publish_flag); - - if (!response) - { - image->unlock(); - - goto error_publish; - } - - ImagePublish::ipool->update(image); - - image->unlock(); - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(iid)); - - // 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_image_get: - oss.str(get_error(method_name, "IMAGE", iid)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "IMAGE", uid, iid)); - goto error_common; - -error_publish: - oss<< action_error(method_name, "MANAGE", "IMAGE", iid, 0) - <<". Is the image persistent? An Image cannot be public and persistent."; - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerImageRemoveAttribute.cc b/src/rm/RequestManagerImageRemoveAttribute.cc deleted file mode 100644 index 8f29ff88cb..0000000000 --- a/src/rm/RequestManagerImageRemoveAttribute.cc +++ /dev/null @@ -1,159 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ImageRemoveAttribute::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - string name; - - int iid; - int uid; - int rc; - - int image_owner; - bool is_public; - - Image * image; - - ostringstream oss; - - const string method_name = "ImageRemoveAttribute"; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - - NebulaLog::log("ReM",Log::DEBUG,"ImageRemoveAttribute invoked"); - - session = xmlrpc_c::value_string(paramList.getString(0)); - iid = xmlrpc_c::value_int (paramList.getInt(1)); - name = xmlrpc_c::value_string(paramList.getString(2)); - - // First, we need to authenticate the user - uid = ImageRemoveAttribute::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - // Get image from the ImagePool - image = ImageRemoveAttribute::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - image_owner = image->get_uid(); - is_public = image->isPublic(); - - image->unlock(); - - //Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::IMAGE, - iid, - AuthRequest::MANAGE, - image_owner, - is_public); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Get image from the ImagePool - image = ImageRemoveAttribute::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - rc = image->remove_template_attribute(name); - - if(rc == 0) - { - rc = ImageRemoveAttribute::ipool->update(image); - } - - if ( rc < 0 ) - { - goto error_remove_attribute; - } - - image->unlock(); - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(iid)); - - // 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_image_get: - oss.str(get_error(method_name, "IMAGE", iid)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "IMAGE", uid, iid)); - goto error_common; - -error_remove_attribute: - oss.str(action_error(method_name, "PUBLISH/UNPUBLISH", "IMAGE", iid, rc)); - image->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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerImageUpdate.cc b/src/rm/RequestManagerImageUpdate.cc deleted file mode 100644 index 417f76fb87..0000000000 --- a/src/rm/RequestManagerImageUpdate.cc +++ /dev/null @@ -1,160 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::ImageUpdate::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int iid; - int uid; - string name; - string value; - int rc; - - int image_owner; - bool is_public; - - Image * image; - - ostringstream oss; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - const string method_name = "ImageUpdate"; - - NebulaLog::log("ReM",Log::DEBUG,"ImageUpdate invoked"); - - session = xmlrpc_c::value_string(paramList.getString(0)); - iid = 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 = ImageUpdate::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - // Get image from the ImagePool - image = ImageUpdate::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - image_owner = image->get_uid(); - is_public = image->isPublic(); - - image->unlock(); - - //Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::IMAGE, - iid, - AuthRequest::MANAGE, - image_owner, - is_public); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Get image from the ImagePool - image = ImageUpdate::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; - } - - rc = image->replace_template_attribute(name, value); - - if(rc == 0) - { - rc = ImageUpdate::ipool->update(image); - } - - if ( rc < 0 ) - { - goto error_update; - } - - image->unlock(); - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(iid)); - - // 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_image_get: - oss.str(get_error(method_name, "IMAGE", iid)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "IMAGE", uid, iid)); - goto error_common; - -error_update: - oss.str(action_error(method_name, "UPDATE ATTRIBUTE", "IMAGE", iid, rc)); - image->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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerInfo.cc b/src/rm/RequestManagerInfo.cc index 59394aea34..052524c4e7 100644 --- a/src/rm/RequestManagerInfo.cc +++ b/src/rm/RequestManagerInfo.cc @@ -14,87 +14,39 @@ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ -#include "RequestManager.h" -#include "NebulaLog.h" +#include "RequestManagerInfo.h" -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ +using namespace std; -void RequestManager::VirtualMachineInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void RequestManagerInfo::request_execute(xmlrpc_c::paramList const& paramList) { - string session; + int oid = xmlrpc_c::value_int(paramList.getInt(1)); + PoolObjectSQL * object; + string str; - int vid, rc; - VirtualMachine * vm; - - ostringstream oss; - - const string method_name = "VirtualMachineInfo"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualMachineInfo method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - vid = xmlrpc_c::value_int (paramList.getInt(1)); - - // Check if it is a valid user - rc = VirtualMachineInfo::upool->authenticate(session); - - if ( rc == -1 ) + if ( basic_authorization(oid) == false ) { - goto error_authenticate; + return; } - // Get the details of the virtual machine - vm = VirtualMachineInfo::vmpool->get(vid,true); + object = pool->get(oid,true); - if ( vm == 0 ) - { - goto error_vm_get; - } + if ( object == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),oid)); + return; + } - oss << *vm; - vm->unlock(); + object->to_xml(str); - // All nice, return the vm info to the client - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - arrayData.push_back(xmlrpc_c::value_string(oss.str())); + object->unlock(); - // 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_vm_get: - oss.str(get_error(method_name, "VM", vid)); - 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; + success_response(str); return; } -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerMigrate.cc b/src/rm/RequestManagerMigrate.cc deleted file mode 100644 index 9761692b33..0000000000 --- a/src/rm/RequestManagerMigrate.cc +++ /dev/null @@ -1,191 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::VirtualMachineMigrate::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - int vid; - int hid; - int uid; - int rc; - bool live; - - string hostname; - string vmm_mad; - string tm_mad; - string vmdir; - - VirtualMachine * vm; - Host * host; - - Nebula& nd = Nebula::instance(); - DispatchManager * dm = nd.get_dm(); - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - ostringstream oss; - - const string method_name = "VirtualMachineMigrate"; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualMachineMigrate invoked"); - - //Parse Arguments - session = xmlrpc_c::value_string(paramList.getString(0)); - vid = xmlrpc_c::value_int(paramList.getInt(1)); - hid = xmlrpc_c::value_int(paramList.getInt(2)); - live = xmlrpc_c::value_boolean(paramList.getBoolean(3)); - - //Get host info to migrate the VM - host = VirtualMachineMigrate::hpool->get(hid,true); - - if ( host == 0 ) - { - goto error_host_get; - } - - hostname = host->get_name(); - vmm_mad = host->get_vmm_mad(); - tm_mad = host->get_tm_mad(); - - nd.get_configuration_attribute("VM_DIR",vmdir); - - host->unlock(); - - //Get the VM and migrate it - vm = VirtualMachineMigrate::vmpool->get(vid,true); - - if ( vm == 0 ) - { - goto error_vm_get; - } - - uid = vm->get_uid(); - - // Only oneadmin or the VM owner can perform operations upon the VM - rc = VirtualMachineMigrate::upool->authenticate(session); - - if ( rc == -1) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::VM,vid,AuthRequest::MANAGE,uid,false); - ar.add_auth(AuthRequest::HOST,hid,AuthRequest::USE,0,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - if((vm->get_state() != VirtualMachine::ACTIVE) || - (vm->get_lcm_state() != VirtualMachine::RUNNING) || - (vm->hasPreviousHistory() && vm->get_previous_reason() == History::NONE)) - { - goto error_state; - } - - vm->add_history(hid,hostname,vmdir,vmm_mad,tm_mad); - - rc = VirtualMachineMigrate::vmpool->update_history(vm); - - if ( rc != 0 ) - { - goto error_history; - } - - vmpool->update(vm); //Insert last_seq in the DB - - if ( live == true ) - { - dm->live_migrate(vm); - } - else - { - dm->migrate(vm); - } - - vm->unlock(); - - // Send results to client - arrayData.push_back(xmlrpc_c::value_boolean(true)); - - arrayresult = new xmlrpc_c::value_array(arrayData); - - *retval = *arrayresult; - - delete arrayresult; - - return; - - -error_host_get: - oss.str(get_error(method_name, "HOST", hid)); - goto error_common; - -error_vm_get: - oss.str(get_error(method_name, "VM", vid)); - goto error_common; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common_lock; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "VM", uid, vid)); - goto error_common_lock; - -error_history: - oss.str(action_error(method_name, "INSERT HISTORY", "VM", vid, rc)); - goto error_common_lock; - -error_state: - oss << action_error(method_name, "MANAGE", "VM", vid, rc) - << ". Reason: VM in wrong state."; - goto error_common_lock; - -error_common_lock: - vm->unlock(); - -error_common: - arrayData.push_back(xmlrpc_c::value_boolean(false)); - arrayData.push_back(xmlrpc_c::value_string(oss.str())); - - xmlrpc_c::value_array arrayresult_error(arrayData); - - *retval = arrayresult_error; - - return; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerPoolInfo.cc b/src/rm/RequestManagerPoolInfo.cc index 772c68d284..024a1854b7 100644 --- a/src/rm/RequestManagerPoolInfo.cc +++ b/src/rm/RequestManagerPoolInfo.cc @@ -14,115 +14,34 @@ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ -#include "RequestManager.h" -#include "NebulaLog.h" +#include "RequestManagerPoolInfo.h" -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ +using namespace std; -void RequestManager::VirtualMachinePoolInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void RequestManagerPoolInfo::request_execute(xmlrpc_c::paramList const& paramList) { - string session; - string username; - string password; + ostringstream oss; + int rc; - int filter_flag; - int rc; - int state; - - ostringstream oss; - ostringstream where_string; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - const string method_name = "VirtualMachinePoolInfo"; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualMachinePoolInfo method invoked"); - - // For backwards compatibility, 2 or 3 arguments can be present. - switch (paramList.size()) + if ( basic_authorization(-1) == false ) { - case 2: - state = -1; - break; - case 3: - state = xmlrpc_c::value_int (paramList.getInt(2)); - break; - default: - paramList.verifyEnd(3); - return; + return; } - // 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 = VirtualMachinePoolInfo::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - /* Filter flag meaning table - * <=-2 :: ALL VMs - * -1 :: User's VMs - * >=0 :: UID User's VMs - */ - if (filter_flag == -1) - { - where_string << "UID=" << rc; - } - else if (filter_flag>=0) - { - where_string << "UID=" << filter_flag; - } - - rc = VirtualMachinePoolInfo::vmpool->dump(oss, state, where_string.str()); + // Call the template pool dump + rc = pool->dump(oss,""); if ( rc != 0 ) { - goto error_dump; + failure_response(INTERNAL,request_error("Internal Error","")); + return; } - // All nice, return the vm 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_dump: - oss.str(get_error(method_name, "VM", -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; + success_response(oss.str()); return; } -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - diff --git a/src/rm/RequestManagerPoolInfoFilter.cc b/src/rm/RequestManagerPoolInfoFilter.cc new file mode 100644 index 0000000000..88a4fe2647 --- /dev/null +++ b/src/rm/RequestManagerPoolInfoFilter.cc @@ -0,0 +1,85 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "RequestManagerPoolInfoFilter.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +const int RequestManagerPoolInfoFilter::ALL = -2; + +const int RequestManagerPoolInfoFilter::MINE = -3; + +const int RequestManagerPoolInfoFilter::MINE_GROUP = -1; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void RequestManagerPoolInfoFilter::request_execute(xmlrpc_c::paramList const& paramList) +{ + int filter_flag = xmlrpc_c::value_int(paramList.getInt(1)); + + ostringstream oss, where_string; + + int rc; + + if ( filter_flag < MINE ) + { + failure_response(XML_RPC_API, request_error("Incorrect filter_flag","")); + return; + } + + switch(filter_flag) + { + case MINE: + where_string << "UID=" << uid; + auth_op = AuthRequest::INFO_POOL_MINE; + break; + + case ALL: + break; + + case MINE_GROUP: + where_string << "UID=" << uid << " OR GID=" << gid; + auth_op = AuthRequest::INFO_POOL_MINE; + break; + + default: + where_string << "UID=" << filter_flag; + break; + } + + if ( basic_authorization(-1) == false ) + { + return; + } + + // Call the template pool dump + rc = pool->dump(oss,where_string.str()); + + if ( rc != 0 ) + { + failure_response(INTERNAL,request_error("Internal Error","")); + return; + } + + success_response(oss.str()); + + return; +} + diff --git a/src/rm/RequestManagerPublish.cc b/src/rm/RequestManagerPublish.cc new file mode 100644 index 0000000000..370efa4ced --- /dev/null +++ b/src/rm/RequestManagerPublish.cc @@ -0,0 +1,62 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "RequestManagerPublish.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void RequestManagerPublish::request_execute(xmlrpc_c::paramList const& paramList) +{ + int oid = xmlrpc_c::value_int(paramList.getInt(1)); + bool pflag = xmlrpc_c::value_boolean(paramList.getBoolean(2)); + PoolObjectSQL * object; + + if ( basic_authorization(oid) == false ) + { + return; + } + + object = pool->get(oid,true); + + if ( object == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),oid)); + return; + } + + int rc = publish(object,pflag); + + if ( rc != 0 ) + { + failure_response(INTERNAL, + request_error("Can not publish/unpublish resource","")); + + object->unlock(); + return; + } + + pool->update(object); + + object->unlock(); + + success_response(oid); + + return; +} + diff --git a/src/rm/RequestManagerSaveDisk.cc b/src/rm/RequestManagerSaveDisk.cc deleted file mode 100644 index 28da4e1271..0000000000 --- a/src/rm/RequestManagerSaveDisk.cc +++ /dev/null @@ -1,282 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::VirtualMachineSaveDisk::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int vm_id; - int disk_id; - int iid; - string img_name; - - int vm_owner; - string user_name; - - int rc; - int uid; - string estr; - char * error_char; - string error_str; - - const string method_name = "VirtualMachineSaveDisk"; - - VirtualMachine * vm; - Image * image; - ImageTemplate * img_template; - User * user; - - Image * source_img; - int source_img_id; - bool source_img_persistent = false; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - ostringstream oss; - - Nebula& nd = Nebula::instance(); - ImageManager * imagem = nd.get_imagem(); - - NebulaLog::log("ReM",Log::DEBUG,"VirtualMachineSaveDisk invoked"); - - //Parse Arguments - session = xmlrpc_c::value_string(paramList.getString(0)); - vm_id = xmlrpc_c::value_int(paramList.getInt(1)); - disk_id = xmlrpc_c::value_int(paramList.getInt(2)); - img_name = xmlrpc_c::value_string(paramList.getString(3)); - - //------------------------------------------------------------------------- - // Authenticate the user - //------------------------------------------------------------------------- - uid = VirtualMachineSaveDisk::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - user = VirtualMachineSaveDisk::upool->get(uid,true); - - if ( user == 0 ) - { - goto error_user_get; - } - - user_name = user->get_name(); - - user->unlock(); - - //------------------------------------------------------------------------- - // Check that the image does not exist & prepare the template - //------------------------------------------------------------------------- - image = VirtualMachineSaveDisk::ipool->get(img_name,uid,false); - - if ( image != 0 ) - { - goto error_image_exists; - } - - oss << "NAME= " << img_name << endl; - oss << "PUBLIC = NO " << endl; - oss << "SOURCE = - " << endl; - - img_template = new ImageTemplate; - - img_template->parse(oss.str(),&error_char); - - oss.str(""); - - //-------------------------------------------------------------------------- - // Get the VM - //-------------------------------------------------------------------------- - vm = VirtualMachineSaveDisk::vmpool->get(vm_id,true); - - if ( vm == 0 ) - { - delete img_template; - goto error_vm_get; - } - - vm_owner = vm->get_uid(); - - vm->unlock(); - - //-------------------------------------------------------------------------- - // Authorize the operation - //-------------------------------------------------------------------------- - if ( uid != 0 ) - { - AuthRequest ar(uid); - string t64; - - ar.add_auth(AuthRequest::VM,vm_id,AuthRequest::MANAGE,vm_owner,false); - ar.add_auth(AuthRequest::IMAGE, - img_template->to_xml(t64), - AuthRequest::CREATE, - uid, - false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - //-------------------------------------------------------------------------- - // Create the image - //-------------------------------------------------------------------------- - rc = VirtualMachineSaveDisk::ipool->allocate(uid,user_name,img_template, - &iid,estr); - - if ( rc < 0 ) - { - goto error_allocate; - } - - oss << "Image " << img_name << " created to store disk."; - - NebulaLog::log("ReM",Log::INFO,oss); - oss.str(""); - - //-------------------------------------------------------------------------- - // Get the VM - //-------------------------------------------------------------------------- - vm = VirtualMachineSaveDisk::vmpool->get(vm_id,true); - - if ( vm == 0 ) - { - goto error_vm_get; - } - - //-------------------------------------------------------------------------- - // Check if the disk has a persistent source image - //-------------------------------------------------------------------------- - oss << "/VM/TEMPLATE/DISK[DISK_ID=" << disk_id << "]/IMAGE_ID"; - rc = vm->xpath(source_img_id, oss.str().c_str(), -1); - oss.str(""); - - if( rc == 0 ) //The disk was created from an Image - { - source_img = VirtualMachineSaveDisk::ipool->get(source_img_id, true); - - if( source_img != 0 ) //The Image still exists - { - source_img_persistent = source_img->isPersistent(); - source_img->unlock(); - - if( source_img_persistent ) - { - goto error_img_persistent; - } - } - } - - //-------------------------------------------------------------------------- - // Store image id to save the disk in the VM template - //-------------------------------------------------------------------------- - rc = vm->save_disk(disk_id, iid, error_str); - - if ( rc == -1 ) - { - goto error_vm_get_disk_id; - } - - VirtualMachineSaveDisk::vmpool->update(vm); - - vm->unlock(); - - //-------------------------------------------------------------------------- - // Send results to client - //-------------------------------------------------------------------------- - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(iid)); - - arrayresult = new xmlrpc_c::value_array(arrayData); - - *retval = *arrayresult; - - delete arrayresult; - - return; - -error_image_exists: - oss << action_error(method_name, "CREATE", "IMAGE", -2, 0); - oss << " Image " << img_name << " already exists in the repository."; - goto error_common; - -error_vm_get: - oss.str(get_error(method_name, "VM", vm_id)); - goto error_common; - -error_img_persistent: - oss << action_error(method_name, "SAVEDISK", "DISK", disk_id, 0); - oss << " Source IMAGE " << source_img_id << " is persistent."; - vm->unlock(); - goto error_common; - -error_vm_get_disk_id: - oss.str(get_error(method_name, "DISK from VM", vm_id)); - oss << " " << error_str; - oss << " Deleting Image " << img_name; - imagem->delete_image(iid); - vm->unlock(); - goto error_common; - -error_user_get: - oss.str(get_error(method_name, "USER", uid)); - goto error_common; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "VM/IMAGE", uid, vm_id)); - delete img_template; - goto error_common; - -error_allocate: - oss << action_error(method_name, "CREATE", "IMAGE", -2, 0); - oss << " " << estr; - goto error_common; - -error_common: - arrayData.push_back(xmlrpc_c::value_boolean(false)); - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - diff --git a/src/rm/RequestManagerTemplateAllocate.cc b/src/rm/RequestManagerTemplateAllocate.cc deleted file mode 100644 index 6ae07c1a44..0000000000 --- a/src/rm/RequestManagerTemplateAllocate.cc +++ /dev/null @@ -1,183 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerTemplateDelete.cc b/src/rm/RequestManagerTemplateDelete.cc deleted file mode 100644 index b222cc2883..0000000000 --- a/src/rm/RequestManagerTemplateDelete.cc +++ /dev/null @@ -1,153 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerTemplateInfo.cc b/src/rm/RequestManagerTemplateInfo.cc deleted file mode 100644 index ca6d15990a..0000000000 --- a/src/rm/RequestManagerTemplateInfo.cc +++ /dev/null @@ -1,104 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 rc; // Requesting user id - VMTemplate * vm_template; - - ostringstream oss; - - const string method_name = "TemplateInfo"; - - /* -- RPC specific vars -- */ - vector 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; - } - - // 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerTemplatePoolInfo.cc b/src/rm/RequestManagerTemplatePoolInfo.cc deleted file mode 100644 index 6a16807202..0000000000 --- a/src/rm/RequestManagerTemplatePoolInfo.cc +++ /dev/null @@ -1,124 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerTemplatePublish.cc b/src/rm/RequestManagerTemplatePublish.cc deleted file mode 100644 index 3e908c3ae9..0000000000 --- a/src/rm/RequestManagerTemplatePublish.cc +++ /dev/null @@ -1,158 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerTemplateRemoveAttribute.cc b/src/rm/RequestManagerTemplateRemoveAttribute.cc deleted file mode 100644 index c23737fdaa..0000000000 --- a/src/rm/RequestManagerTemplateRemoveAttribute.cc +++ /dev/null @@ -1,159 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerTemplateUpdate.cc b/src/rm/RequestManagerTemplateUpdate.cc deleted file mode 100644 index 86e210a718..0000000000 --- a/src/rm/RequestManagerTemplateUpdate.cc +++ /dev/null @@ -1,160 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerUpdateTemplate.cc b/src/rm/RequestManagerUpdateTemplate.cc new file mode 100644 index 0000000000..3e1a0a2c51 --- /dev/null +++ b/src/rm/RequestManagerUpdateTemplate.cc @@ -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. */ +/* -------------------------------------------------------------------------- */ + +#include "RequestManagerUpdateTemplate.h" + +using namespace std; + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void RequestManagerUpdateTemplate::request_execute(xmlrpc_c::paramList const& paramList) +{ + int rc; + string error_str; + + int oid = xmlrpc_c::value_int(paramList.getInt(1)); + string tmpl = xmlrpc_c::value_string(paramList.getString(2)); + + PoolObjectSQL * object; + + if ( basic_authorization(oid) == false ) + { + return; + } + + object = pool->get(oid,true); + + if ( object == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),oid)); + return; + } + + rc = object->replace_template(tmpl, error_str); + + if ( rc != 0 ) + { + failure_response(INTERNAL, request_error("Can not update template",error_str)); + object->unlock(); + + return; + } + + pool->update(object); + + object->unlock(); + + success_response(oid); + + return; +} + diff --git a/src/rm/RequestManagerUser.cc b/src/rm/RequestManagerUser.cc new file mode 100644 index 0000000000..93c8221911 --- /dev/null +++ b/src/rm/RequestManagerUser.cc @@ -0,0 +1,184 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "RequestManagerUser.h" + +using namespace std; + +void RequestManagerUser:: + request_execute(xmlrpc_c::paramList const& paramList) +{ + int id = xmlrpc_c::value_int(paramList.getInt(1)); + User * user; + string error_str; + + if ( basic_authorization(id) == false ) + { + return; + } + + user = static_cast(pool->get(id,true)); + + if ( user == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),id)); + return; + } + + if ( user_action(user,paramList,error_str) < 0 ) + { + failure_response(INTERNAL, request_error(error_str,"")); + return; + } + + success_response(id); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int UserChangePassword::user_action(User * user, + xmlrpc_c::paramList const& paramList, + string& error_str) +{ + + string new_pass = xmlrpc_c::value_string(paramList.getString(2)); + + user->set_password(new_pass); + + pool->update(user); + + user->unlock(); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int UserAddGroup::user_action(User * user, + xmlrpc_c::paramList const& paramList, + string& error_str) +{ + + int user_id = xmlrpc_c::value_int(paramList.getInt(1)); + int group_id = xmlrpc_c::value_int(paramList.getInt(2)); + int rc; + + rc = user->add_group(group_id); + + if ( rc != 0 ) + { + user->unlock(); + + error_str = "User is already in this group"; + return rc; + } + + pool->update(user); + + user->unlock(); + + Nebula& nd = Nebula::instance(); + GroupPool * gpool = nd.get_gpool(); + Group * group = gpool->get(group_id, true); + + if( group == 0 ) + { + User * user = static_cast(pool->get(user_id,true)); + + if ( user != 0 ) + { + user->del_group(group_id); + + pool->update(user); + + user->unlock(); + } + + error_str = "Group does not exist"; + return -1; + } + + group->add_user(user_id); + + gpool->update(group); + + group->unlock(); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int UserDelGroup::user_action(User * user, + xmlrpc_c::paramList const& paramList, + string& error_str) +{ + + int user_id = xmlrpc_c::value_int(paramList.getInt(1)); + int group_id = xmlrpc_c::value_int(paramList.getInt(2)); + int rc; + + rc = user->del_group(group_id); + + if ( rc != 0 ) + { + user->unlock(); + + if ( rc == -1 ) + { + error_str = "User is not part of this group"; + } + else if ( rc == -2 ) + { + error_str = "Can not remove main group from user"; + } + else + { + error_str = "Can not remove group from user"; + } + return rc; + } + + pool->update(user); + + user->unlock(); + + Nebula& nd = Nebula::instance(); + GroupPool * gpool = nd.get_gpool(); + Group * group = gpool->get(group_id, true); + + if( group == 0 ) + { + //Group does not exists, should never occur + error_str = "Can not remove user from group"; + return -1; + } + + group->del_user(user_id); + + gpool->update(group); + + group->unlock(); + + return 0; +} + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + diff --git a/src/rm/RequestManagerUserAllocate.cc b/src/rm/RequestManagerUserAllocate.cc deleted file mode 100644 index dd2a535d94..0000000000 --- a/src/rm/RequestManagerUserAllocate.cc +++ /dev/null @@ -1,140 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::UserAllocate::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - string username; - string password; - string error_str; - - int uid; - - int rc; - ostringstream oss; - - User * user; - - const string method_name = "UserAllocate"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"UserAllocate method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - - username = xmlrpc_c::value_string(paramList.getString(1)); - password = xmlrpc_c::value_string(paramList.getString(2)); - - rc = UserAllocate::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::USER, - -1, - AuthRequest::CREATE, - 0, - false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Let's make sure that the user doesn't exist in the database - user = UserAllocate::upool->get(username,false); - - if (user != 0 ) - { - goto error_duplicate; - } - - // Now let's add the user - rc = UserAllocate::upool->allocate(&uid,username,password,true,error_str); - - if ( rc == -1 ) - { - goto error_allocate; - } - - // All nice, return the new uid to client - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - arrayData.push_back(xmlrpc_c::value_int(uid)); - - // 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_authorize: - oss.str(authorization_error(method_name, "CREATE", "USER", rc, -1)); - goto error_common; - -error_duplicate: - oss << action_error(method_name, "CREATE", "USER", -2, -1) - << ". Reason: Existing user, cannot duplicate."; - goto error_common; - -error_allocate: - oss << action_error(method_name, "CREATE", "USER", -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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerUserChangePassword.cc b/src/rm/RequestManagerUserChangePassword.cc deleted file mode 100644 index 663d5cf234..0000000000 --- a/src/rm/RequestManagerUserChangePassword.cc +++ /dev/null @@ -1,120 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::UserChangePassword::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int uid; - int rc; - string new_pass; - User * user; - ostringstream oss; - - const string method_name = "UserChangePassword"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"UserChangePassword method invoked"); - - // Get the parameters & user - session = xmlrpc_c::value_string(paramList.getString(0)); - uid = xmlrpc_c::value_int(paramList.getInt(1)); - new_pass = xmlrpc_c::value_string(paramList.getString(2)); - - //Authenticate the user - rc = UserChangePassword::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::USER,uid,AuthRequest::MANAGE,0,false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - user = UserChangePassword::upool->get(uid,true); - - if ( user == 0 ) - { - goto error_user_get; - } - - user->set_password(new_pass); - - UserChangePassword::upool->update(user); - - user->unlock(); - - //Result - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayresult = new xmlrpc_c::value_array(arrayData); - - *retval = *arrayresult; - - delete arrayresult; - - return; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "USER", rc, uid)); - goto error_common; - -error_user_get: - oss.str(get_error(method_name, "USER", uid)); - goto error_common; - -error_common: - NebulaLog::log("ReM",Log::ERROR,oss); - - arrayData.push_back(xmlrpc_c::value_boolean(false)); - arrayData.push_back(xmlrpc_c::value_string(oss.str())); - - xmlrpc_c::value_array arrayresult_error(arrayData); - - *retval = arrayresult_error; - - return; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerUserDelete.cc b/src/rm/RequestManagerUserDelete.cc deleted file mode 100644 index 4c2eb55843..0000000000 --- a/src/rm/RequestManagerUserDelete.cc +++ /dev/null @@ -1,142 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::UserDelete::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int uid; - User * user; - - int rc; - ostringstream oss; - - const string method_name = "UserDelete"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"UserDelete method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - uid = xmlrpc_c::value_int(paramList.getInt(1)); - - // oneadmin cannot be deleted - if ( uid == 0 ) - { - goto error_oneadmin_deletion; - } - - rc = UserDelete::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::USER, - uid, - AuthRequest::DELETE, - 0, - false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Now let's get the user - user = UserDelete::upool->get(uid,true); - - if ( user == 0) - { - goto error_get_user; - } - - rc = UserDelete::upool->drop(user); - - user->unlock(); - - if ( rc != 0 ) - { - goto error_delete; - } - - // All nice, return the new uid to client - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - - // 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_oneadmin_deletion: - oss << action_error(method_name, "DELETE", "USER", uid, -1) - << ". Reason: Oneadmin cannot be deleted."; - goto error_common; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "DELETE", "USER", rc, uid)); - goto error_common; - -error_get_user: - oss.str(get_error(method_name, "USER", uid)); - goto error_common; - -error_delete: - oss.str(action_error(method_name, "DELETE", "USER", uid, rc)); - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerUserInfo.cc b/src/rm/RequestManagerUserInfo.cc deleted file mode 100644 index 1ae53c5cc8..0000000000 --- a/src/rm/RequestManagerUserInfo.cc +++ /dev/null @@ -1,122 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::UserInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - int the_uid, uid; - - User * user; - ostringstream oss; - - const string method_name = "UserInfo"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"UserInfo method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - the_uid = xmlrpc_c::value_int(paramList.getInt(1)); - - // Only oneadmin can retrieve user information - uid = UserInfo::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::USER, - the_uid, - AuthRequest::INFO, - 0, - false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - // Now let's get the user - user = UserInfo::upool->get(the_uid,true); - - if ( user == 0 ) - { - goto error_get_user; - } - - oss << *user; - - user->unlock(); - - // All nice, return the new uid to 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_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "INFO", "USER", uid, -1)); - goto error_common; - -error_get_user: - oss.str(get_error(method_name, "USER", the_uid)); - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerUserPoolInfo.cc b/src/rm/RequestManagerUserPoolInfo.cc deleted file mode 100644 index 359abce280..0000000000 --- a/src/rm/RequestManagerUserPoolInfo.cc +++ /dev/null @@ -1,116 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::UserPoolInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int rc; - int uid; - ostringstream oss; - - const string method_name = "UserPoolInfo"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"UserPoolInfo method invoked"); - - // Get the parameters - session = xmlrpc_c::value_string(paramList.getString(0)); - - // Only oneadmin can list the whole user pool - uid = UserPoolInfo::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - //Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::USER, - -1, - AuthRequest::INFO, - 0, - false); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Now let's get the info - rc = UserPoolInfo::upool->dump(oss,""); - - if ( rc != 0 ) - { - goto error_dumping; - } - - // All nice, return the new uid to 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_authorize: - oss.str(authorization_error(method_name, "INFO", "USER", uid, -1)); - goto error_common; - -error_dumping: - oss.str(get_error(method_name, "USER", -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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerVMTemplate.cc b/src/rm/RequestManagerVMTemplate.cc new file mode 100644 index 0000000000..b93ca5f202 --- /dev/null +++ b/src/rm/RequestManagerVMTemplate.cc @@ -0,0 +1,84 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "RequestManagerVMTemplate.h" +#include "Nebula.h" + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void VMTemplateInstantiate::request_execute(xmlrpc_c::paramList const& paramList) +{ + int id = xmlrpc_c::value_int(paramList.getInt(1)); + string name = xmlrpc_c::value_string(paramList.getString(2)); + + int rc, ouid, vid; + + Nebula& nd = Nebula::instance(); + VirtualMachinePool* vmpool = nd.get_vmpool(); + VMTemplatePool * tpool = static_cast(pool); + + VirtualMachineTemplate * tmpl; + VMTemplate * rtmpl; + + string error_str; + + rtmpl = tpool->get(id,true); + + if ( rtmpl == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),id)); + return; + } + + tmpl = rtmpl->clone_template(); + ouid = rtmpl->get_uid(); + + rtmpl->unlock(); + + tmpl->erase("NAME"); + tmpl->set(new SingleAttribute("NAME",name)); + + if ( uid != 0 ) + { + AuthRequest ar(uid); + + ar.add_auth(auth_object, id, auth_op, ouid, false); + + VirtualMachine::set_auth_request(uid, ar, tmpl); + + if (UserPool::authorize(ar) == -1) + { + failure_response(AUTHORIZATION, authorization_error(ar.message)); + delete tmpl; + return; + } + } + + rc = vmpool->allocate(uid, gid, tmpl, &vid, error_str, false); + + if ( rc < 0 ) + { + failure_response(INTERNAL, allocate_error(AuthRequest::VM,error_str)); + return; + } + + success_response(vid); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + diff --git a/src/rm/RequestManagerVirtualMachine.cc b/src/rm/RequestManagerVirtualMachine.cc new file mode 100644 index 0000000000..10142230c0 --- /dev/null +++ b/src/rm/RequestManagerVirtualMachine.cc @@ -0,0 +1,455 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "RequestManagerVirtualMachine.h" +#include "Nebula.h" + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +bool RequestManagerVirtualMachine::vm_authorization(int oid, int hid, ImageTemplate *tmpl) +{ + PoolObjectSQL * object; + + int ouid; + + if ( uid == 0 ) + { + return true; + } + + object = pool->get(oid,true); + + if ( object == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),oid)); + return false; + } + + ouid = object->get_uid(); + + object->unlock(); + + AuthRequest ar(uid); + + ar.add_auth(auth_object, oid, auth_op, ouid, false); + + if (hid != -1) + { + ar.add_auth(AuthRequest::HOST,hid,AuthRequest::USE,0,false); + } + else if (tmpl != 0) + { + string t64; + + ar.add_auth(AuthRequest::IMAGE, + tmpl->to_xml(t64), + AuthRequest::CREATE, + uid, + false); + } + + if (UserPool::authorize(ar) == -1) + { + failure_response(AUTHORIZATION, authorization_error(ar.message)); + return false; + } + + return true; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int RequestManagerVirtualMachine::get_host_information(int hid, + string& name, + string& vmm, + string& tm) +{ + Nebula& nd = Nebula::instance(); + HostPool * hpool = nd.get_hpool(); + + Host * host; + + host = hpool->get(hid,true); + + if ( host == 0 ) + { + failure_response(NO_EXISTS, + get_error(object_name(AuthRequest::HOST),hid)); + return -1; + } + + name = host->get_name(); + vmm = host->get_vmm_mad(); + tm = host->get_tm_mad(); + + host->unlock(); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +VirtualMachine * RequestManagerVirtualMachine::get_vm(int id) +{ + VirtualMachine * vm; + + vm = static_cast(pool->get(id,true)); + + if ( vm == 0 ) + { + failure_response(NO_EXISTS,get_error(object_name(auth_object),id)); + return 0; + } + + return vm; +} +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int RequestManagerVirtualMachine::add_history(VirtualMachine * vm, + int hid, + const string& hostname, + const string& vmm_mad, + const string& tm_mad) +{ + Nebula& nd = Nebula::instance(); + string vmdir; + + int rc; + + VirtualMachinePool * vmpool = static_cast(pool); + + nd.get_configuration_attribute("VM_DIR",vmdir); + + vm->add_history(hid,hostname,vmdir,vmm_mad,tm_mad); + + rc = vmpool->update_history(vm); + + if ( rc != 0 ) + { + failure_response(INTERNAL, + request_error("Can not update virtual machine history","")); + return -1; + } + + vmpool->update(vm); + + return 0; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ +void VirtualMachineAction::request_execute(xmlrpc_c::paramList const& paramList) +{ + string action = xmlrpc_c::value_string(paramList.getString(1)); + int id = xmlrpc_c::value_int(paramList.getInt(2)); + + int rc; + + Nebula& nd = Nebula::instance(); + DispatchManager * dm = nd.get_dm(); + + if ( vm_authorization(id,-1,0) == false ) + { + return; + } + + if (action == "shutdown") + { + rc = dm->shutdown(id); + } + else if (action == "hold") + { + rc = dm->hold(id); + } + else if (action == "release") + { + rc = dm->release(id); + } + else if (action == "stop") + { + rc = dm->stop(id); + } + else if (action == "cancel") + { + rc = dm->cancel(id); + } + else if (action == "suspend") + { + rc = dm->suspend(id); + } + else if (action == "resume") + { + rc = dm->resume(id); + } + else if (action == "restart") + { + rc = dm->restart(id); + } + else if (action == "finalize") + { + rc = dm->finalize(id); + } + else if (action == "resubmit") + { + rc = dm->resubmit(id); + } + + switch (rc) + { + case 0: + success_response(id); + break; + case -1: + failure_response(NO_EXISTS,get_error(object_name(auth_object),id)); + break; + case -2: + failure_response(ACTION, + request_error("Worng state to perform action","")); + break; + case -3: + failure_response(ACTION, + request_error("Virtual machine action not supported","")); + break; + default: + failure_response(INTERNAL, + request_error("Internal error","Action result not defined")); + } + + return; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void VirtualMachineDeploy::request_execute(xmlrpc_c::paramList const& paramList) +{ + Nebula& nd = Nebula::instance(); + DispatchManager * dm = nd.get_dm(); + + VirtualMachine * vm; + + string hostname; + string vmm_mad; + string tm_mad; + + int id = xmlrpc_c::value_int(paramList.getInt(1)); + int hid = xmlrpc_c::value_int(paramList.getInt(2)); + + if ( vm_authorization(id,hid,0) == false ) + { + return; + } + + if (get_host_information(hid,hostname,vmm_mad,tm_mad) != 0) + { + return; + } + + if ( (vm = get_vm(id)) == 0 ) + { + return; + } + + if ( vm->get_state() != VirtualMachine::PENDING ) + { + failure_response(ACTION, + request_error("Worng state to perform action","")); + + vm->unlock(); + return; + } + + if ( add_history(vm,hid,hostname,vmm_mad,tm_mad) != 0) + { + vm->unlock(); + return; + } + + dm->deploy(vm); + + vm->unlock(); + + success_response(id); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void VirtualMachineMigrate::request_execute(xmlrpc_c::paramList const& paramList) +{ + Nebula& nd = Nebula::instance(); + DispatchManager * dm = nd.get_dm(); + + VirtualMachine * vm; + + string hostname; + string vmm_mad; + string tm_mad; + + int id = xmlrpc_c::value_int(paramList.getInt(1)); + int hid = xmlrpc_c::value_int(paramList.getInt(2)); + bool live = xmlrpc_c::value_boolean(paramList.getBoolean(3)); + + if ( vm_authorization(id,hid,0) == false ) + { + return; + } + + if (get_host_information(hid,hostname,vmm_mad,tm_mad) != 0) + { + return; + } + + if ( (vm = get_vm(id)) == 0 ) + { + return; + } + + if((vm->get_state() != VirtualMachine::ACTIVE) || + (vm->get_lcm_state() != VirtualMachine::RUNNING) || + (vm->hasPreviousHistory() && vm->get_previous_reason() == History::NONE)) + { + failure_response(ACTION, + request_error("Worng state to perform action","")); + + vm->unlock(); + return; + } + + if ( add_history(vm,hid,hostname,vmm_mad,tm_mad) != 0) + { + vm->unlock(); + return; + } + + if ( live == true ) + { + dm->live_migrate(vm); + } + else + { + dm->migrate(vm); + } + + vm->unlock(); + + success_response(id); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void VirtualMachineSaveDisk::request_execute(xmlrpc_c::paramList const& paramList) +{ + Nebula& nd = Nebula::instance(); + ImagePool * ipool = nd.get_ipool(); + + int id = xmlrpc_c::value_int(paramList.getInt(1)); + int disk_id = xmlrpc_c::value_int(paramList.getInt(2)); + string img_name = xmlrpc_c::value_string(paramList.getString(3)); + + VirtualMachine * vm; + string vm_owner; + + int iid; + ImageTemplate * itemplate; + + int rc; + ostringstream oss; + string error_str; + char * error_char; + + // ------------------ Template for the new image ------------------ + + oss << "NAME= " << img_name << endl; + oss << "PUBLIC = NO " << endl; + oss << "SOURCE = - " << endl; + + itemplate = new ImageTemplate; + + itemplate->parse(oss.str(), &error_char); + + // ------------------ Authorize the operation ------------------ + + if ( vm_authorization(id,-1,itemplate) == false ) + { + return; + } + + // ------------------ Create the image ------------------ + + rc = ipool->allocate(uid, gid, itemplate, &iid,error_str); + + if ( rc < 0 ) + { + failure_response(INTERNAL, + allocate_error(AuthRequest::IMAGE,error_str)); + return; + } + + // ------------------ Store image id to save the disk ------------------ + + if ( (vm = get_vm(id)) == 0 ) + { + Image * img; + + if ( (img = ipool->get(iid,true)) != 0 ) + { + string tmp_error; + + ipool->drop(img, tmp_error); + img->unlock(); + } + + return; + } + + rc = vm->save_disk(disk_id, iid, error_str); + + if ( rc == 0 ) + { + pool->update(vm); + } + + vm->unlock(); + + if ( rc == -1 ) + { + Image * img; + + if ( (img = ipool->get(iid,true)) != 0 ) + { + string tmp_error; + + ipool->drop(img, tmp_error); + img->unlock(); + } + + failure_response(INTERNAL, + request_error("Can not save_as disk",error_str)); + return; + } + + // Return the new allocated Image ID + success_response(iid); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerVirtualNetwork.cc b/src/rm/RequestManagerVirtualNetwork.cc new file mode 100644 index 0000000000..f716ba6554 --- /dev/null +++ b/src/rm/RequestManagerVirtualNetwork.cc @@ -0,0 +1,94 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "RequestManagerVirtualNetwork.h" +#include "VirtualNetworkTemplate.h" + +using namespace std; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +string RequestManagerVirtualNetwork::leases_error (char *error) +{ + ostringstream oss; + + oss << "Parse error."; + + if ( error != 0 ) + { + oss << " " << error; + free(error); + } + + return request_error("Error modifiying network leases",oss.str()); +} + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void RequestManagerVirtualNetwork:: + request_execute(xmlrpc_c::paramList const& paramList) +{ + int id = xmlrpc_c::value_int (paramList.getInt(1)); + string str_tmpl = xmlrpc_c::value_string (paramList.getString(2)); + + VirtualNetworkTemplate tmpl; + VirtualNetwork * vn; + + char * error_msg = 0; + string error_str; + int rc; + + if ( basic_authorization(id) == false ) + { + return; + } + + rc = tmpl.parse(str_tmpl, &error_msg); + + if ( rc != 0 ) + { + failure_response(INTERNAL, leases_error(error_msg)); + return; + } + + vn = static_cast(pool->get(id,true)); + + if ( vn == 0 ) + { + failure_response(NO_EXISTS, get_error(object_name(auth_object),id)); + return; + } + + rc = leases_action(vn,&tmpl,error_str); + + if ( rc < 0 ) + { + failure_response(INTERNAL, + request_error("Error modifiying network leases",error_str)); + + vn->unlock(); + return; + } + + pool->update(vn); + + vn->unlock(); + + success_response(id); +} + diff --git a/src/rm/RequestManagerVirtualNetworkAddLeases.cc b/src/rm/RequestManagerVirtualNetworkAddLeases.cc deleted file mode 100644 index 5214d38636..0000000000 --- a/src/rm/RequestManagerVirtualNetworkAddLeases.cc +++ /dev/null @@ -1,175 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 "VirtualNetworkTemplate.h" -#include "AuthManager.h" - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -void RequestManager::VirtualNetworkAddLeases::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int nid; - int uid; - int rc; - - string str_template; - string error_add; - char* error_msg = 0; - - VirtualNetworkTemplate leases_template; - VirtualNetwork * vn; - - int network_owner; - bool is_public; - - ostringstream oss; - const string method_name = "VirtualNetworkAddLeases"; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualNetworkAddLeases invoked"); - - session = xmlrpc_c::value_string (paramList.getString(0)); - nid = xmlrpc_c::value_int (paramList.getInt(1)); - str_template = xmlrpc_c::value_string (paramList.getString(2)); - - // First, we need to authenticate the user - uid = VirtualNetworkAddLeases::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - // Check template syntax - - rc = leases_template.parse(str_template,&error_msg); - - if ( rc != 0 ) - { - goto error_parse; - } - - // Get virtual network from the VirtualNetworkPool - vn = VirtualNetworkAddLeases::vnpool->get(nid,true); - - if ( vn == 0 ) - { - goto error_vn_get; - } - - network_owner = vn->get_uid(); - is_public = vn->isPublic(); - - vn->unlock(); - - // Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::NET, - nid, - AuthRequest::MANAGE, - network_owner, - is_public); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Get virtual network from the VirtualNetworkPool - vn = VirtualNetworkAddLeases::vnpool->get(nid,true); - - if ( vn == 0 ) - { - goto error_vn_get; - } - - rc = vn->add_leases(&leases_template, error_add); - - if ( rc < 0 ) - { - goto error_add; - } - - vn->unlock(); - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(nid)); - - // 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_parse: - oss << action_error(method_name, "PARSE", "LEASES TEMPLATE",-2,rc); - if (error_msg != 0) - { - oss << " Reason: " << error_msg; - free(error_msg); - } - goto error_common; - -error_vn_get: - oss.str(get_error(method_name, "NET", nid)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "NET", uid, nid)); - goto error_common; - -error_add: - oss << action_error(method_name, "ADD LEASE", "NET", nid, rc); - oss << " Reason: " << error_add; - vn->unlock(); - -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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerVirtualNetworkAllocate.cc b/src/rm/RequestManagerVirtualNetworkAllocate.cc deleted file mode 100644 index 6d66296c8c..0000000000 --- a/src/rm/RequestManagerVirtualNetworkAllocate.cc +++ /dev/null @@ -1,184 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 "VirtualNetworkTemplate.h" - -#include "AuthManager.h" - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -void RequestManager::VirtualNetworkAllocate::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - string name; - string user_name; - string str_template; - string error_str; - - VirtualNetworkTemplate * vn_template; - User * user; - - int nid; - int uid; - int rc; - char * error_msg = 0; - - ostringstream oss; - - const string method_name = "VirtualNetworkAllocate"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualNetworkAllocate method invoked"); - - // Get the parameters & host - session = xmlrpc_c::value_string(paramList.getString(0)); - str_template = xmlrpc_c::value_string(paramList.getString(1)); - - //-------------------------------------------------------------------------- - // Authorize this request - //-------------------------------------------------------------------------- - uid = VirtualNetworkAllocate::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - //-------------------------------------------------------------------------- - // Authorize this request - //-------------------------------------------------------------------------- - vn_template = new VirtualNetworkTemplate; - - rc = vn_template->parse(str_template,&error_msg); - - if ( rc != 0 ) - { - goto error_parse; - } - - if ( uid != 0 ) - { - AuthRequest ar(uid); - string t64; - string pub; - string pub_name = "PUBLIC"; - - vn_template->get(pub_name, pub); - transform (pub.begin(), pub.end(), pub.begin(),(int(*)(int))toupper); - - ar.add_auth(AuthRequest::NET, - vn_template->to_xml(t64), - AuthRequest::CREATE, - uid, - (pub == "YES")); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - //-------------------------------------------------------------------------- - // Get the User Name - //-------------------------------------------------------------------------- - - user = VirtualNetworkAllocate::upool->get(uid,true); - - if ( user == 0 ) - { - goto error_user_get; - } - - user_name = user->get_name(); - - user->unlock(); - - //-------------------------------------------------------------------------- - // Allocate the Virtual Network - //-------------------------------------------------------------------------- - rc = vnpool->allocate(uid,user_name,vn_template,&nid,error_str); - - if ( rc < 0 ) - { - goto error_vn_allocate; - } - - //Result - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - arrayData.push_back(xmlrpc_c::value_int(nid)); - arrayresult = new xmlrpc_c::value_array(arrayData); - - *retval = *arrayresult; - - delete arrayresult; - - return; - - -error_user_get: - oss.str(get_error(method_name, "USER", uid)); - - delete vn_template; - goto error_common; - -error_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "CREATE", "VNET", uid, -1)); - delete vn_template; - goto error_common; - -error_parse: - oss << action_error(method_name, "PARSE", "VNET TEMPLATE",-2,rc); - if (error_msg != 0) - { - oss << ". Reason: " << error_msg; - free(error_msg); - } - - delete vn_template; - goto error_common; - -error_vn_allocate: - oss << action_error(method_name, "CREATE", "NET", -2, 0); - oss << " " << error_str; - goto error_common; - -error_common: - NebulaLog::log("ReM",Log::ERROR,oss); - - arrayData.push_back(xmlrpc_c::value_boolean(false)); - arrayData.push_back(xmlrpc_c::value_string(oss.str())); - - xmlrpc_c::value_array arrayresult_error(arrayData); - - *retval = arrayresult_error; - - return; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerVirtualNetworkDelete.cc b/src/rm/RequestManagerVirtualNetworkDelete.cc deleted file mode 100644 index 7b3bbcc2bb..0000000000 --- a/src/rm/RequestManagerVirtualNetworkDelete.cc +++ /dev/null @@ -1,151 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::VirtualNetworkDelete::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - string name; - int nid; - - VirtualNetwork * vn; - - int network_owner; - bool is_public; - - int rc; - ostringstream oss; - - const string method_name = "VirtualNetworkDelete"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualNetworkDelete method invoked"); - - // Get the parameters & host - session = xmlrpc_c::value_string(paramList.getString(0)); - nid = xmlrpc_c::value_int (paramList.getInt (1)); - - // First, we need to authenticate the user - rc = VirtualNetworkDelete::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - // Retrieve VN from the pool - vn = vnpool->get(nid,true); - - if ( vn == 0 ) - { - goto error_vn_get; - } - - network_owner = vn->get_uid(); - is_public = vn->isPublic(); - - vn->unlock(); - - - //Authorize the operation - if ( rc != 0 ) // rc == 0 means oneadmin - { - AuthRequest ar(rc); - - ar.add_auth(AuthRequest::NET, - nid, - AuthRequest::DELETE, - network_owner, - is_public); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Retrieve VN from the pool - vn = vnpool->get(nid,true); - - if ( vn == 0 ) - { - goto error_vn_get; - } - - rc = vnpool->drop(vn); - - vn->unlock(); - - if ( rc != 0 ) - { - goto error_vn_drop; - } - - // All nice, return the host info to the client - arrayData.push_back(xmlrpc_c::value_boolean(true)); // SUCCESS - 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_authorize: - oss.str(authorization_error(method_name, "DELETE", "NET", rc, nid)); - goto error_common; - -error_vn_get: - oss.str(get_error(method_name, "NET", nid)); - goto error_common; - -error_vn_drop: - oss.str(action_error(method_name, "DELETE", "NET",nid,rc)); - goto error_common; - -error_common: - NebulaLog::log ("ReM",Log::ERROR,oss); - - arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE - arrayData.push_back(xmlrpc_c::value_string(oss.str())); - - xmlrpc_c::value_array arrayresult_error(arrayData); - - *retval = arrayresult_error; - - return; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerVirtualNetworkInfo.cc b/src/rm/RequestManagerVirtualNetworkInfo.cc deleted file mode 100644 index 1d1f8e039d..0000000000 --- a/src/rm/RequestManagerVirtualNetworkInfo.cc +++ /dev/null @@ -1,104 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::VirtualNetworkInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int nid; - int rc; - string info; - - VirtualNetwork * vn; - - ostringstream oss; - - const string method_name = "VirtualNetworkInfo"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualNetworkInfo method invoked"); - - // Get the parameters & host - session = xmlrpc_c::value_string(paramList.getString(0)); - nid = xmlrpc_c::value_int (paramList.getInt (1)); - - // Check if it is a valid user - rc = VirtualNetworkInfo::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - vn = vnpool->get(nid,true); - - if ( vn == 0 ) - { - goto error_vn_get; - } - - oss << *vn; - - vn->unlock(); - - // All nice, return the Virtual Network 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_authenticate: - oss.str(authenticate_error(method_name)); - goto error_common; - -error_vn_get: - oss.str(get_error(method_name, "NET", nid)); - 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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerVirtualNetworkPoolInfo.cc b/src/rm/RequestManagerVirtualNetworkPoolInfo.cc deleted file mode 100644 index cb8500a82f..0000000000 --- a/src/rm/RequestManagerVirtualNetworkPoolInfo.cc +++ /dev/null @@ -1,127 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::VirtualNetworkPoolInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - string username; - string password; - - ostringstream oss; - ostringstream where_string; - - int rc; - int filter_flag; - - const string method_name = "VirtualNetworkPoolInfo"; - - /* -- RPC specific vars -- */ - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - NebulaLog::log("ReM",Log::DEBUG,"VirtualNetworkPoolInfo 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 = VirtualNetworkPoolInfo::upool->authenticate(session); - - if ( rc == -1 ) - { - goto error_authenticate; - } - - /** Filter flag meaning table - * <=-2 :: ALL Networks - * -1 :: User's Networks plus Public ones - * >=0 :: UID User's Networks - **/ - if ( filter_flag < -2 ) - { - goto error_filter_flag; - } - - switch(filter_flag) - { - case -2: - // TODO define authentication bug #278 - break; - case -1: - where_string << "UID=" << rc << " OR PUBLIC=1"; - break; - default: - where_string << "UID=" << filter_flag; - } - - rc = VirtualNetworkPoolInfo::vnpool->dump(oss,where_string.str()); - - if ( rc != 0 ) - { - goto error_dump; - } - - //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())); - - 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, "NETWORK", -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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerVirtualNetworkPublish.cc b/src/rm/RequestManagerVirtualNetworkPublish.cc deleted file mode 100644 index d7d6a24f38..0000000000 --- a/src/rm/RequestManagerVirtualNetworkPublish.cc +++ /dev/null @@ -1,146 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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::VirtualNetworkPublish::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int nid; - bool publish_flag; - int uid; - - VirtualNetwork * vn; - - int network_owner; - bool is_public; - - ostringstream oss; - - const string method_name = "VirtualNetworkPublish"; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - - NebulaLog::log("ReM",Log::DEBUG,"VirtualNetworkPublish invoked"); - - session = xmlrpc_c::value_string (paramList.getString(0)); - nid = xmlrpc_c::value_int (paramList.getInt(1)); - publish_flag = xmlrpc_c::value_boolean(paramList.getBoolean(2)); - - // First, we need to authenticate the user - uid = VirtualNetworkPublish::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - // Get virtual network from the VirtualNetworkPool - vn = VirtualNetworkPublish::vnpool->get(nid,true); - - if ( vn == 0 ) - { - goto error_vn_get; - } - - network_owner = vn->get_uid(); - is_public = vn->isPublic(); - - vn->unlock(); - - //Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::NET, - nid, - AuthRequest::MANAGE, - network_owner, - is_public); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Get virtual network from the VirtualNetworkPool - vn = VirtualNetworkPublish::vnpool->get(nid,true); - - if ( vn == 0 ) - { - goto error_vn_get; - } - - vn->publish(publish_flag); - - VirtualNetworkPublish::vnpool->update(vn); - - vn->unlock(); - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(nid)); - - // 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_vn_get: - oss.str(get_error(method_name, "NET", nid)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "NET", uid, nid)); - vn->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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/RequestManagerVirtualNetworkRemoveLeases.cc b/src/rm/RequestManagerVirtualNetworkRemoveLeases.cc deleted file mode 100644 index dd36dfe9ff..0000000000 --- a/src/rm/RequestManagerVirtualNetworkRemoveLeases.cc +++ /dev/null @@ -1,177 +0,0 @@ -/* -------------------------------------------------------------------------- */ -/* 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 "VirtualNetworkTemplate.h" - -#include "NebulaLog.h" -#include "Nebula.h" - -#include "AuthManager.h" - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -void RequestManager::VirtualNetworkRemoveLeases::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - - int nid; - int uid; - int rc; - - string str_template; - string error_add; - char * error_msg = 0; - - VirtualNetworkTemplate leases_template; - VirtualNetwork * vn; - - int network_owner; - bool is_public; - - ostringstream oss; - - const string method_name = "VirtualNetworkRemoveLeases"; - - vector arrayData; - xmlrpc_c::value_array * arrayresult; - - - NebulaLog::log("ReM",Log::DEBUG,"VirtualNetworkRemoveLeases invoked"); - - session = xmlrpc_c::value_string (paramList.getString(0)); - nid = xmlrpc_c::value_int (paramList.getInt(1)); - str_template = xmlrpc_c::value_string (paramList.getString(2)); - - // First, we need to authenticate the user - uid = VirtualNetworkRemoveLeases::upool->authenticate(session); - - if ( uid == -1 ) - { - goto error_authenticate; - } - - // Check template syntax - rc = leases_template.parse(str_template,&error_msg); - - if ( rc != 0 ) - { - goto error_parse; - } - - // Get virtual network from the VirtualNetworkPool - vn = VirtualNetworkRemoveLeases::vnpool->get(nid,true); - - if ( vn == 0 ) - { - goto error_vn_get; - } - - network_owner = vn->get_uid(); - is_public = vn->isPublic(); - - vn->unlock(); - - // Authorize the operation - if ( uid != 0 ) // uid == 0 means oneadmin - { - AuthRequest ar(uid); - - ar.add_auth(AuthRequest::NET, - nid, - AuthRequest::MANAGE, - network_owner, - is_public); - - if (UserPool::authorize(ar) == -1) - { - goto error_authorize; - } - } - - // Get virtual network from the VirtualNetworkPool - vn = VirtualNetworkRemoveLeases::vnpool->get(nid,true); - - if ( vn == 0 ) - { - goto error_vn_get; - } - - rc = vn->remove_leases(&leases_template, error_add); - - if ( rc < 0 ) - { - goto error_add; - } - - vn->unlock(); - - arrayData.push_back(xmlrpc_c::value_boolean(true)); - arrayData.push_back(xmlrpc_c::value_int(nid)); - - // 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_parse: - oss << action_error(method_name, "PARSE", "LEASES TEMPLATE",-2,rc); - if (error_msg != 0) - { - oss << " Reason: " << error_msg; - free(error_msg); - } - goto error_common; - -error_vn_get: - oss.str(get_error(method_name, "NET", nid)); - goto error_common; - -error_authorize: - oss.str(authorization_error(method_name, "MANAGE", "NET", uid, nid)); - goto error_common; - -error_add: - oss << action_error(method_name, "REMOVE LEASE", "NET", nid, rc); - oss << " Reason: " << error_add; - - vn->unlock(); - -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; -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ diff --git a/src/rm/SConstruct b/src/rm/SConstruct index 11c674e9ea..a025765a41 100644 --- a/src/rm/SConstruct +++ b/src/rm/SConstruct @@ -22,53 +22,52 @@ lib_name='nebula_rm' #Sources to generate the library source_files=[ + 'Request.cc', 'RequestManager.cc', - 'RequestManagerAction.cc', - 'RequestManagerAllocate.cc', - 'RequestManagerDeploy.cc', - 'RequestManagerMigrate.cc', - 'RequestManagerSaveDisk.cc', 'RequestManagerInfo.cc', 'RequestManagerPoolInfo.cc', - 'RequestManagerHostAllocate.cc', - 'RequestManagerHostDelete.cc', - 'RequestManagerHostInfo.cc', - 'RequestManagerHostPoolInfo.cc', - 'RequestManagerHostEnable.cc', - 'RequestManagerImageAllocate.cc', - 'RequestManagerImageDelete.cc', - 'RequestManagerImageInfo.cc', - 'RequestManagerImageUpdate.cc', - 'RequestManagerImageRemoveAttribute.cc', - 'RequestManagerImagePublish.cc', - 'RequestManagerImagePersistent.cc', - 'RequestManagerImageEnable.cc', - 'RequestManagerImagePoolInfo.cc', - 'RequestManagerClusterAdd.cc', - 'RequestManagerClusterAllocate.cc', - 'RequestManagerClusterDelete.cc', - 'RequestManagerClusterInfo.cc', - 'RequestManagerClusterPoolInfo.cc', - 'RequestManagerClusterRemove.cc', - 'RequestManagerVirtualNetworkAllocate.cc', - 'RequestManagerVirtualNetworkInfo.cc', - 'RequestManagerVirtualNetworkPoolInfo.cc', - 'RequestManagerVirtualNetworkPublish.cc', - 'RequestManagerVirtualNetworkDelete.cc', - 'RequestManagerVirtualNetworkAddLeases.cc', - 'RequestManagerVirtualNetworkRemoveLeases.cc', - 'RequestManagerUserAllocate.cc', - 'RequestManagerUserDelete.cc', - 'RequestManagerUserChangePassword.cc', - 'RequestManagerUserInfo.cc', - 'RequestManagerUserPoolInfo.cc', - 'RequestManagerTemplateAllocate.cc', - 'RequestManagerTemplateDelete.cc', - 'RequestManagerTemplateInfo.cc', - 'RequestManagerTemplateUpdate.cc', - 'RequestManagerTemplateRemoveAttribute.cc', - 'RequestManagerTemplatePublish.cc', - 'RequestManagerTemplatePoolInfo.cc', + 'RequestManagerPoolInfoFilter.cc', + 'RequestManagerDelete.cc', + 'RequestManagerPublish.cc', + 'RequestManagerAllocate.cc', + 'RequestManagerVirtualNetwork.cc', + 'RequestManagerVirtualMachine.cc', + 'RequestManagerVMTemplate.cc', + 'RequestManagerUpdateTemplate.cc', + 'RequestManagerUser.cc', + 'RequestManagerHost.cc', + 'RequestManagerImage.cc', + 'RequestManagerChown.cc', + +# 'RequestManagerAction.cc', +# 'RequestManagerAllocate.cc', +# 'RequestManagerDeploy.cc', +# 'RequestManagerMigrate.cc', +# 'RequestManagerSaveDisk.cc', +# 'RequestManagerHostAllocate.cc', +# 'RequestManagerHostEnable.cc', +# 'RequestManagerImageAllocate.cc', +# 'RequestManagerImageUpdate.cc', +# 'RequestManagerImageRemoveAttribute.cc', +# 'RequestManagerImagePublish.cc', +# 'RequestManagerImagePersistent.cc', +# 'RequestManagerImageEnable.cc', +# 'RequestManagerClusterAdd.cc', +# 'RequestManagerClusterAllocate.cc', +# 'RequestManagerClusterRemove.cc', +# 'RequestManagerGroupAllocate.cc', +# 'RequestManagerVirtualNetworkAllocate.cc', +# 'RequestManagerVirtualNetworkInfo.cc', +# 'RequestManagerVirtualNetworkPublish.cc', +# 'RequestManagerVirtualNetworkAddLeases.cc', +# 'RequestManagerVirtualNetworkRemoveLeases.cc', +# 'RequestManagerUserAllocate.cc', +# 'RequestManagerUserChangePassword.cc', +# 'RequestManagerTemplateAllocate.cc', +# 'RequestManagerTemplateUpdate.cc', +# 'RequestManagerTemplateRemoveAttribute.cc', +# 'RequestManagerTemplatePublish.cc', +# 'RequestManagerChown.cc', ] # Build library diff --git a/src/sunstone/bin/sunstone-server b/src/sunstone/bin/sunstone-server index e7b505ac42..6ecf6bb9c4 100755 --- a/src/sunstone/bin/sunstone-server +++ b/src/sunstone/bin/sunstone-server @@ -23,12 +23,18 @@ if [ -z "$ONE_LOCATION" ]; then SUNSTONE_LOCK_FILE=/var/lock/one/.sunstone.lock SUNSTONE_LOG=/var/log/one/sunstone.log SUNSTONE_CONF=/etc/one/sunstone-server.conf + ONEMONITOR_CMD=/usr/lib/one/sunstone/share/OneMonitor/runOneMonitor.sh + HOST_LOG_FOLDER=/var/log/one/OneMonitor/host + VM_LOG_FOLDER=/var/log/one/OneMonitor/vm else SUNSTONE_PID=$ONE_LOCATION/var/sunstone.pid SUNSTONE_SERVER=$ONE_LOCATION/lib/sunstone/config.ru SUNSTONE_LOCK_FILE=$ONE_LOCATION/var/.sunstone.lock SUNSTONE_LOG=$ONE_LOCATION/var/sunstone.log SUNSTONE_CONF=$ONE_LOCATION/etc/sunstone-server.conf + ONEMONITOR_CMD=$ONE_LOCATION/lib/sunstone/share/OneMonitor/runOneMonitor.sh + HOST_LOG_FOLDER=$ONE_LOCATION/var/OneMonitor/host + VM_LOG_FOLDER=$ONE_LOCATION/var/OneMonitor/vm fi setup() @@ -84,6 +90,24 @@ start() fi echo "sunstone-server listening on $HOST:$PORT" + + # Start the monitoring app + if [ ! -d $HOST_LOG_FOLDER ] + then + mkdir -p $HOST_LOG_FOLDER + [[ $? -ne 0 ]] && ( echo "Error creating host log directory"; exit 1 ) + fi + + if [ ! -d $VM_LOG_FOLDER ] + then + mkdir -p $VM_LOG_FOLDER + [[ $? -ne 0 ]] && ( echo "Error creating vm log directory"; exit 1 ) + fi + + $ONEMONITOR_CMD $MONITORING_INTERVAL $HOST_LOG_FOLDER $VM_LOG_FOLDER &>/dev/null & + + [[ $? -ne 0 ]] && ( echo "Error launching monitoring daemon"; exit 1 ) + } # @@ -102,6 +126,8 @@ stop() # Remove pid files rm -f $SUNSTONE_LOCK_FILE &> /dev/null + killall $ONEMONITOR_CMD + echo "sunstone-server stopped" } diff --git a/src/sunstone/models/SunstoneServer.rb b/src/sunstone/models/SunstoneServer.rb index dd306a69d2..9c1198fe21 100644 --- a/src/sunstone/models/SunstoneServer.rb +++ b/src/sunstone/models/SunstoneServer.rb @@ -17,6 +17,8 @@ require 'OpenNebulaJSON' include OpenNebulaJSON +require 'OneMonitorClient' + class SunstoneServer def initialize(username, password) # TBD one_client_user(name) from CloudServer @@ -223,7 +225,6 @@ class SunstoneServer # The VM host and its VNC port host = resource['HISTORY/HOSTNAME'] vnc_port = resource['TEMPLATE/GRAPHICS/PORT'] - # The noVNC proxy_port proxy_port = config[:vnc_proxy_base_port].to_i + vnc_port.to_i @@ -262,6 +263,37 @@ class SunstoneServer return [200, nil] end + ############################################################################ + # + ############################################################################ + + def get_log(params) + resource = params[:resource] + id = params[:id] + id = "global" unless id + columns = params['monitor_resources'].split(',') + history_length = params['history_length'] + + log_file_folder = case resource + when "vm","VM" + VM_LOG_FOLDER + when "host","HOST" + HOST_LOG_FOLDER + end + + monitor_client = OneMonitorClient.new(id,log_file_folder) + return monitor_client.get_data_for_id(id,columns,history_length).to_json + end + + ############################################################################ + # + ############################################################################ + + ############################################################################ + # + ############################################################################ + + private diff --git a/src/sunstone/public/css/application.css b/src/sunstone/public/css/application.css index f318adfb7e..6840aefa7c 100644 --- a/src/sunstone/public/css/application.css +++ b/src/sunstone/public/css/application.css @@ -55,17 +55,16 @@ table#dashboard_table tr { vertical-align: top; } -table#dashboard_table td{ +table#dashboard_table > tbody > tr > td{ width:50%; } div.panel { background-color: #ffffff; padding:0; - width:80%; margin: 10px; border: 1px #ddd solid; - min-height: 110px; + min-height: 50px; -webkit-border-radius: 3px; -moz-border-radius: 3px; -moz-box-shadow: 5px 5px 5px #888; @@ -77,6 +76,8 @@ div.panel h3 { border: 0; padding:5px 10px 5px 10px; margin: 0; + color: white; + font-weight: bold; background-color: #353735; -webkit-border-radius: 3px 3px 0 0; -moz-border-radius: 3px 3px 0 0; @@ -105,7 +106,7 @@ div.panel_info table.info_table tr { border: 0; border-bottom: 1px dotted #ccc; } -div.panel_info table.info_table td { +div.panel_info table.info_table > tbody > tr > td { border: 0; width: 100%!important; } @@ -114,11 +115,11 @@ div.panel_info table.info_table td.value_td { text-align: right; } -.key_td_green { +.green { color: green!important; } -.key_td_red { +.red { color: #B81515!important; } @@ -362,7 +363,7 @@ tr.even:hover{ vertical-align:top; } -.info_table th,h3 { +.info_table > thead th,h3 { border-bottom: 2px solid #353735; color: #353735; font-size: 14px; @@ -371,7 +372,7 @@ tr.even:hover{ } -.info_table td{ +.info_table > tbody > tr > td{ border-bottom: 1px solid #CCCCCC; color: #353735; padding-top: 6px; @@ -387,6 +388,12 @@ tr.even:hover{ font-weight:bold; } +.info_table td.graph_td{ + padding-top:0px!important; + padding-bottom:0px!important; + vertical-align:middle!important; +} + .info_table td.value_td{ text-align:left; } diff --git a/src/sunstone/public/js/opennebula.js b/src/sunstone/public/js/opennebula.js index d08c89e43a..88391d8756 100644 --- a/src/sunstone/public/js/opennebula.js +++ b/src/sunstone/public/js/opennebula.js @@ -471,6 +471,70 @@ var OpenNebula = { } } }); + }, + + "monitor" : function(params){ + var callback = params.success; + var callback_error = params.error; + var id = params.data.id; + var resource = OpenNebula.Host.resource; + var data = params.data; + + var method = "monitor"; + var action = OpenNebula.Helper.action(method); + var request = OpenNebula.Helper.request(resource,method, data); + + $.ajax({ + url: "host/"+id+"/monitor", + type: "GET", + data: data['monitor'], + dataType: "json", + success: function(response) + { + if (callback) + { + callback(request,response); + } + }, + error: function(response) + { + if (callback_error) + { + callback_error(request, OpenNebula.Error(response)); + } + } + }); + }, + "monitor_all" : function(params){ + var callback = params.success; + var callback_error = params.error; + var resource = OpenNebula.Host.resource; + var data = params.data; + + var method = "monitor"; + var action = OpenNebula.Helper.action(method); + var request = OpenNebula.Helper.request(resource,method, data); + + $.ajax({ + url: "host/monitor", + type: "GET", + data: data['monitor'], + dataType: "json", + success: function(response) + { + if (callback) + { + callback(request,response); + } + }, + error: function(response) + { + if (callback_error) + { + callback_error(request, OpenNebula.Error(response)); + } + } + }); } }, @@ -1303,8 +1367,72 @@ var OpenNebula = { } } }); + }, + + "monitor" : function(params){ + var callback = params.success; + var callback_error = params.error; + var id = params.data.id; + var resource = OpenNebula.VM.resource; + var data = params.data; + + var method = "monitor"; + var action = OpenNebula.Helper.action(method); + var request = OpenNebula.Helper.request(resource,method, data); + + $.ajax({ + url: "vm/"+id+"/monitor", + type: "GET", + data: data['monitor'], + dataType: "json", + success: function(response) + { + if (callback) + { + callback(request,response); + } + }, + error: function(response) + { + if (callback_error) + { + callback_error(request, OpenNebula.Error(response)); + } + } + }); + }, + "monitor_all" : function(params){ + var callback = params.success; + var callback_error = params.error; + var resource = OpenNebula.VM.resource; + var data = params.data; + + var method = "monitor"; + var action = OpenNebula.Helper.action(method); + var request = OpenNebula.Helper.request(resource,method, data); + + $.ajax({ + url: "vm/monitor", + type: "GET", + data: data['monitor'], + dataType: "json", + success: function(response) + { + if (callback) + { + callback(request,response); + } + }, + error: function(response) + { + if (callback_error) + { + callback_error(request, OpenNebula.Error(response)); + } + } + }); } - + }, "Cluster": { diff --git a/src/sunstone/public/js/plugins/dashboard-tab.js b/src/sunstone/public/js/plugins/dashboard-tab.js index b6bc6fb2ac..1550a5e092 100644 --- a/src/sunstone/public/js/plugins/dashboard-tab.js +++ b/src/sunstone/public/js/plugins/dashboard-tab.js @@ -14,44 +14,81 @@ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ +var HISTORY_LENGTH=40; +var GRAPH_AUTOREFRESH_INTERVAL=10000; //10 secs + +var graph1 = { + title : "graph1", + monitor_resources : "total,active,error", + history_length : HISTORY_LENGTH +}; + +var graph2 = { + title : "graph2", + monitor_resources : "cpu_usage,used_cpu,max_cpu", + history_length : HISTORY_LENGTH +}; + +var graph3 = { + title : "graph3", + monitor_resources : "mem_usage,used_mem,max_mem", + history_length : HISTORY_LENGTH +}; + +var graph4 = { + title : "graph4", + monitor_resources : "total,active,error", + history_length : HISTORY_LENGTH +}; + +var graph5 = { + title : "graph5", + monitor_resources : "net_tx,net_rx", + history_length : HISTORY_LENGTH +}; + var dashboard_tab_content = '\ +\ +\ +
\ +\ \ - \ \ @@ -59,95 +96,67 @@ var dashboard_tab_content = \ \ - \ \ \ \ - \ +
\ -
\ -

Hosts\ -
\ - +\ -
\ -

\ -
\ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
Total
Active
\ -
\ -
\ -
\
\ -

Clusters\ -
\ - +\ -
\ -

\ +

Summary of resources

\
\ - \ - \ - \ - \ - \ -
Total
\ +\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
Hosts (total/active)
Clusters
VM Templates (total/public)
VM Instances (total/running/failed)
Virtual Networks (total/public)
Images (total/public)
Users
\ +\
\
\
\
\ -

Virtual Machines\ -
\ - +\ -
\ -

\ -
\ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
Total
Running
Failed
\ -
\ -
\ -
\ -
\ -

Virtual Networks\ -
\ - +\ -
\ -

\ -
\ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
Total
Public
\ -
\ -
\ +

Quickstart

\ +
\ +
\ + \ + Host
\ + Cluster
\ + VM Template
\ + VM Instance
\ + Image
\ + User
\ +
\ + \ +
\ \
\
\ -

\ - Images\ -
\ - +\ -
\ -

\ -
\ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
Total
Public
\ -
\ +

Sunstone documentation

\ +
    \ +
  • Sunstone installation and setup
  • \ +
  • Sunstone plugin guide
  • \ +
  • Sunstone plugin reference
  • \ +
\
\
\ +
\ +
\ +\ + \ + \ \ -
\
\ -

Users\ -
\ - +\ -
\ -

\ +

Historical monitoring information

\
\ - \ - \ - \ - \ - \ -
Total
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
Total host count
'+spinner+'
Hosts CPU
'+spinner+'
Hosts memory
'+spinner+'
Total VM count
'+spinner+'
VM Network stats
'+spinner+'
\
\
\
'; - +
\ +\ +'; var dashboard_tab = { title: 'Dashboard', @@ -157,6 +166,74 @@ var dashboard_tab = { Sunstone.addMainTab('dashboard_tab',dashboard_tab); +function plot_global_graph(data,info){ + var id = info.title; + var labels_arr = info.monitor_resources.split(','); + var serie; + var series = []; + var width = ($(window).width()-129)*45/100; + + $('#'+id).html('
'); + + for (var i = 0; i< labels_arr.length; i++) { + serie = { + label: labels_arr[i], + data: data[i] + }; + series.push(serie); + }; + + var options = { + legend : { show : true, + noColumns: labels_arr.length, + container: $('#'+id+'_legend')}, + xaxis : { mode: "time", + timeformat: "%h:%M" + }, + yaxis : { labelWidth: 40 } + } + + switch (id){ + case "graph3": + case "graph5": + options["yaxis"]["tickFormatter"] = function(val,axis) { return humanize_size(val); } + } + + + + $.plot($('#'+id+'_graph'),series,options); +} + +function quickstart_setup(){ + + $('#quickstart').button("disable"); + + $('#quickstart_form input').click(function(){ + $('#quickstart').val($(this).val()); + $('#quickstart').button("enable"); + }); + + $('#quickstart').click(function(){ + Sunstone.runAction($(this).val()); + return false; + }); +} + +function graph_autorefresh(){ + setInterval(function(){ + refresh_graphs(); + },GRAPH_AUTOREFRESH_INTERVAL); + +} + +function refresh_graphs(){ + Sunstone.runAction("Host.monitor_all", graph1); + Sunstone.runAction("Host.monitor_all", graph2); + Sunstone.runAction("Host.monitor_all", graph3); + Sunstone.runAction("VM.monitor_all", graph4); + Sunstone.runAction("VM.monitor_all", graph5); +} + $(document).ready(function(){ //Dashboard link listener $("#dashboard_table h3 a").live("click", function (){ @@ -164,13 +241,17 @@ $(document).ready(function(){ showTab(tab); return false; }); - + emptyDashboard(); if (uid!=0) { $("td.oneadmin").hide(); } - - + + quickstart_setup(); + + refresh_graphs(); + graph_autorefresh(); + }); //puts the dashboard values into "retrieving" @@ -180,62 +261,73 @@ function emptyDashboard(){ function updateDashboard(what,json_info){ - db = $('#dashboard_tab'); - switch (what){ - case "hosts": - total_hosts=json_info.length; - active_hosts=0; - $.each(json_info,function(){ - if (parseInt(this.HOST.STATE) < 3){ - active_hosts++;} - }); - $('#total_hosts',db).html(total_hosts); - $('#active_hosts',db).html(active_hosts); - break; - case "clusters": - total_clusters=json_info.length; - $('#total_clusters',db).html(total_clusters); - break; - case "vms": - total_vms=json_info.length; - running_vms=0; + var db = $('#dashboard_tab'); + switch (what){ + case "hosts": + var total_hosts=json_info.length; + var active_hosts=0; + $.each(json_info,function(){ + if (parseInt(this.HOST.STATE) < 3){ + active_hosts++;} + }); + $('#total_hosts',db).html(total_hosts+' / '); + $('#active_hosts',db).html(active_hosts); + break; + case "clusters": + var total_clusters=json_info.length; + $('#total_clusters',db).html(total_clusters); + break; + case "vms": + var total_vms=json_info.length; + var running_vms=0; failed_vms=0; - $.each(json_info,function(){ - vm_state = parseInt(this.VM.STATE); - if (vm_state == 3){ - running_vms++; - } - else if (vm_state == 7) { - failed_vms++; - } - }); - $('#total_vms',db).html(total_vms); - $('#running_vms',db).html(running_vms); - $('#failed_vms',db).html(failed_vms); - break; - case "vnets": - public_vnets=0; - total_vnets=json_info.length; - $.each(json_info,function(){ - if (parseInt(this.VNET.PUBLIC)){ - public_vnets++;} - }); - $('#total_vnets',db).html(total_vnets); - $('#public_vnets',db).html(public_vnets); - break; - case "users": - total_users=json_info.length; - $('#total_users',db).html(total_users); - break; - case "images": - total_images=json_info.length; - public_images=0; - $.each(json_info,function(){ - if (parseInt(this.IMAGE.PUBLIC)){ - public_images++;} - }); - $('#total_images',db).html(total_images); - $('#public_images',db).html(public_images); - break; - } -} + $.each(json_info,function(){ + vm_state = parseInt(this.VM.STATE); + if (vm_state == 3){ + running_vms++; + } + else if (vm_state == 7) { + failed_vms++; + } + }); + $('#total_vms',db).html(total_vms+' / '); + $('#running_vms',db).html(running_vms+' / '); + $('#failed_vms',db).html(failed_vms); + break; + case "vnets": + var public_vnets=0; + var total_vnets=json_info.length; + $.each(json_info,function(){ + if (parseInt(this.VNET.PUBLIC)){ + public_vnets++;} + }); + $('#total_vnets',db).html(total_vnets+' / '); + $('#public_vnets',db).html(public_vnets); + break; + case "users": + var total_users=json_info.length; + $('#total_users',db).html(total_users); + break; + case "images": + var total_images=json_info.length; + var public_images=0; + $.each(json_info,function(){ + if (parseInt(this.IMAGE.PUBLIC)){ + public_images++;} + }); + $('#total_images',db).html(total_images+' / '); + $('#public_images',db).html(public_images); + break; + case "templates": + var total_templates=json_info.length; + var public_templates=0; + $.each(json_info,function(){ + if (parseInt(this.VMTEMPLATE.PUBLIC)){ + public_templates++; + } + }); + $('#total_templates',db).html(total_templates+' / '); + $('#public_templates',db).html(public_templates); + break; + } +} \ No newline at end of file diff --git a/src/sunstone/public/js/plugins/hosts-tab.js b/src/sunstone/public/js/plugins/hosts-tab.js index 17c005fb62..7673b61885 100644 --- a/src/sunstone/public/js/plugins/hosts-tab.js +++ b/src/sunstone/public/js/plugins/hosts-tab.js @@ -16,6 +16,24 @@ /*Host tab plugin*/ +var HOST_HISTORY_LENGTH = 40; +var host_graphs = [ + { + title : "CPU Monitoring information", + monitor_resources : "cpu_usage,used_cpu,max_cpu", + humanize_figures : false, + history_length : HOST_HISTORY_LENGTH + }, + { + title: "Memory monitoring information", + monitor_resources : "mem_usage,used_mem,max_mem", + humanize_figures : true, + history_length : HOST_HISTORY_LENGTH + } +] + + + var hosts_tab_content = '
\
\ @@ -198,7 +216,28 @@ var host_actions = { OpenNebula.Cluster.list({success: updateClustersView, error: onError}); } }, - + + "Host.monitor" : { + type: "monitor", + call : OpenNebula.Host.monitor, + callback: function(req,response) { + var info = req.request.data[0].monitor; + plot_graph(response,'#host_monitoring_tab', + 'host_monitor_',info); + }, + error: onError + }, + + "Host.monitor_all" : { + type: "monitor_global", + call: OpenNebula.Host.monitor_all, + callback: function(req,response) { + var info = req.request.data[0].monitor; + plot_global_graph(response,info); + }, + error: onError + }, + "Cluster.create" : { type: "create", call : OpenNebula.Cluster.create, @@ -208,7 +247,7 @@ var host_actions = { error : onError, notify: true }, - + "Cluster.create_dialog" : { type: "custom", call: popUpCreateClusterDialog @@ -327,6 +366,10 @@ var host_info_panel = { "host_template_tab" : { title: "Host template", content: "" + }, + "host_monitoring_tab": { + title: "Monitoring information", + content: "" } }; @@ -533,7 +576,7 @@ function updateHostInfo(request,host){ '+host_info.HOST_SHARE.USED_CPU+'\ \ \ - Used CPU(allocated)\ + Used CPU (allocated)\ '+host_info.HOST_SHARE.CPU_USAGE+'\ \ \ @@ -552,11 +595,23 @@ function updateHostInfo(request,host){ prettyPrintJSON(host_info.TEMPLATE)+ '' } - + + var monitor_tab = { + title: "Monitoring information", + content : generateMonitoringDivs(host_graphs,"host_monitor_") + } + //Sunstone.updateInfoPanelTab(info_panel_name,tab_name, new tab object); Sunstone.updateInfoPanelTab("host_info_panel","host_info_tab",info_tab); Sunstone.updateInfoPanelTab("host_info_panel","host_template_tab",template_tab); + Sunstone.updateInfoPanelTab("host_info_panel","host_monitoring_tab",monitor_tab); + Sunstone.popUpInfoPanel("host_info_panel"); + //pop up panel while we retrieve the graphs + for (var i=0; i\
\ @@ -305,13 +330,7 @@ var vm_actions = { colored_log += line + "\n"; } - var log_tab = { - title: "VM log", - content: '
'+colored_log+'
' - } - Sunstone.updateInfoPanelTab("vm_info_panel","vm_log_tab",log_tab); - Sunstone.popUpInfoPanel("vm_info_panel",0); - + $('#vm_log_tab#').html('
'+colored_log+'
') }, error: function(request,error_json){ $("#vm_log pre").html(''); @@ -333,7 +352,27 @@ var vm_actions = { callback: null, error: onError, notify: true - } + }, + + "VM.monitor" : { + type: "monitor", + call : OpenNebula.VM.monitor, + callback: function(req,response) { + var info = req.request.data[0].monitor; + plot_graph(response,'#vm_monitoring_tab', + 'vm_monitor_',info); + }, + error: onError + }, + "VM.monitor_all" : { + type: "monitor_global", + call: OpenNebula.VM.monitor_all, + callback: function(req,response) { + var info = req.request.data[0].monitor; + plot_global_graph(response,info); + }, + error: onError + }, } @@ -624,30 +663,36 @@ function updateVMInfo(request,vm){ \ ' } - + var template_tab = { title: "VM Template", content: '\ '+ prettyPrintJSON(vm_info.TEMPLATE)+ - '
VM template
' + '' } - + var log_tab = { title: "VM log", - content: '
'+spinner+'
' + content: '
'+spinner+'
' } - - Sunstone.updateInfoPanelTab("vm_info_panel","vm_info_tab",info_tab); + + var monitoring_tab = { + title: "Monitoring information", + content: generateMonitoringDivs(vm_graphs,"vm_monitor_") + } + + Sunstone.updateInfoPanelTab("vm_info_panel","vm_info_tab",info_tab); Sunstone.updateInfoPanelTab("vm_info_panel","vm_template_tab",template_tab); Sunstone.updateInfoPanelTab("vm_info_panel","vm_log_tab",log_tab); - - - //Here it is special, as we will let the callback from the VM.log - //action popUp the info panel again when the info is received. + Sunstone.updateInfoPanelTab("vm_info_panel","vm_monitoring_tab",monitoring_tab); + + //Pop up the info panel and asynchronously get vm_log and stats Sunstone.popUpInfoPanel("vm_info_panel"); Sunstone.runAction("VM.log",vm_info.ID); - + for (var i=0; i\ +\ +\ +
'+spinner+'
\ +'; + }); + + return str; +} + +function plot_graph(data,context,id_prefix,info){ + var labels = info.monitor_resources; + var humanize = info.humanize_figures ? humanize_size : function(val){return val}; + var labels_arr = labels.split(','); + var id_suffix = labels.replace(/,/g,'_'); + var series = []; + var serie = null; + + for (var i = 0; i< labels_arr.length; i++) { + serie = { + label: labels_arr[i], + data: data[i] + }; + series.push(serie); + }; + + var options = { + legend : { show : true, + noColumns: labels_arr.length, + container: $('#legend_'+id_suffix) + }, + xaxis : { mode: "time", + timeformat: "%h:%M" + }, + yaxis : { labelWidth: 40, + tickFormatter: function(val, axis) { + return humanize(val); + } + } + } + + id = id_prefix + id_suffix; + $.plot($('#'+id, context),series,options); +} + //functions that used as true and false conditions for testing mainly function True(){ return true; } function False(){ return false; -} +} diff --git a/src/sunstone/public/js/sunstone.js b/src/sunstone/public/js/sunstone.js index 4492c40038..7add76c027 100644 --- a/src/sunstone/public/js/sunstone.js +++ b/src/sunstone/public/js/sunstone.js @@ -17,7 +17,7 @@ var cookie = {}; var username = ''; var uid = ''; -var spinner = 'retrieving'; +var spinner = 'retrieving'; //Sunstone configuration is formed by predifined "actions", main tabs @@ -187,12 +187,14 @@ var Sunstone = { // * "create" calls to opennebula.js // * "single" element calls to opennebula.js // * "list" (get the pool of elements) calls to opennebula.js + // * "monitor_global" (returns monitoring information from a pool of elements + // * "monitor_single" (returns monitoring information from 1 element to create graphs) // * "multiple" - actions to be run on a given list of elements // (with maybe an extra parameter). // * The default actions. Simple call the the pre-defined "call" // function with an extraparam if defined. switch (action_cfg.type){ - + case "create": case "register": call({data:data_arg, success: callback, error:err}); @@ -203,6 +205,13 @@ var Sunstone = { case "list": call({success: callback, error:err}); break; + case "monitor_global": + call({timeout: true, success: callback, error:err, data: {monitor: data_arg}}); + break; + case "monitor": + case "monitor_single": + call({timeout: true, success: callback, error:err, data: {id:data_arg, monitor: extra_param}}); + break; case "multiple": //run on the list of nodes that come on the data $.each(data_arg,function(){ diff --git a/src/sunstone/public/vendor/flot/LICENSE.txt b/src/sunstone/public/vendor/flot/LICENSE.txt new file mode 100644 index 0000000000..07d5b2094d --- /dev/null +++ b/src/sunstone/public/vendor/flot/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright (c) 2007-2009 IOLA and Ole Laursen + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/sunstone/public/vendor/flot/NOTICE b/src/sunstone/public/vendor/flot/NOTICE new file mode 100644 index 0000000000..384d1f5cfc --- /dev/null +++ b/src/sunstone/public/vendor/flot/NOTICE @@ -0,0 +1,6 @@ +THIRD-PARTY SOFTWARE + + * Author: Ole Laursen (http://people.iola.dk/olau/) + * Info: http://code.google.com/p/flot/ + * Copyright: Copyright (c) 2007-2009 IOLA and Ole Laursen + * License: MIT License: http://www.opensource.org/licenses/mit-license.php (or LICENSE.txt) diff --git a/src/sunstone/public/vendor/flot/README.txt b/src/sunstone/public/vendor/flot/README.txt new file mode 100644 index 0000000000..1e49787a05 --- /dev/null +++ b/src/sunstone/public/vendor/flot/README.txt @@ -0,0 +1,90 @@ +About +----- + +Flot is a Javascript plotting library for jQuery. Read more at the +website: + + http://code.google.com/p/flot/ + +Take a look at the examples linked from above, they should give a good +impression of what Flot can do and the source code of the examples is +probably the fastest way to learn how to use Flot. + + +Installation +------------ + +Just include the Javascript file after you've included jQuery. + +Generally, all browsers that support the HTML5 canvas tag are +supported. + +For support for Internet Explorer < 9, you can use Excanvas, a canvas +emulator; this is used in the examples bundled with Flot. You just +include the excanvas script like this: + + + +If it's not working on your development IE 6.0, check that it has +support for VML which Excanvas is relying on. It appears that some +stripped down versions used for test environments on virtual machines +lack the VML support. + +You can also try using Flashcanvas (see +http://code.google.com/p/flashcanvas/), which uses Flash to do the +emulation. Although Flash can be a bit slower to load than VML, if +you've got a lot of points, the Flash version can be much faster +overall. Flot contains some wrapper code for activating Excanvas which +Flashcanvas is compatible with. + +You need at least jQuery 1.2.6, but try at least 1.3.2 for interactive +charts because of performance improvements in event handling. + + +Basic usage +----------- + +Create a placeholder div to put the graph in: + +
+ +You need to set the width and height of this div, otherwise the plot +library doesn't know how to scale the graph. You can do it inline like +this: + +
+ +You can also do it with an external stylesheet. Make sure that the +placeholder isn't within something with a display:none CSS property - +in that case, Flot has trouble measuring label dimensions which +results in garbled looks and might have trouble measuring the +placeholder dimensions which is fatal (it'll throw an exception). + +Then when the div is ready in the DOM, which is usually on document +ready, run the plot function: + + $.plot($("#placeholder"), data, options); + +Here, data is an array of data series and options is an object with +settings if you want to customize the plot. Take a look at the +examples for some ideas of what to put in or look at the reference +in the file "API.txt". Here's a quick example that'll draw a line from +(0, 0) to (1, 1): + + $.plot($("#placeholder"), [ [[0, 0], [1, 1]] ], { yaxis: { max: 1 } }); + +The plot function immediately draws the chart and then returns a plot +object with a couple of methods. + + +What's with the name? +--------------------- + +First: it's pronounced with a short o, like "plot". Not like "flawed". + +So "Flot" rhymes with "plot". + +And if you look up "flot" in a Danish-to-English dictionary, some up +the words that come up are "good-looking", "attractive", "stylish", +"smart", "impressive", "extravagant". One of the main goals with Flot +is pretty looks. diff --git a/src/sunstone/public/vendor/flot/jquery.flot.min.js b/src/sunstone/public/vendor/flot/jquery.flot.min.js new file mode 100644 index 0000000000..4467fc5d8c --- /dev/null +++ b/src/sunstone/public/vendor/flot/jquery.flot.min.js @@ -0,0 +1,6 @@ +/* Javascript plotting library for jQuery, v. 0.7. + * + * Released under the MIT license by IOLA, December 2007. + * + */ +(function(b){b.color={};b.color.make=function(d,e,g,f){var c={};c.r=d||0;c.g=e||0;c.b=g||0;c.a=f!=null?f:1;c.add=function(h,j){for(var k=0;k=1){return"rgb("+[c.r,c.g,c.b].join(",")+")"}else{return"rgba("+[c.r,c.g,c.b,c.a].join(",")+")"}};c.normalize=function(){function h(k,j,l){return jl?l:j)}c.r=h(0,parseInt(c.r),255);c.g=h(0,parseInt(c.g),255);c.b=h(0,parseInt(c.b),255);c.a=h(0,c.a,1);return c};c.clone=function(){return b.color.make(c.r,c.b,c.g,c.a)};return c.normalize()};b.color.extract=function(d,e){var c;do{c=d.css(e).toLowerCase();if(c!=""&&c!="transparent"){break}d=d.parent()}while(!b.nodeName(d.get(0),"body"));if(c=="rgba(0, 0, 0, 0)"){c="transparent"}return b.color.parse(c)};b.color.parse=function(c){var d,f=b.color.make;if(d=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c)){return f(parseInt(d[1],10),parseInt(d[2],10),parseInt(d[3],10))}if(d=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(c)){return f(parseInt(d[1],10),parseInt(d[2],10),parseInt(d[3],10),parseFloat(d[4]))}if(d=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c)){return f(parseFloat(d[1])*2.55,parseFloat(d[2])*2.55,parseFloat(d[3])*2.55)}if(d=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(c)){return f(parseFloat(d[1])*2.55,parseFloat(d[2])*2.55,parseFloat(d[3])*2.55,parseFloat(d[4]))}if(d=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c)){return f(parseInt(d[1],16),parseInt(d[2],16),parseInt(d[3],16))}if(d=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c)){return f(parseInt(d[1]+d[1],16),parseInt(d[2]+d[2],16),parseInt(d[3]+d[3],16))}var e=b.trim(c).toLowerCase();if(e=="transparent"){return f(255,255,255,0)}else{d=a[e]||[0,0,0];return f(d[0],d[1],d[2])}};var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);(function(c){function b(av,ai,J,af){var Q=[],O={colors:["#edc240","#afd8f8","#cb4b4b","#4da74d","#9440ed"],legend:{show:true,noColumns:1,labelFormatter:null,labelBoxBorderColor:"#ccc",container:null,position:"ne",margin:5,backgroundColor:null,backgroundOpacity:0.85},xaxis:{show:null,position:"bottom",mode:null,color:null,tickColor:null,transform:null,inverseTransform:null,min:null,max:null,autoscaleMargin:null,ticks:null,tickFormatter:null,labelWidth:null,labelHeight:null,reserveSpace:null,tickLength:null,alignTicksWithAxis:null,tickDecimals:null,tickSize:null,minTickSize:null,monthNames:null,timeformat:null,twelveHourClock:false},yaxis:{autoscaleMargin:0.02,position:"left"},xaxes:[],yaxes:[],series:{points:{show:false,radius:3,lineWidth:2,fill:true,fillColor:"#ffffff",symbol:"circle"},lines:{lineWidth:2,fill:false,fillColor:null,steps:false},bars:{show:false,lineWidth:2,barWidth:1,fill:true,fillColor:null,align:"left",horizontal:false},shadowSize:3},grid:{show:true,aboveData:false,color:"#545454",backgroundColor:null,borderColor:null,tickColor:null,labelMargin:5,axisMargin:8,borderWidth:2,minBorderMargin:null,markings:null,markingsColor:"#f4f4f4",markingsLineWidth:2,clickable:false,hoverable:false,autoHighlight:true,mouseActiveRadius:10},hooks:{}},az=null,ad=null,y=null,H=null,A=null,p=[],aw=[],q={left:0,right:0,top:0,bottom:0},G=0,I=0,h=0,w=0,ak={processOptions:[],processRawData:[],processDatapoints:[],drawSeries:[],draw:[],bindEvents:[],drawOverlay:[],shutdown:[]},aq=this;aq.setData=aj;aq.setupGrid=t;aq.draw=W;aq.getPlaceholder=function(){return av};aq.getCanvas=function(){return az};aq.getPlotOffset=function(){return q};aq.width=function(){return h};aq.height=function(){return w};aq.offset=function(){var aB=y.offset();aB.left+=q.left;aB.top+=q.top;return aB};aq.getData=function(){return Q};aq.getAxes=function(){var aC={},aB;c.each(p.concat(aw),function(aD,aE){if(aE){aC[aE.direction+(aE.n!=1?aE.n:"")+"axis"]=aE}});return aC};aq.getXAxes=function(){return p};aq.getYAxes=function(){return aw};aq.c2p=C;aq.p2c=ar;aq.getOptions=function(){return O};aq.highlight=x;aq.unhighlight=T;aq.triggerRedrawOverlay=f;aq.pointOffset=function(aB){return{left:parseInt(p[aA(aB,"x")-1].p2c(+aB.x)+q.left),top:parseInt(aw[aA(aB,"y")-1].p2c(+aB.y)+q.top)}};aq.shutdown=ag;aq.resize=function(){B();g(az);g(ad)};aq.hooks=ak;F(aq);Z(J);X();aj(ai);t();W();ah();function an(aD,aB){aB=[aq].concat(aB);for(var aC=0;aC=O.colors.length){aG=0;++aF}}var aH=0,aN;for(aG=0;aGa3.datamax&&a1!=aB){a3.datamax=a1}}c.each(m(),function(a1,a2){a2.datamin=aO;a2.datamax=aI;a2.used=false});for(aU=0;aU0&&aT[aR-aP]!=null&&aT[aR-aP]!=aT[aR]&&aT[aR-aP+1]!=aT[aR+1]){for(aN=0;aNaM){aM=a0}}if(aX.y){if(a0aV){aV=a0}}}}if(aJ.bars.show){var aY=aJ.bars.align=="left"?0:-aJ.bars.barWidth/2;if(aJ.bars.horizontal){aQ+=aY;aV+=aY+aJ.bars.barWidth}else{aK+=aY;aM+=aY+aJ.bars.barWidth}}aF(aJ.xaxis,aK,aM);aF(aJ.yaxis,aQ,aV)}c.each(m(),function(a1,a2){if(a2.datamin==aO){a2.datamin=null}if(a2.datamax==aI){a2.datamax=null}})}function j(aB,aC){var aD=document.createElement("canvas");aD.className=aC;aD.width=G;aD.height=I;if(!aB){c(aD).css({position:"absolute",left:0,top:0})}c(aD).appendTo(av);if(!aD.getContext){aD=window.G_vmlCanvasManager.initElement(aD)}aD.getContext("2d").save();return aD}function B(){G=av.width();I=av.height();if(G<=0||I<=0){throw"Invalid dimensions for plot, width = "+G+", height = "+I}}function g(aC){if(aC.width!=G){aC.width=G}if(aC.height!=I){aC.height=I}var aB=aC.getContext("2d");aB.restore();aB.save()}function X(){var aC,aB=av.children("canvas.base"),aD=av.children("canvas.overlay");if(aB.length==0||aD==0){av.html("");av.css({padding:0});if(av.css("position")=="static"){av.css("position","relative")}B();az=j(true,"base");ad=j(false,"overlay");aC=false}else{az=aB.get(0);ad=aD.get(0);aC=true}H=az.getContext("2d");A=ad.getContext("2d");y=c([ad,az]);if(aC){av.data("plot").shutdown();aq.resize();A.clearRect(0,0,G,I);y.unbind();av.children().not([az,ad]).remove()}av.data("plot",aq)}function ah(){if(O.grid.hoverable){y.mousemove(aa);y.mouseleave(l)}if(O.grid.clickable){y.click(R)}an(ak.bindEvents,[y])}function ag(){if(M){clearTimeout(M)}y.unbind("mousemove",aa);y.unbind("mouseleave",l);y.unbind("click",R);an(ak.shutdown,[y])}function r(aG){function aC(aH){return aH}var aF,aB,aD=aG.options.transform||aC,aE=aG.options.inverseTransform;if(aG.direction=="x"){aF=aG.scale=h/Math.abs(aD(aG.max)-aD(aG.min));aB=Math.min(aD(aG.max),aD(aG.min))}else{aF=aG.scale=w/Math.abs(aD(aG.max)-aD(aG.min));aF=-aF;aB=Math.max(aD(aG.max),aD(aG.min))}if(aD==aC){aG.p2c=function(aH){return(aH-aB)*aF}}else{aG.p2c=function(aH){return(aD(aH)-aB)*aF}}if(!aE){aG.c2p=function(aH){return aB+aH/aF}}else{aG.c2p=function(aH){return aE(aB+aH/aF)}}}function L(aD){var aB=aD.options,aF,aJ=aD.ticks||[],aI=[],aE,aK=aB.labelWidth,aG=aB.labelHeight,aC;function aH(aM,aL){return c('
'+aM.join("")+"
").appendTo(av)}if(aD.direction=="x"){if(aK==null){aK=Math.floor(G/(aJ.length>0?aJ.length:1))}if(aG==null){aI=[];for(aF=0;aF'+aE+"
")}}if(aI.length>0){aI.push('
');aC=aH(aI,"width:10000px;");aG=aC.height();aC.remove()}}}else{if(aK==null||aG==null){for(aF=0;aF'+aE+"
")}}if(aI.length>0){aC=aH(aI,"");if(aK==null){aK=aC.children().width()}if(aG==null){aG=aC.find("div.tickLabel").height()}aC.remove()}}}if(aK==null){aK=0}if(aG==null){aG=0}aD.labelWidth=aK;aD.labelHeight=aG}function au(aD){var aC=aD.labelWidth,aL=aD.labelHeight,aH=aD.options.position,aF=aD.options.tickLength,aG=O.grid.axisMargin,aJ=O.grid.labelMargin,aK=aD.direction=="x"?p:aw,aE;var aB=c.grep(aK,function(aN){return aN&&aN.options.position==aH&&aN.reserveSpace});if(c.inArray(aD,aB)==aB.length-1){aG=0}if(aF==null){aF="full"}var aI=c.grep(aK,function(aN){return aN&&aN.reserveSpace});var aM=c.inArray(aD,aI)==0;if(!aM&&aF=="full"){aF=5}if(!isNaN(+aF)){aJ+=+aF}if(aD.direction=="x"){aL+=aJ;if(aH=="bottom"){q.bottom+=aL+aG;aD.box={top:I-q.bottom,height:aL}}else{aD.box={top:q.top+aG,height:aL};q.top+=aL+aG}}else{aC+=aJ;if(aH=="left"){aD.box={left:q.left+aG,width:aC};q.left+=aC+aG}else{q.right+=aC+aG;aD.box={left:G-q.right,width:aC}}}aD.position=aH;aD.tickLength=aF;aD.box.padding=aJ;aD.innermost=aM}function U(aB){if(aB.direction=="x"){aB.box.left=q.left;aB.box.width=h}else{aB.box.top=q.top;aB.box.height=w}}function t(){var aC,aE=m();c.each(aE,function(aF,aG){aG.show=aG.options.show;if(aG.show==null){aG.show=aG.used}aG.reserveSpace=aG.show||aG.options.reserveSpace;n(aG)});allocatedAxes=c.grep(aE,function(aF){return aF.reserveSpace});q.left=q.right=q.top=q.bottom=0;if(O.grid.show){c.each(allocatedAxes,function(aF,aG){S(aG);P(aG);ap(aG,aG.ticks);L(aG)});for(aC=allocatedAxes.length-1;aC>=0;--aC){au(allocatedAxes[aC])}var aD=O.grid.minBorderMargin;if(aD==null){aD=0;for(aC=0;aC=0){aD=0}}if(aF.max==null){aB+=aH*aG;if(aB>0&&aE.datamax!=null&&aE.datamax<=0){aB=0}}}}aE.min=aD;aE.max=aB}function S(aG){var aM=aG.options;var aH;if(typeof aM.ticks=="number"&&aM.ticks>0){aH=aM.ticks}else{aH=0.3*Math.sqrt(aG.direction=="x"?G:I)}var aT=(aG.max-aG.min)/aH,aO,aB,aN,aR,aS,aQ,aI;if(aM.mode=="time"){var aJ={second:1000,minute:60*1000,hour:60*60*1000,day:24*60*60*1000,month:30*24*60*60*1000,year:365.2425*24*60*60*1000};var aK=[[1,"second"],[2,"second"],[5,"second"],[10,"second"],[30,"second"],[1,"minute"],[2,"minute"],[5,"minute"],[10,"minute"],[30,"minute"],[1,"hour"],[2,"hour"],[4,"hour"],[8,"hour"],[12,"hour"],[1,"day"],[2,"day"],[3,"day"],[0.25,"month"],[0.5,"month"],[1,"month"],[2,"month"],[3,"month"],[6,"month"],[1,"year"]];var aC=0;if(aM.minTickSize!=null){if(typeof aM.tickSize=="number"){aC=aM.tickSize}else{aC=aM.minTickSize[0]*aJ[aM.minTickSize[1]]}}for(var aS=0;aS=aC){break}}aO=aK[aS][0];aN=aK[aS][1];if(aN=="year"){aQ=Math.pow(10,Math.floor(Math.log(aT/aJ.year)/Math.LN10));aI=(aT/aJ.year)/aQ;if(aI<1.5){aO=1}else{if(aI<3){aO=2}else{if(aI<7.5){aO=5}else{aO=10}}}aO*=aQ}aG.tickSize=aM.tickSize||[aO,aN];aB=function(aX){var a2=[],a0=aX.tickSize[0],a3=aX.tickSize[1],a1=new Date(aX.min);var aW=a0*aJ[a3];if(a3=="second"){a1.setUTCSeconds(a(a1.getUTCSeconds(),a0))}if(a3=="minute"){a1.setUTCMinutes(a(a1.getUTCMinutes(),a0))}if(a3=="hour"){a1.setUTCHours(a(a1.getUTCHours(),a0))}if(a3=="month"){a1.setUTCMonth(a(a1.getUTCMonth(),a0))}if(a3=="year"){a1.setUTCFullYear(a(a1.getUTCFullYear(),a0))}a1.setUTCMilliseconds(0);if(aW>=aJ.minute){a1.setUTCSeconds(0)}if(aW>=aJ.hour){a1.setUTCMinutes(0)}if(aW>=aJ.day){a1.setUTCHours(0)}if(aW>=aJ.day*4){a1.setUTCDate(1)}if(aW>=aJ.year){a1.setUTCMonth(0)}var a5=0,a4=Number.NaN,aY;do{aY=a4;a4=a1.getTime();a2.push(a4);if(a3=="month"){if(a0<1){a1.setUTCDate(1);var aV=a1.getTime();a1.setUTCMonth(a1.getUTCMonth()+1);var aZ=a1.getTime();a1.setTime(a4+a5*aJ.hour+(aZ-aV)*a0);a5=a1.getUTCHours();a1.setUTCHours(0)}else{a1.setUTCMonth(a1.getUTCMonth()+a0)}}else{if(a3=="year"){a1.setUTCFullYear(a1.getUTCFullYear()+a0)}else{a1.setTime(a4+aW)}}}while(a4aU){aP=aU}aQ=Math.pow(10,-aP);aI=aT/aQ;if(aI<1.5){aO=1}else{if(aI<3){aO=2;if(aI>2.25&&(aU==null||aP+1<=aU)){aO=2.5;++aP}}else{if(aI<7.5){aO=5}else{aO=10}}}aO*=aQ;if(aM.minTickSize!=null&&aO0){if(aM.min==null){aG.min=Math.min(aG.min,aL[0])}if(aM.max==null&&aL.length>1){aG.max=Math.max(aG.max,aL[aL.length-1])}}aB=function(aX){var aY=[],aV,aW;for(aW=0;aW1&&/\..*0$/.test((aD[1]-aD[0]).toFixed(aE)))){aG.tickDecimals=aE}}}}aG.tickGenerator=aB;if(c.isFunction(aM.tickFormatter)){aG.tickFormatter=function(aV,aW){return""+aM.tickFormatter(aV,aW)}}else{aG.tickFormatter=aR}}function P(aF){var aH=aF.options.ticks,aG=[];if(aH==null||(typeof aH=="number"&&aH>0)){aG=aF.tickGenerator(aF)}else{if(aH){if(c.isFunction(aH)){aG=aH({min:aF.min,max:aF.max})}else{aG=aH}}}var aE,aB;aF.ticks=[];for(aE=0;aE1){aC=aD[1]}}else{aB=+aD}if(aC==null){aC=aF.tickFormatter(aB,aF)}if(!isNaN(aB)){aF.ticks.push({v:aB,label:aC})}}}function ap(aB,aC){if(aB.options.autoscaleMargin&&aC.length>0){if(aB.options.min==null){aB.min=Math.min(aB.min,aC[0].v)}if(aB.options.max==null&&aC.length>1){aB.max=Math.max(aB.max,aC[aC.length-1].v)}}}function W(){H.clearRect(0,0,G,I);var aC=O.grid;if(aC.show&&aC.backgroundColor){N()}if(aC.show&&!aC.aboveData){ac()}for(var aB=0;aBaG){var aC=aH;aH=aG;aG=aC}return{from:aH,to:aG,axis:aE}}function N(){H.save();H.translate(q.left,q.top);H.fillStyle=am(O.grid.backgroundColor,w,0,"rgba(255, 255, 255, 0)");H.fillRect(0,0,h,w);H.restore()}function ac(){var aF;H.save();H.translate(q.left,q.top);var aH=O.grid.markings;if(aH){if(c.isFunction(aH)){var aK=aq.getAxes();aK.xmin=aK.xaxis.min;aK.xmax=aK.xaxis.max;aK.ymin=aK.yaxis.min;aK.ymax=aK.yaxis.max;aH=aH(aK)}for(aF=0;aFaC.axis.max||aI.toaI.axis.max){continue}aC.from=Math.max(aC.from,aC.axis.min);aC.to=Math.min(aC.to,aC.axis.max);aI.from=Math.max(aI.from,aI.axis.min);aI.to=Math.min(aI.to,aI.axis.max);if(aC.from==aC.to&&aI.from==aI.to){continue}aC.from=aC.axis.p2c(aC.from);aC.to=aC.axis.p2c(aC.to);aI.from=aI.axis.p2c(aI.from);aI.to=aI.axis.p2c(aI.to);if(aC.from==aC.to||aI.from==aI.to){H.beginPath();H.strokeStyle=aD.color||O.grid.markingsColor;H.lineWidth=aD.lineWidth||O.grid.markingsLineWidth;H.moveTo(aC.from,aI.from);H.lineTo(aC.to,aI.to);H.stroke()}else{H.fillStyle=aD.color||O.grid.markingsColor;H.fillRect(aC.from,aI.to,aC.to-aC.from,aI.from-aI.to)}}}var aK=m(),aM=O.grid.borderWidth;for(var aE=0;aEaB.max||(aQ=="full"&&aM>0&&(aO==aB.min||aO==aB.max))){continue}if(aB.direction=="x"){aN=aB.p2c(aO);aJ=aQ=="full"?-w:aQ;if(aB.position=="top"){aJ=-aJ}}else{aL=aB.p2c(aO);aP=aQ=="full"?-h:aQ;if(aB.position=="left"){aP=-aP}}if(H.lineWidth==1){if(aB.direction=="x"){aN=Math.floor(aN)+0.5}else{aL=Math.floor(aL)+0.5}}H.moveTo(aN,aL);H.lineTo(aN+aP,aL+aJ)}H.stroke()}if(aM){H.lineWidth=aM;H.strokeStyle=O.grid.borderColor;H.strokeRect(-aM/2,-aM/2,h+aM,w+aM)}H.restore()}function k(){av.find(".tickLabels").remove();var aG=['
'];var aJ=m();for(var aD=0;aD');for(var aE=0;aEaC.max){continue}var aK={},aI;if(aC.direction=="x"){aI="center";aK.left=Math.round(q.left+aC.p2c(aH.v)-aC.labelWidth/2);if(aC.position=="bottom"){aK.top=aF.top+aF.padding}else{aK.bottom=I-(aF.top+aF.height-aF.padding)}}else{aK.top=Math.round(q.top+aC.p2c(aH.v)-aC.labelHeight/2);if(aC.position=="left"){aK.right=G-(aF.left+aF.width-aF.padding);aI="right"}else{aK.left=aF.left+aF.padding;aI="left"}}aK.width=aC.labelWidth;var aB=["position:absolute","text-align:"+aI];for(var aL in aK){aB.push(aL+":"+aK[aL]+"px")}aG.push('
'+aH.label+"
")}aG.push("
")}aG.push("
");av.append(aG.join(""))}function d(aB){if(aB.lines.show){at(aB)}if(aB.bars.show){e(aB)}if(aB.points.show){ao(aB)}}function at(aE){function aD(aP,aQ,aI,aU,aT){var aV=aP.points,aJ=aP.pointsize,aN=null,aM=null;H.beginPath();for(var aO=aJ;aO=aR&&aS>aT.max){if(aR>aT.max){continue}aL=(aT.max-aS)/(aR-aS)*(aK-aL)+aL;aS=aT.max}else{if(aR>=aS&&aR>aT.max){if(aS>aT.max){continue}aK=(aT.max-aS)/(aR-aS)*(aK-aL)+aL;aR=aT.max}}if(aL<=aK&&aL=aK&&aL>aU.max){if(aK>aU.max){continue}aS=(aU.max-aL)/(aK-aL)*(aR-aS)+aS;aL=aU.max}else{if(aK>=aL&&aK>aU.max){if(aL>aU.max){continue}aR=(aU.max-aL)/(aK-aL)*(aR-aS)+aS;aK=aU.max}}if(aL!=aN||aS!=aM){H.moveTo(aU.p2c(aL)+aQ,aT.p2c(aS)+aI)}aN=aK;aM=aR;H.lineTo(aU.p2c(aK)+aQ,aT.p2c(aR)+aI)}H.stroke()}function aF(aI,aQ,aP){var aW=aI.points,aV=aI.pointsize,aN=Math.min(Math.max(0,aP.min),aP.max),aX=0,aU,aT=false,aM=1,aL=0,aR=0;while(true){if(aV>0&&aX>aW.length+aV){break}aX+=aV;var aZ=aW[aX-aV],aK=aW[aX-aV+aM],aY=aW[aX],aJ=aW[aX+aM];if(aT){if(aV>0&&aZ!=null&&aY==null){aR=aX;aV=-aV;aM=2;continue}if(aV<0&&aX==aL+aV){H.fill();aT=false;aV=-aV;aM=1;aX=aL=aR+aV;continue}}if(aZ==null||aY==null){continue}if(aZ<=aY&&aZ=aY&&aZ>aQ.max){if(aY>aQ.max){continue}aK=(aQ.max-aZ)/(aY-aZ)*(aJ-aK)+aK;aZ=aQ.max}else{if(aY>=aZ&&aY>aQ.max){if(aZ>aQ.max){continue}aJ=(aQ.max-aZ)/(aY-aZ)*(aJ-aK)+aK;aY=aQ.max}}if(!aT){H.beginPath();H.moveTo(aQ.p2c(aZ),aP.p2c(aN));aT=true}if(aK>=aP.max&&aJ>=aP.max){H.lineTo(aQ.p2c(aZ),aP.p2c(aP.max));H.lineTo(aQ.p2c(aY),aP.p2c(aP.max));continue}else{if(aK<=aP.min&&aJ<=aP.min){H.lineTo(aQ.p2c(aZ),aP.p2c(aP.min));H.lineTo(aQ.p2c(aY),aP.p2c(aP.min));continue}}var aO=aZ,aS=aY;if(aK<=aJ&&aK=aP.min){aZ=(aP.min-aK)/(aJ-aK)*(aY-aZ)+aZ;aK=aP.min}else{if(aJ<=aK&&aJ=aP.min){aY=(aP.min-aK)/(aJ-aK)*(aY-aZ)+aZ;aJ=aP.min}}if(aK>=aJ&&aK>aP.max&&aJ<=aP.max){aZ=(aP.max-aK)/(aJ-aK)*(aY-aZ)+aZ;aK=aP.max}else{if(aJ>=aK&&aJ>aP.max&&aK<=aP.max){aY=(aP.max-aK)/(aJ-aK)*(aY-aZ)+aZ;aJ=aP.max}}if(aZ!=aO){H.lineTo(aQ.p2c(aO),aP.p2c(aK))}H.lineTo(aQ.p2c(aZ),aP.p2c(aK));H.lineTo(aQ.p2c(aY),aP.p2c(aJ));if(aY!=aS){H.lineTo(aQ.p2c(aY),aP.p2c(aJ));H.lineTo(aQ.p2c(aS),aP.p2c(aJ))}}}H.save();H.translate(q.left,q.top);H.lineJoin="round";var aG=aE.lines.lineWidth,aB=aE.shadowSize;if(aG>0&&aB>0){H.lineWidth=aB;H.strokeStyle="rgba(0,0,0,0.1)";var aH=Math.PI/18;aD(aE.datapoints,Math.sin(aH)*(aG/2+aB/2),Math.cos(aH)*(aG/2+aB/2),aE.xaxis,aE.yaxis);H.lineWidth=aB/2;aD(aE.datapoints,Math.sin(aH)*(aG/2+aB/4),Math.cos(aH)*(aG/2+aB/4),aE.xaxis,aE.yaxis)}H.lineWidth=aG;H.strokeStyle=aE.color;var aC=ae(aE.lines,aE.color,0,w);if(aC){H.fillStyle=aC;aF(aE.datapoints,aE.xaxis,aE.yaxis)}if(aG>0){aD(aE.datapoints,0,0,aE.xaxis,aE.yaxis)}H.restore()}function ao(aE){function aH(aN,aM,aU,aK,aS,aT,aQ,aJ){var aR=aN.points,aI=aN.pointsize;for(var aL=0;aLaT.max||aOaQ.max){continue}H.beginPath();aP=aT.p2c(aP);aO=aQ.p2c(aO)+aK;if(aJ=="circle"){H.arc(aP,aO,aM,0,aS?Math.PI:Math.PI*2,false)}else{aJ(H,aP,aO,aM,aS)}H.closePath();if(aU){H.fillStyle=aU;H.fill()}H.stroke()}}H.save();H.translate(q.left,q.top);var aG=aE.points.lineWidth,aC=aE.shadowSize,aB=aE.points.radius,aF=aE.points.symbol;if(aG>0&&aC>0){var aD=aC/2;H.lineWidth=aD;H.strokeStyle="rgba(0,0,0,0.1)";aH(aE.datapoints,aB,null,aD+aD/2,true,aE.xaxis,aE.yaxis,aF);H.strokeStyle="rgba(0,0,0,0.2)";aH(aE.datapoints,aB,null,aD/2,true,aE.xaxis,aE.yaxis,aF)}H.lineWidth=aG;H.strokeStyle=aE.color;aH(aE.datapoints,aB,ae(aE.points,aE.color),0,false,aE.xaxis,aE.yaxis,aF);H.restore()}function E(aN,aM,aV,aI,aQ,aF,aD,aL,aK,aU,aR,aC){var aE,aT,aJ,aP,aG,aB,aO,aH,aS;if(aR){aH=aB=aO=true;aG=false;aE=aV;aT=aN;aP=aM+aI;aJ=aM+aQ;if(aTaL.max||aPaK.max){return}if(aEaL.max){aT=aL.max;aB=false}if(aJaK.max){aP=aK.max;aO=false}aE=aL.p2c(aE);aJ=aK.p2c(aJ);aT=aL.p2c(aT);aP=aK.p2c(aP);if(aD){aU.beginPath();aU.moveTo(aE,aJ);aU.lineTo(aE,aP);aU.lineTo(aT,aP);aU.lineTo(aT,aJ);aU.fillStyle=aD(aJ,aP);aU.fill()}if(aC>0&&(aG||aB||aO||aH)){aU.beginPath();aU.moveTo(aE,aJ+aF);if(aG){aU.lineTo(aE,aP+aF)}else{aU.moveTo(aE,aP+aF)}if(aO){aU.lineTo(aT,aP+aF)}else{aU.moveTo(aT,aP+aF)}if(aB){aU.lineTo(aT,aJ+aF)}else{aU.moveTo(aT,aJ+aF)}if(aH){aU.lineTo(aE,aJ+aF)}else{aU.moveTo(aE,aJ+aF)}aU.stroke()}}function e(aD){function aC(aJ,aI,aL,aG,aK,aN,aM){var aO=aJ.points,aF=aJ.pointsize;for(var aH=0;aH")}aH.push("");aF=true}if(aN){aJ=aN(aJ,aM)}aH.push('
'+aJ+"")}if(aF){aH.push("")}if(aH.length==0){return}var aL=''+aH.join("")+"
";if(O.legend.container!=null){c(O.legend.container).html(aL)}else{var aI="",aC=O.legend.position,aD=O.legend.margin;if(aD[0]==null){aD=[aD,aD]}if(aC.charAt(0)=="n"){aI+="top:"+(aD[1]+q.top)+"px;"}else{if(aC.charAt(0)=="s"){aI+="bottom:"+(aD[1]+q.bottom)+"px;"}}if(aC.charAt(1)=="e"){aI+="right:"+(aD[0]+q.right)+"px;"}else{if(aC.charAt(1)=="w"){aI+="left:"+(aD[0]+q.left)+"px;"}}var aK=c('
'+aL.replace('style="','style="position:absolute;'+aI+";")+"
").appendTo(av);if(O.legend.backgroundOpacity!=0){var aG=O.legend.backgroundColor;if(aG==null){aG=O.grid.backgroundColor;if(aG&&typeof aG=="string"){aG=c.color.parse(aG)}else{aG=c.color.extract(aK,"background-color")}aG.a=1;aG=aG.toString()}var aB=aK.children();c('
').prependTo(aK).css("opacity",O.legend.backgroundOpacity)}}}var ab=[],M=null;function K(aI,aG,aD){var aO=O.grid.mouseActiveRadius,a0=aO*aO+1,aY=null,aR=false,aW,aU;for(aW=Q.length-1;aW>=0;--aW){if(!aD(Q[aW])){continue}var aP=Q[aW],aH=aP.xaxis,aF=aP.yaxis,aV=aP.datapoints.points,aT=aP.datapoints.pointsize,aQ=aH.c2p(aI),aN=aF.c2p(aG),aC=aO/aH.scale,aB=aO/aF.scale;if(aH.options.inverseTransform){aC=Number.MAX_VALUE}if(aF.options.inverseTransform){aB=Number.MAX_VALUE}if(aP.lines.show||aP.points.show){for(aU=0;aUaC||aK-aQ<-aC||aJ-aN>aB||aJ-aN<-aB){continue}var aM=Math.abs(aH.p2c(aK)-aI),aL=Math.abs(aF.p2c(aJ)-aG),aS=aM*aM+aL*aL;if(aS=Math.min(aZ,aK)&&aN>=aJ+aE&&aN<=aJ+aX):(aQ>=aK+aE&&aQ<=aK+aX&&aN>=Math.min(aZ,aJ)&&aN<=Math.max(aZ,aJ))){aY=[aW,aU/aT]}}}}if(aY){aW=aY[0];aU=aY[1];aT=Q[aW].datapoints.pointsize;return{datapoint:Q[aW].datapoints.points.slice(aU*aT,(aU+1)*aT),dataIndex:aU,series:Q[aW],seriesIndex:aW}}return null}function aa(aB){if(O.grid.hoverable){u("plothover",aB,function(aC){return aC.hoverable!=false})}}function l(aB){if(O.grid.hoverable){u("plothover",aB,function(aC){return false})}}function R(aB){u("plotclick",aB,function(aC){return aC.clickable!=false})}function u(aC,aB,aD){var aE=y.offset(),aH=aB.pageX-aE.left-q.left,aF=aB.pageY-aE.top-q.top,aJ=C({left:aH,top:aF});aJ.pageX=aB.pageX;aJ.pageY=aB.pageY;var aK=K(aH,aF,aD);if(aK){aK.pageX=parseInt(aK.series.xaxis.p2c(aK.datapoint[0])+aE.left+q.left);aK.pageY=parseInt(aK.series.yaxis.p2c(aK.datapoint[1])+aE.top+q.top)}if(O.grid.autoHighlight){for(var aG=0;aGaH.max||aIaG.max){return}var aF=aE.points.radius+aE.points.lineWidth/2;A.lineWidth=aF;A.strokeStyle=c.color.parse(aE.color).scale("a",0.5).toString();var aB=1.5*aF,aC=aH.p2c(aC),aI=aG.p2c(aI);A.beginPath();if(aE.points.symbol=="circle"){A.arc(aC,aI,aB,0,2*Math.PI,false)}else{aE.points.symbol(A,aC,aI,aB,false)}A.closePath();A.stroke()}function v(aE,aB){A.lineWidth=aE.bars.lineWidth;A.strokeStyle=c.color.parse(aE.color).scale("a",0.5).toString();var aD=c.color.parse(aE.color).scale("a",0.5).toString();var aC=aE.bars.align=="left"?0:-aE.bars.barWidth/2;E(aB[0],aB[1],aB[2]||0,aC,aC+aE.bars.barWidth,0,function(){return aD},aE.xaxis,aE.yaxis,A,aE.bars.horizontal,aE.bars.lineWidth)}function am(aJ,aB,aH,aC){if(typeof aJ=="string"){return aJ}else{var aI=H.createLinearGradient(0,aH,0,aB);for(var aE=0,aD=aJ.colors.length;aE12){n=n-12}else{if(n==0){n=12}}}for(var g=0;g0&&j.which!=m.which)||i(j.target).is(m.not)){return}}switch(j.type){case"mousedown":i.extend(m,i(k).offset(),{elem:k,target:j.target,pageX:j.pageX,pageY:j.pageY});d.add(document,"mousemove mouseup",f,m);g(k,false);h.dragging=null;return false;case !h.dragging&&"mousemove":if(e(j.pageX-m.pageX)+e(j.pageY-m.pageY)w){var A=B;B=w;w=A}var y=w-B;if(E&&((E[0]!=null&&yE[1]))){return}D.min=B;D.max=w});o.setupGrid();o.draw();if(!q.preventEvent){o.getPlaceholder().trigger("plotzoom",[o])}};o.pan=function(p){var q={x:+p.left,y:+p.top};if(isNaN(q.x)){q.x=0}if(isNaN(q.y)){q.y=0}b.each(o.getAxes(),function(s,u){var v=u.options,t,r,w=q[u.direction];t=u.c2p(u.p2c(u.min)+w),r=u.c2p(u.p2c(u.max)+w);var x=v.panRange;if(x===false){return}if(x){if(x[0]!=null&&x[0]>t){w=x[0]-t;t+=w;r+=w}if(x[1]!=null&&x[1] "LAST_MON_TIME", + :id => "ID", + :name => "NAME", + :state => "STATE", + :cluster => "CLUSTER", + :disk_usage => "HOST_SHARE/DISK_USAGE", + :cpu_usage => "HOST_SHARE/CPU_USAGE", + :mem_usage => "HOST_SHARE/MEM_USAGE", + :max_mem => "HOST_SHARE/MAX_MEM", + :max_disk => "HOST_SHARE/MAX_DISK", + :max_cpu => "HOST_SHARE/MAX_CPU", + :free_mem => "HOST_SHARE/FREE_MEM", + :free_disk => "HOST_SHARE/FREE_DISK", + :free_cpu => "HOST_SHARE/FREE_CPU", + :used_disk => "HOST_SHARE/USED_DISK", + :used_mem => "HOST_SHARE/USED_MEM", + :used_cpu => "HOST_SHARE/USED_CPU" + } + + def initialize (log_file_folder,monitoring_elems=HOST_MONITORING_ELEMS) + super log_file_folder,monitoring_elems + end + + def factory(client) + HostPool.new(client) + end + + def active (host_hash) + host_hash[:state].to_i < 3 + end + + def error (host_hash) + host_hash[:state].to_i == 3 + end +end diff --git a/src/sunstone/share/OneMonitor/OneMonitor.rb b/src/sunstone/share/OneMonitor/OneMonitor.rb new file mode 100644 index 0000000000..64f0707c27 --- /dev/null +++ b/src/sunstone/share/OneMonitor/OneMonitor.rb @@ -0,0 +1,114 @@ +# -------------------------------------------------------------------------- # +# 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 'OneMonitorUtils' +include OpenNebula + +class OneMonitor + + OUTPUT_METHOD="CSV" + case OUTPUT_METHOD + when "CSV" then include OneMonitorCSV + end + + def initialize(log_file_folder,monitoring_elems) + # Authenticate in OpenNebula + @client = Client.new + @log_file_folder = log_file_folder + @monitoring_elems = monitoring_elems + @results = [] + reinit_global_results + end + + def results + @results + end + + def snapshot + #init global results + + rc = monitor #calling the extending class method + rc = save if rc + if rc + @results = [] + reinit_global_results + puts "New monitoring snapshots saved." + else + puts "Error saving new snapshot." + end + return rc + end + + def monitor + pool = factory(@client) + rc = pool.info + + if OpenNebula.is_error?(rc) + puts "Error monitoring: #{rc.message}" + return nil + end + + pool.each do | elem | + time = elem[@monitoring_elems[:time]].to_i + + hash = {} + @monitoring_elems.each do | key,value | + hash[key] = elem[value] + end + + #do not log time = 0, it causes + #graphs being drawn from 1970 + + if time > 0 + @results << hash + add_to_global(hash) + end + + @n_active += 1 if active(hash) + @n_error += 1 if error(hash) + @n_total += 1 + end + + end + + def reinit_global_results + @global_results = {} + @monitoring_elems.each do | key,value | + @global_results[key] = 0 + end + @n_active = @n_error = @n_total = 0 + end + + def add_to_global(hash) + hash.each do | key,value | + @global_results[key] += value.to_i + end + time = hash[:time].to_i + @global_results[:time] = time + end + +end diff --git a/src/sunstone/share/OneMonitor/OneMonitorClient.rb b/src/sunstone/share/OneMonitor/OneMonitorClient.rb new file mode 100644 index 0000000000..7f042d4d29 --- /dev/null +++ b/src/sunstone/share/OneMonitor/OneMonitorClient.rb @@ -0,0 +1,35 @@ +require 'OneMonitorClientUtils' + +class OneMonitorClient + + INPUT_METHOD="CSV" + case INPUT_METHOD + when "CSV" then include OneMonitorCSVClient + end + + def initialize(ids, log_file_folder) + #create filenames to read + ids = [ids] unless ids.class == Array + @file_names = {} + ids.each do | id | + @file_names[id] = OneMonitorClient.full_path(log_file_folder,id) + end + return @file_names + end + + def get_multiple_data(columns,length) + result = [] + @file_names.each do | id,file_name | + result << get_data_for_id(id,columns,length) + end + return result + end + + def get_data_for_id(id, columns, length) + readOneMonitorFile(@file_names[id],columns,length) + end + + def self.full_path(folder,id) + "#{folder}/#{id}" + end +end diff --git a/src/sunstone/share/OneMonitor/OneMonitorClientUtils.rb b/src/sunstone/share/OneMonitor/OneMonitorClientUtils.rb new file mode 100644 index 0000000000..0593b3c686 --- /dev/null +++ b/src/sunstone/share/OneMonitor/OneMonitorClientUtils.rb @@ -0,0 +1,40 @@ +module OneMonitorCSVClient + def readOneMonitorFile(file_name,columns,length) + first_line = `head -1 #{file_name}`.chomp + + if $?.exitstatus != 0 + return [] #silently fail, cannot find this file + end + + n_lines = `wc -l #{file_name} | cut -d' ' -f 1`.to_i + if n_lines <= length.to_i + length = n_lines-1 + end + + fields = first_line.split(',') + poll_time_pos = fields.index("time") + + if !poll_time_pos + return [] #silently fail, no timestamp + end + + tail = `tail -#{length} #{file_name}` + series = [] #will hold several graphs + + columns.each do | column_name | + + graph = [] + column_pos = fields.index(column_name) + next unless column_pos + + tail.each_line do | line | + line_arr = line.delete('"').split(',') + graph << [ line_arr[poll_time_pos].to_i*1000, line_arr[column_pos].to_i ] + end + + series << graph + end + + return series + end +end diff --git a/src/sunstone/share/OneMonitor/OneMonitorUtils.rb b/src/sunstone/share/OneMonitor/OneMonitorUtils.rb new file mode 100644 index 0000000000..b512887881 --- /dev/null +++ b/src/sunstone/share/OneMonitor/OneMonitorUtils.rb @@ -0,0 +1,93 @@ +# -------------------------------------------------------------------------- # +# 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. # +#--------------------------------------------------------------------------- # + +module OneMonitorCSV + + def save + rc = save_csv + save_global_csv if rc + end + + def save_csv(separator=",") + + @results.each do | mon_hash | + id = mon_hash[:id] + log_name = "#{@log_file_folder}/#{id}" + + begin + log_file = File.new(log_name,'a') + + if !File.size?(log_name) + header = csv_header + log_file.puts(header) + end + + line = hash_to_csv(mon_hash) + log_file.puts(line) + log_file.close + rescue Exception => e + puts e.message + puts "Error writing log" + return nil + end + end + end + + def save_global_csv + begin + + global_log_file = "#{@log_file_folder}/global" + global_file = File.new(global_log_file,'a') + + if !File.size?(global_log_file) + then + header = csv_header+",active,error,total" + global_file.puts(header) + end + + csv = hash_to_csv(@global_results)+%&,"#{@n_active}","#{@n_error}","#{@n_total}"& + global_file.puts(csv) + global_file.close + return 0 + rescue Exception => e + puts e.message + puts "Error writing global results" + return nil + end + + + end + + def hash_to_csv hash,separator="," + csv_line = "" + #we need to respect the order of monitoring elems + #keys, which might not be the same in hash + @monitoring_elems.each do | key, value | + csv_line += %&"#{hash[key]}"#{separator}& + end + csv_line.chop! unless csv_line.empty? + end + + def csv_header separator="," + str = "" + @monitoring_elems.each do | key,value | + str += "#{key}," + end + #remove final separator + str.chop! unless str.empty? + end + +end diff --git a/src/sunstone/share/OneMonitor/VMMonitor.rb b/src/sunstone/share/OneMonitor/VMMonitor.rb new file mode 100644 index 0000000000..e9e0a29de3 --- /dev/null +++ b/src/sunstone/share/OneMonitor/VMMonitor.rb @@ -0,0 +1,48 @@ +# -------------------------------------------------------------------------- # +# 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 'OneMonitor' + +class VMMonitor < OneMonitor + + VM_MONITORING_ELEMS = { + :time => "LAST_POLL", + :id => "ID", + :name => "NAME", + :lcm_state => "LCM_STATE", + :state => "STATE", + :memory => "MEMORY", + :cpu => "CPU", + :net_tx => "NET_TX", + :net_rx => "NET_RX" + } + + def initialize (log_file_folder,monitoring_elems=VM_MONITORING_ELEMS) + super log_file_folder,monitoring_elems + end + + def factory(client) + VirtualMachinePool.new(client) + end + + def active (vm_hash) + vm_hash[:state].to_i == 3 + end + + def error (vm_hash) + vm_hash[:state].to_i == 7 + end +end diff --git a/src/sunstone/share/OneMonitor/runOneMonitor.rb b/src/sunstone/share/OneMonitor/runOneMonitor.rb new file mode 100755 index 0000000000..48818a852c --- /dev/null +++ b/src/sunstone/share/OneMonitor/runOneMonitor.rb @@ -0,0 +1,41 @@ +#!/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. # +#--------------------------------------------------------------------------- # + +$: << File.dirname(__FILE__) + +require 'HostMonitor.rb' +require 'VMMonitor.rb' + +DEFAULT_INTERVAL= 600 #secs +DEFAULT_HOST_LOG_FOLDER = "#{ENV['ONE_LOCATION']}/logs/host/" +DEFAULT_VM_LOG_FOLDER = "#{ENV['ONE_LOCATION']}/logs/vm/" + + +#ARG0=interval, ARG1=hostfolder, ARG2=vmfolder +MONITOR_INTERVAL= ARGV[0]? ARGV[0].to_i : DEFAULT_INTERVAL #secs +HOST_LOG_FOLDER= ARGV[1]? ARGV[1]: DEFAULT_HOST_LOG_FOLDER +VM_LOG_FOLDER=ARGV[2] ? ARGV[2] : DEFAULT_VM_LOG_FOLDER + +hostm = HostMonitor.new(HOST_LOG_FOLDER) +vmm = VMMonitor.new(VM_LOG_FOLDER) + +while true do + hostm.snapshot + vmm.snapshot + sleep MONITOR_INTERVAL +end diff --git a/src/sunstone/sunstone-server.rb b/src/sunstone/sunstone-server.rb index b614b24bfa..0ac9d9bc06 100755 --- a/src/sunstone/sunstone-server.rb +++ b/src/sunstone/sunstone-server.rb @@ -1,4 +1,5 @@ #!/usr/bin/env ruby +# -*- coding: utf-8 -*- # -------------------------------------------------------------------------- # # Copyright 2002-2011, OpenNebula Project Leads (OpenNebula.org) # @@ -30,8 +31,12 @@ else CONFIGURATION_FILE = ONE_LOCATION+"/etc/sunstone-server.conf" end +HOST_LOG_FOLDER = LOG_LOCATION+"/OneMonitor/host" +VM_LOG_FOLDER = LOG_LOCATION+"/OneMonitor/vm" + $: << RUBY_LIB_LOCATION $: << File.dirname(__FILE__)+'/models' +$: << File.dirname(__FILE__)+'/share/OneMonitor' ############################################################################## # Required libraries @@ -90,6 +95,7 @@ helpers do session.clear return [204, ""] end + end before do @@ -155,6 +161,19 @@ get '/vm/:id/log' do @SunstoneServer.get_vm_log(params[:id]) end +############################################################################## +# Logs +############################################################################## + +get '/:resource/monitor' do + @SunstoneServer.get_log(params) +end + +get '/:resource/:id/monitor' do + @SunstoneServer.get_log(params) +end + + ############################################################################## # GET Pool information ############################################################################## @@ -239,4 +258,3 @@ end post '/:resource/:id/action' do @SunstoneServer.perform_action(params[:resource], params[:id], request.body.read) end - diff --git a/src/sunstone/templates/index.html b/src/sunstone/templates/index.html index 37560374d2..65d614820b 100644 --- a/src/sunstone/templates/index.html +++ b/src/sunstone/templates/index.html @@ -16,7 +16,7 @@ - + @@ -69,6 +69,9 @@
+
+
+
diff --git a/src/test/Nebula.cc b/src/test/Nebula.cc index 1324dff46e..4fb6df495c 100644 --- a/src/test/Nebula.cc +++ b/src/test/Nebula.cc @@ -77,16 +77,16 @@ void Nebula::start() delete ipool; } - if ( cpool != 0) - { - delete cpool; - } - if ( tpool != 0) { delete tpool; } + if ( gpool != 0) + { + delete gpool; + } + if ( vmm != 0) { delete vmm; @@ -122,6 +122,11 @@ void Nebula::start() delete hm; } + if ( imagem != 0 ) + { + delete imagem; + } + if ( authm != 0) { delete authm; @@ -165,12 +170,14 @@ void Nebula::start() NebulaLog::log("ONE",Log::INFO,"Bootstraping OpenNebula database."); + bootstrap(); VirtualMachinePool::bootstrap(db); HostPool::bootstrap(db); VirtualNetworkPool::bootstrap(db); UserPool::bootstrap(db); ImagePool::bootstrap(db); - ClusterPool::bootstrap(db); + VMTemplatePool::bootstrap(db); + GroupPool::bootstrap(db); } catch (exception&) { @@ -183,8 +190,8 @@ void Nebula::start() { string mac_prefix = "00:00"; int size = 1; - string default_image_type; - string default_device_prefix; + string default_image_type = "OS"; + string default_device_prefix = "hd"; if (tester->need_vm_pool) { @@ -201,6 +208,11 @@ void Nebula::start() vnpool = tester->create_vnpool(db,mac_prefix,size); } + if (tester->need_group_pool) + { + gpool = tester->create_gpool(db); + } + if (tester->need_user_pool) { upool = tester->create_upool(db); @@ -213,11 +225,6 @@ void Nebula::start() default_device_prefix); } - if (tester->need_cluster_pool) - { - cpool = tester->create_cpool(db); - } - if (tester->need_template_pool) { tpool = tester->create_tpool(db); @@ -366,8 +373,7 @@ void Nebula::start() { try { - rm = tester->create_rm(vmpool,hpool,vnpool,upool,ipool,cpool,tpool, - log_location + "one_xmlrpc.log"); + rm = tester->create_rm(log_location + "one_xmlrpc.log"); } catch (bad_alloc&) { @@ -432,7 +438,7 @@ void Nebula::start() } } - // ---- Auth Manager ---- + // ---- Image Manager ---- if (tester->need_imagem) { try @@ -481,8 +487,25 @@ void Nebula::start() hm->load_mads(0); } + if( imagem != 0 ) + { + imagem->load_mads(0); + } + if( authm != 0 ) { authm->load_mads(0); } }; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void Nebula::bootstrap() +{ + ostringstream oss; + + oss << "CREATE TABLE pool_control (tablename VARCHAR(32) PRIMARY KEY, " + "last_oid BIGINT UNSIGNED)"; + db->exec(oss); +} diff --git a/src/test/NebulaTest.cc b/src/test/NebulaTest.cc index c0a6b04808..f50cda3339 100644 --- a/src/test/NebulaTest.cc +++ b/src/test/NebulaTest.cc @@ -47,16 +47,16 @@ ImagePool* NebulaTest::create_ipool( SqlDB* db, return new ImagePool(db,default_image_type,default_device_prefix); } -ClusterPool* NebulaTest::create_cpool(SqlDB* db) -{ - return new ClusterPool(db); -} - VMTemplatePool* NebulaTest::create_tpool(SqlDB* db) { return new VMTemplatePool(db); } +GroupPool* NebulaTest::create_gpool(SqlDB* db) +{ + return new GroupPool(db); +} + // ----------------------------------------------------------- // Managers // ----------------------------------------------------------- @@ -108,27 +108,11 @@ DispatchManager* NebulaTest::create_dm(VirtualMachinePool* vmpool, return new DispatchManager(vmpool, hpool); } -RequestManager* NebulaTest::create_rm( - VirtualMachinePool * vmpool, - HostPool * hpool, - VirtualNetworkPool * vnpool, - UserPool * upool, - ImagePool * ipool, - ClusterPool * cpool, - VMTemplatePool * tpool, - string log_file) +RequestManager* NebulaTest::create_rm(string log_file) { int rm_port = 2633; - return new RequestManager(vmpool, - hpool, - vnpool, - upool, - ipool, - cpool, - tpool, - rm_port, - log_file); + return new RequestManager(rm_port, log_file); } HookManager* NebulaTest::create_hm(VirtualMachinePool * vmpool) @@ -137,8 +121,12 @@ HookManager* NebulaTest::create_hm(VirtualMachinePool * vmpool) VectorAttribute * mad; vector hm_mads; + ostringstream oss; - mad_value.insert(make_pair("executable","one_hm")); + // we need the full path (i.e, starting with '/') + // for the dummy executable + oss << getenv("PWD") << "/../../hm_mad/test/dummy"; + mad_value.insert(make_pair("EXECUTABLE",oss.str())); mad = new VectorAttribute("HM_MAD",mad_value); hm_mads.push_back(mad); @@ -157,10 +145,14 @@ ImageManager* NebulaTest::create_imagem(ImagePool * ipool) VectorAttribute * mad; vector im_mads; + ostringstream oss; - mad_value.insert(make_pair("executable","one_image")); + // we need the full path (i.e, starting with '/') + // for the dummy executable + oss << getenv("PWD") << "/../../mad/test/dummy"; + mad_value.insert(make_pair("EXECUTABLE",oss.str())); - mad = new VectorAttribute("HM_MAD",mad_value); + mad = new VectorAttribute("IMAGE_MAD",mad_value); im_mads.push_back(mad); return new ImageManager(ipool,im_mads); diff --git a/src/um/User.cc b/src/um/User.cc index d3c49c407c..3dd668b573 100644 --- a/src/um/User.cc +++ b/src/um/User.cc @@ -23,16 +23,9 @@ #include #include "User.h" +#include "Nebula.h" +#include "Group.h" -/* ************************************************************************** */ -/* User :: Constructor/Destructor */ -/* ************************************************************************** */ - -User::User(int id, string name, string pass, bool _enabled): - PoolObjectSQL(id,name,-1,table), password(pass), enabled(_enabled) - {}; - -User::~User(){}; /* ************************************************************************** */ /* User :: Database Access Functions */ @@ -124,30 +117,23 @@ error_username: /* User :: Misc */ /* ************************************************************************** */ -ostream& operator<<(ostream& os, User& user) -{ - string user_str; - - os << user.to_xml(user_str); - - return os; -}; - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - string& User::to_xml(string& xml) const { ostringstream oss; + string collection_xml; int enabled_int = enabled?1:0; + ObjectCollection::to_xml(collection_xml); + oss << "" "" << oid <<"" << + "" << gid <<"" << "" << name <<"" << "" << password <<"" << "" << enabled_int <<"" << + collection_xml << ""; xml = oss.str(); @@ -162,17 +148,31 @@ int User::from_xml(const string& xml) { int rc = 0; int int_enabled; + vector content; // Initialize the internal XML object update_from_str(xml); rc += xpath(oid, "/USER/ID", -1); + rc += xpath(gid, "/USER/GID", -1); rc += xpath(name, "/USER/NAME", "not_found"); rc += xpath(password, "/USER/PASSWORD", "not_found"); rc += xpath(int_enabled, "/USER/ENABLED", 0); enabled = int_enabled; + // Get associated classes + ObjectXML::get_nodes("/USER/GROUPS", content); + + if( content.size() < 1 ) + { + return -1; + } + + // Set of IDs + rc += ObjectCollection::from_xml_node(content[0]); + + if (rc != 0) { return -1; diff --git a/src/um/UserPool.cc b/src/um/UserPool.cc index 6985e6222b..ae896b742b 100644 --- a/src/um/UserPool.cc +++ b/src/um/UserPool.cc @@ -88,7 +88,8 @@ UserPool::UserPool(SqlDB * db):PoolSQL(db,User::table) string error_str; string sha1_pass = SSLTools::sha1_digest(one_pass); - allocate(&one_uid, one_name, sha1_pass, true, error_str); + allocate(&one_uid,GroupPool::ONEADMIN_ID,one_name,sha1_pass, + true, error_str); } else { @@ -115,13 +116,19 @@ UserPool::UserPool(SqlDB * db):PoolSQL(db,User::table) int UserPool::allocate ( int * oid, + int gid, string username, string password, bool enabled, string& error_str) { - User * user; - ostringstream oss; + Nebula& nd = Nebula::instance(); + + User * user; + GroupPool * gpool; + Group * group; + + ostringstream oss; if ( username.empty() ) { @@ -136,13 +143,34 @@ int UserPool::allocate ( } // Build a new User object - user = new User(-1, username, password, enabled); + user = new User(-1, gid, username, password, enabled); + + user->add_collection_id(gid); //Adds the primary group to the collection // Insert the Object in the pool *oid = PoolSQL::allocate(user, error_str); - return *oid; + if ( *oid < 0 ) + { + return *oid; + } + // Adds User to group + gpool = nd.get_gpool(); + group = gpool->get(gid, true); + + if( group == 0 ) + { + return -1; + } + + group->add_user(*oid); + + gpool->update(group); + + group->unlock(); + + return *oid; error_name: oss << "NAME cannot be empty."; @@ -150,6 +178,7 @@ error_name: error_duplicated: oss << "NAME is already taken by USER " << user->get_oid() << "."; + goto error_common; error_common: *oid = -1; @@ -161,21 +190,25 @@ error_common: /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -int UserPool::authenticate(string& session) +bool UserPool::authenticate(const string& session, int& user_id, int& group_id) { map::iterator index; User * user = 0; string username; string secret, u_pass; - int uid; - int user_id = -1; - int rc; + int uid, gid; + int rc; + bool result; Nebula& nd = Nebula::instance(); AuthManager * authm = nd.get_authm(); + user_id = -1; + group_id = -1; + result = false; + rc = User::split_secret(session,username,secret); if ( rc != 0 ) @@ -189,6 +222,7 @@ int UserPool::authenticate(string& session) { u_pass = user->password; uid = user->oid; + gid = user->gid; user->unlock(); } @@ -196,6 +230,7 @@ int UserPool::authenticate(string& session) { u_pass = "-"; uid = -1; + gid = -1; } AuthRequest ar(uid); @@ -206,14 +241,18 @@ int UserPool::authenticate(string& session) { if (ar.plain_authenticate()) { - user_id = 0; + user_id = 0; + group_id = GroupPool::ONEADMIN_ID; + result = true; } } else if (authm == 0) //plain auth { if ( user != 0 && ar.plain_authenticate()) //no plain for external users { - user_id = uid; + user_id = uid; + group_id = gid; + result = true; } } else //use the driver @@ -225,7 +264,9 @@ int UserPool::authenticate(string& session) { if ( user != 0 ) //knwon user_id { - user_id = uid; + user_id = uid; + group_id = gid; + result = true; } else //External user, username & pass in driver message { @@ -242,7 +283,12 @@ int UserPool::authenticate(string& session) if ( !is.fail() ) { - allocate(&user_id,mad_name,mad_pass,true,error_str); + allocate(&user_id, + GroupPool::USERS_ID, + mad_name, + mad_pass, + true, + error_str); } if ( user_id == -1 ) @@ -253,12 +299,15 @@ int UserPool::authenticate(string& session) ". Driver response: " << ar.message; ar.message = oss.str(); - user_id = -1; + } + else + { + group_id = GroupPool::USERS_ID; + result = true; } } } - - if (user_id == -1) + else { ostringstream oss; oss << "Auth Error: " << ar.message; @@ -267,7 +316,7 @@ int UserPool::authenticate(string& session) } } - return user_id; + return result; } /* -------------------------------------------------------------------------- */ diff --git a/src/um/test/SConstruct b/src/um/test/SConstruct index 042bc45c2f..a766dc55aa 100644 --- a/src/um/test/SConstruct +++ b/src/um/test/SConstruct @@ -17,15 +17,38 @@ Import('env') env.Prepend(LIBS=[ - 'nebula_um', + 'nebula_host', 'nebula_pool', + 'nebula_template', 'nebula_xml', 'nebula_log', + 'nebula_common', + 'nebula_sql', + +### TODO: delete not needed + 'nebula_core_test', + 'nebula_host', + 'nebula_xml', + 'nebula_vmm', + 'nebula_im', + 'nebula_rm', + 'nebula_tm', + 'nebula_um', + 'nebula_mad', + 'nebula_template', + 'nebula_vm', + 'nebula_vmtemplate', + 'nebula_group', + 'nebula_vnm', + 'nebula_image', + 'nebula_pool', + 'nebula_hm', 'nebula_authm', 'nebula_common', - 'nebula_mad', - 'nebula_core', + 'nebula_lcm', + 'nebula_dm', 'nebula_sql', + 'nebula_log', 'crypto' ]) diff --git a/src/um/test/UserPoolTest.cc b/src/um/test/UserPoolTest.cc index 238a557e4d..c90dd971cb 100644 --- a/src/um/test/UserPoolTest.cc +++ b/src/um/test/UserPoolTest.cc @@ -31,26 +31,24 @@ const string usernames[] = { "A user", "B user", "C user", "D user", "E user" }; const string passwords[] = { "A pass", "B pass", "C pass", "D pass", "E pass" }; const string dump_result = - "0one_user_test" - "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8" - "11a" - "p1" - "2a namepass" - "13a_name" - "password1" - "4another namesecret" - "15user" - "12341" - ""; + "00one_user_test5baa61e4c9b93f3f0682250b6cf8331b7ee68fd81010ap1020a namepass1030a_namepassword1040another namesecret1050user123410"; const string dump_where_result = - "1a" - "p1" - "2a namepass" - "13a_name" - "password1" - "4another namesecret" - "1"; + "10ap1020a namepass1030a_namepassword1040another namesecret10"; + +#include "NebulaTest.h" + +class NebulaTestUser: public NebulaTest +{ +public: + NebulaTestUser():NebulaTest() + { + NebulaTest::the_tester = this; + + need_group_pool = true; + need_user_pool = true; + } +}; class UserPoolTest : public PoolTest { @@ -78,14 +76,20 @@ class UserPoolTest : public PoolTest protected: + NebulaTestUser * tester; + UserPool * upool; + GroupPool * gpool; + + void bootstrap(SqlDB* db) { - UserPool::bootstrap(db); + // setUp overwritten }; PoolSQL* create_pool(SqlDB* db) { - return new UserPool(db); + // setUp overwritten + return upool; }; int allocate(int index) @@ -93,7 +97,7 @@ protected: int oid; string err; - return ((UserPool*)pool)->allocate(&oid, usernames[index], + return ((UserPool*)pool)->allocate(&oid, 0, usernames[index], passwords[index], true, err); }; @@ -112,6 +116,28 @@ public: ~UserPoolTest(){xmlCleanupParser();}; + void setUp() + { + create_db(); + + tester = new NebulaTestUser(); + + Nebula& neb = Nebula::instance(); + neb.start(); + + upool = neb.get_upool(); + gpool = neb.get_gpool(); + + pool = upool; + }; + + void tearDown() + { + delete_db(); + + delete tester; + }; + /* ********************************************************************* */ /* ********************************************************************* */ @@ -158,20 +184,30 @@ public: void authenticate() { UserPool* user_pool = (UserPool*) pool; + + bool rc; + int oid, gid; + // There is an initial user, created with the one_auth file: // one_user_test:password string session="one_user_test:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"; - int oid = user_pool->authenticate( session ); + rc = user_pool->authenticate( session, oid, gid ); + CPPUNIT_ASSERT( rc == true ); + CPPUNIT_ASSERT( oid == 0 ); CPPUNIT_ASSERT( oid == 0 ); session = "one_user_test:wrong_password"; - oid = user_pool->authenticate( session ); + rc = user_pool->authenticate( session, oid, gid ); + CPPUNIT_ASSERT( rc == false ); CPPUNIT_ASSERT( oid == -1 ); + CPPUNIT_ASSERT( gid == -1 ); session = "unknown_user:5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"; - oid = user_pool->authenticate( session ); + rc = user_pool->authenticate( session, oid, gid ); + CPPUNIT_ASSERT( rc == false ); CPPUNIT_ASSERT( oid == -1 ); + CPPUNIT_ASSERT( gid == -1 ); } void get_using_name() @@ -257,17 +293,17 @@ public: UserPool * up = static_cast(pool); // Allocate a user. - rc = up->allocate(&oid, usernames[0], passwords[0], true, err); + rc = up->allocate(&oid, 0,usernames[0], passwords[0], true, err); CPPUNIT_ASSERT( oid == 1 ); CPPUNIT_ASSERT( oid == rc ); // Try to allocate twice the same user, should fail - rc = up->allocate(&oid, usernames[0], passwords[0], true, err); + rc = up->allocate(&oid, 0,usernames[0], passwords[0], true, err); CPPUNIT_ASSERT( rc == -1 ); CPPUNIT_ASSERT( oid == rc ); // Try again, with different password - rc = up->allocate(&oid, usernames[0], passwords[1], true, err); + rc = up->allocate(&oid, 0, usernames[0], passwords[1], true, err); CPPUNIT_ASSERT( rc == -1 ); CPPUNIT_ASSERT( oid == rc ); } @@ -282,7 +318,7 @@ public: for(int i=0; i<5; i++) { - ((UserPool*)pool)->allocate(&oid, d_names[i], d_pass[i], true, err); + ((UserPool*)pool)->allocate(&oid, 0, d_names[i], d_pass[i], true, err); } ostringstream oss; @@ -309,7 +345,7 @@ public: for(int i=0; i<5; i++) { - ((UserPool*)pool)->allocate(&oid, d_names[i], d_pass[i], true, err); + ((UserPool*)pool)->allocate(&oid, 0, d_names[i], d_pass[i], true, err); } // Note: second parameter of dump is the WHERE constraint. The "order diff --git a/src/vm/VirtualMachine.cc b/src/vm/VirtualMachine.cc index 83b0af12d2..261c15d35f 100644 --- a/src/vm/VirtualMachine.cc +++ b/src/vm/VirtualMachine.cc @@ -25,6 +25,7 @@ #include "VirtualMachine.h" #include "VirtualNetworkPool.h" +#include "ImagePool.h" #include "NebulaLog.h" #include "Nebula.h" @@ -38,10 +39,9 @@ VirtualMachine::VirtualMachine(int id, int _uid, - string _user_name, + int _gid, VirtualMachineTemplate * _vm_template): - PoolObjectSQL(id,"",_uid,table), - user_name(_user_name), + PoolObjectSQL(id,"",_uid,_gid,table), last_poll(0), state(INIT), lcm_state(LCM_INIT), @@ -96,11 +96,11 @@ VirtualMachine::~VirtualMachine() const char * VirtualMachine::table = "vm_pool"; const char * VirtualMachine::db_names = - "oid, name, body, uid, last_poll, state, lcm_state"; + "oid, name, body, uid, gid, last_poll, state, lcm_state"; const char * VirtualMachine::db_bootstrap = "CREATE TABLE IF NOT EXISTS " "vm_pool (oid INTEGER PRIMARY KEY, name TEXT, body TEXT, uid INTEGER, " - "last_poll INTEGER, state INTEGER, lcm_state INTEGER)"; + "gid INTEGER, last_poll INTEGER, state INTEGER, lcm_state INTEGER)"; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -516,6 +516,7 @@ int VirtualMachine::insert_replace(SqlDB *db, bool replace) << "'" << sql_name << "'," << "'" << sql_xml << "'," << uid << "," + << gid << "," << last_poll << "," << state << "," << lcm_state << ")"; @@ -987,6 +988,11 @@ int VirtualMachine::save_disk(int disk_id, int img_id, string& error_str) goto error_saved; } + if(!((disk->vector_value("PERSISTENT")).empty())) + { + goto error_persistent; + } + disk->replace("SAVE", "YES"); oss << (img_id); @@ -998,8 +1004,12 @@ int VirtualMachine::save_disk(int disk_id, int img_id, string& error_str) goto error_not_found; +error_persistent: + oss << "Source image for DISK " << disk_id << " is persistent."; + goto error_common; + error_saved: - oss << "The DISK " << disk_id << " is already suppossed to be saved."; + oss << "The DISK " << disk_id << " is already going to be saved."; goto error_common; error_not_found: @@ -1015,6 +1025,54 @@ error_common: /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ +void VirtualMachine::set_auth_request(int uid, + AuthRequest& ar, + VirtualMachineTemplate *tmpl) +{ + int num; + vector vectors; + VectorAttribute * vector; + + Nebula& nd = Nebula::instance(); + + ImagePool * ipool = nd.get_ipool(); + VirtualNetworkPool * vnpool = nd.get_vnpool(); + + num = tmpl->get("DISK",vectors); + + for(int i=0; i(vectors[i]); + + if ( vector == 0 ) + { + continue; + } + + ipool->authorize_disk(vector,uid,&ar); + } + + vectors.clear(); + + num = tmpl->get("NIC",vectors); + + for(int i=0; i(vectors[i]); + + if ( vector == 0 ) + { + continue; + } + + vnpool->authorize_nic(vector,uid,&ar); + } +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + pthread_mutex_t VirtualMachine::lex_mutex = PTHREAD_MUTEX_INITIALIZER; extern "C" @@ -1084,17 +1142,6 @@ error_yy: /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -ostream& operator<<(ostream& os, const VirtualMachine& vm) -{ - string vm_str; - - os << vm.to_xml(vm_str); - - return os; -}; - -/* -------------------------------------------------------------------------- */ - string& VirtualMachine::to_xml(string& xml) const { @@ -1106,7 +1153,7 @@ string& VirtualMachine::to_xml(string& xml) const oss << "" << "" << oid << "" << "" << uid << "" - << "" << user_name << "" + << "" << gid << "" << "" << name << "" << "" << last_poll << "" << "" << state << "" @@ -1132,6 +1179,9 @@ string& VirtualMachine::to_xml(string& xml) const return xml; } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + int VirtualMachine::from_xml(const string &xml_str) { vector content; @@ -1146,7 +1196,7 @@ int VirtualMachine::from_xml(const string &xml_str) // Get class base attributes rc += xpath(oid, "/VM/ID", -1); rc += xpath(uid, "/VM/UID", -1); - rc += xpath(user_name, "/VM/USERNAME", "not_found"); + rc += xpath(gid, "/VM/GID", -1); rc += xpath(name, "/VM/NAME", "not_found"); rc += xpath(last_poll, "/VM/LAST_POLL",0); diff --git a/src/vm/VirtualMachinePool.cc b/src/vm/VirtualMachinePool.cc index bd8006f8f1..51422eee44 100644 --- a/src/vm/VirtualMachinePool.cc +++ b/src/vm/VirtualMachinePool.cc @@ -167,7 +167,7 @@ VirtualMachinePool::VirtualMachinePool(SqlDB * db, int VirtualMachinePool::allocate ( int uid, - string user_name, + int gid, VirtualMachineTemplate * vm_template, int * oid, string& error_str, @@ -178,7 +178,7 @@ int VirtualMachinePool::allocate ( // ------------------------------------------------------------------------ // Build a new Virtual Machine object // ------------------------------------------------------------------------ - vm = new VirtualMachine(-1, uid, user_name, vm_template); + vm = new VirtualMachine(-1, uid, gid, vm_template); if (on_hold == true) { diff --git a/src/vm/test/VirtualMachinePoolTest.cc b/src/vm/test/VirtualMachinePoolTest.cc index a1c7e7010e..aeb53b41b7 100644 --- a/src/vm/test/VirtualMachinePoolTest.cc +++ b/src/vm/test/VirtualMachinePoolTest.cc @@ -25,7 +25,6 @@ using namespace std; const int uids[] = {123, 261, 123}; -const string user_names[] = {"A user","B user","C user"}; const string names[] = {"VM one", "Second VM", "VM one"}; @@ -47,21 +46,21 @@ const string templates[] = const string xmls[] = { - "0123A userVM one001231VM one010000000000000000", - "1261B userSecond VM0" + "12611Second VM0" "1000000000000<" "/ETIME>0000", - "0123A userVM one001231VM one010000000000000000