diff --git a/SConstruct b/SConstruct index 7557aea8e2..d27c7599e5 100644 --- a/SConstruct +++ b/SConstruct @@ -57,6 +57,7 @@ main_env.Append(LIBPATH=[ cwd+'/src/vnm', cwd+'/src/hm', cwd+'/src/um', + cwd+'/src/authm', ]) # Compile flags @@ -161,6 +162,7 @@ build_scripts=[ 'src/vnm/SConstruct', 'src/hm/SConstruct', 'src/um/SConstruct', + 'src/authm/SConstruct', ] for script in build_scripts: diff --git a/include/AuthManager.h b/include/AuthManager.h new file mode 100644 index 0000000000..d29a163560 --- /dev/null +++ b/include/AuthManager.h @@ -0,0 +1,469 @@ +/* -------------------------------------------------------------------------- */ +/* 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. */ +/* -------------------------------------------------------------------------- */ + +#ifndef AUTH_MANAGER_H_ +#define AUTH_MANAGER_H_ + +#include + +#include "MadManager.h" +#include "ActionManager.h" + +#include "AuthManagerDriver.h" + +using namespace std; + +//Forward definition of the AuthRequest +class AuthRequest; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +extern "C" void * authm_action_loop(void *arg); + +class AuthManager : public MadManager, public ActionListener +{ +public: + + AuthManager( + time_t timer, + time_t __time_out, + vector& _mads): + MadManager(_mads), timer_period(timer) + { + _time_out = __time_out; + + am.addListener(this); + + pthread_mutex_init(&mutex,0); + }; + + ~AuthManager(){}; + + enum Actions + { + AUTHENTICATE, + AUTHORIZE, + FINALIZE + }; + + /** + * Triggers specific actions to the Auth Manager. This function + * wraps the ActionManager trigger function. + * @param action the Auth Manager action + * @param request an auth request + */ + void trigger( + Actions action, + AuthRequest * request); + + /** + * This functions starts the associated listener thread, and creates a + * new thread for the AuthManager. This thread will wait in + * an action loop till it receives ACTION_FINALIZE. + * @return 0 on success. + */ + int start(); + + /** + * Loads Virtual Machine Manager Mads defined in configuration file + * @param uid of the user executing the driver. When uid is 0 the nebula + * identity will be used. Otherwise the Mad will be loaded through the + * sudo application. + */ + void load_mads(int uid); + + /** + * Gets the thread identification. + * @return pthread_t for the manager thread (that in the action loop). + */ + pthread_t get_thread_id() const + { + return authm_thread; + }; + + /** + * Notify the result of an auth request + */ + void notify_request(int auth_id, bool result, const string& message); + + /** + * Discards a pending request. Call this before freeing not notified or + * timeout requests. + */ + void discard_request(int auth_id) + { + lock(); + + auth_requests.erase(auth_id); + + unlock(); + } + + /** + * Gets default timeout for Auth requests + */ + static time_t time_out() + { + return _time_out; + } + +private: + /** + * Thread id for the Transfer Manager + */ + pthread_t authm_thread; + + /** + * Action engine for the Manager + */ + ActionManager am; + + /** + * List of pending requests + */ + map auth_requests; + + /** + * Mutex to access the auth_requests + */ + pthread_mutex_t mutex; + + /** + * Default timeout for Auth requests + */ + static time_t _time_out; + + /** + * Timer for the Manager (periocally triggers timer action) + */ + time_t timer_period; + + /** + * Generic name for the Auth driver + */ + static const char * auth_driver_name; + + /** + * Returns a pointer to a Auth Manager driver. + * @param name of an attribute of the driver (e.g. its type) + * @param value of the attribute + * @return the Auth driver with attribute name equal to value + * or 0 in not found + */ + const AuthManagerDriver * get( + const string& name, + const string& value) + { + return static_cast + (MadManager::get(0,name,value)); + }; + + /** + * Returns a pointer to a Auth Manager driver. The driver is + * searched by its name. + * @param name the name of the driver + * @return the TM driver owned by uid with attribute name equal to value + * or 0 in not found + */ + const AuthManagerDriver * get() + { + string name("NAME"); + + return static_cast + (MadManager::get(0,name,auth_driver_name)); + }; + + /** + * Function to execute the Manager action loop method within a new pthread + * (requires C linkage) + */ + friend void * authm_action_loop(void *arg); + + /** + * The action function executed when an action is triggered. + * @param action the name of the action + * @param arg arguments for the action function + */ + void do_action( + const string & action, + void * arg); + + /** + * This function authenticates a user + */ + void authenticate_action(AuthRequest * ar); + + /** + * This function authorizes a user request + */ + void authorize_action(AuthRequest * ar); + + /** + * This function is periodically executed to check time_outs on requests + */ + void timer_action(); + + /** + * Function to lock the pool + */ + void lock() + { + pthread_mutex_lock(&mutex); + }; + + /** + * Function to unlock the pool + */ + void unlock() + { + pthread_mutex_unlock(&mutex); + }; + + /** + * Add a new request to the Request map + * @param ar pointer to the AuthRequest + * @return the id for the request + */ + int add_request(AuthRequest *ar); + + /** + * Gets request from the Request map + * @param id for the request + * @return pointer to the AuthRequest + */ + AuthRequest * get_request(int id); +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +/** + * The AuthRequest class is used to pass an Authorization or Authentication + * request to the AuthManager. The result of the request will be stored + * in the result and message attributes of this class. + */ +class AuthRequest : public ActionListener +{ +public: + AuthRequest(int _uid): + result(false), + timeout(false), + uid(_uid), + time_out(0), + self_authorize(true) + { + am.addListener(this); + }; + + ~AuthRequest(){}; + + /** + * Authorization Request Type + */ + enum Operation + { + CREATE, /** Authorization to create an object (host, vm, net, image)*/ + DELETE, /** Authorization to delete an object */ + USE, /** Authorization to use an object */ + MANAGE, /** Authorization to manage an object */ + INFO /** Authorization to view an object */ + }; + + /** + * OpenNebula objects to perform an Operation + */ + enum Object + { + VM, + HOST, + NET, + IMAGE, + USER, + CLUSTER + }; + + /** + * Sets the challenge to authenticate an user + * @param challenge a driver specific authentication challenge + */ + void add_authenticate(const string &_username, + const string &_password, + const string &_session) + { + username = _username; + password = _password; + session = _session; + } + + /** + * Adds a new authorization item to this request + * + * OBJECT:OBJECT_ID:ACTION:OWNER:PUBLIC + * + * @param ob the object over which the operation will be performed + * @param ob_id the object unique id + * @param op the operation to be authorized + * @param owner id of user that owns the object. For creates MUST equals + uid, hosts owner is uid=0 + * @param pub public attribute + */ + void add_auth(Object ob, + const string& ob_id, + Operation op, + int owner, + bool pub); + + /** + * Adds a new authorization item to this requests + */ + void add_auth(Object ob, + int ob_id, + Operation op, + int owner, + bool pub) + { + ostringstream oss; + oss << ob_id; + + add_auth(ob,oss.str(),op,owner,pub); + }; + + /** + * Gets the authorization requests in a single string + * @return a space separated list of auth requests. + */ + string get_auths() + { + ostringstream oss; + + for (unsigned int i=0; i auths; + + /** + * Plain authorization for the request + */ + bool self_authorize; + + /** + * No actions defined for the Auth request, just FINALIZE when done + */ + void do_action(const string &name, void *args){}; + + /** + * Base 64 encoding + * @param in the string to encoded + * @return a pointer to the encoded string (must be freed) or 0 in case of + * error + */ + static string * base64_encode(const string& in); + +}; + +#endif /*AUTH_MANAGER_H*/ + diff --git a/include/AuthManagerDriver.h b/include/AuthManagerDriver.h new file mode 100644 index 0000000000..50dde72e14 --- /dev/null +++ b/include/AuthManagerDriver.h @@ -0,0 +1,98 @@ +/* -------------------------------------------------------------------------- */ +/* 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. */ +/* -------------------------------------------------------------------------- */ + +#ifndef AUTH_MANAGER_DRIVER_H_ +#define AUTH_MANAGER_DRIVER_H_ + +#include +#include +#include + +#include "Mad.h" + +using namespace std; + +//Forward definition of the AuthManager Class +class AuthManager; + +/** + * AuthManagerDriver provides a base class to implement TM + * Drivers. This class implements the protocol and recover functions + * from the Mad interface. + */ +class AuthManagerDriver : public Mad +{ +public: + + AuthManagerDriver( + int userid, + const map& attrs, + bool sudo, + AuthManager * _authm): + Mad(userid,attrs,sudo), authm(_authm){}; + + virtual ~AuthManagerDriver(){}; + + /** + * Implements the VM Manager driver protocol. + * @param message the string read from the driver + */ + void protocol( + string& message); + + /** + * Re-starts the driver + */ + void recover(); + +private: + friend class AuthManager; + + /** + * The AuthManager to notify results. + */ + AuthManager * authm; + + /** + * Sends an authorization request to the MAD: + * "AUTHORIZE OPERATION_ID USER_ID REQUEST1 REQUEST2..." + * @param oid an id to identify the request. + * @param uid the user id. + * @param requests space separated list of requests in the form OP:OBJ:ID + */ + void authorize(int oid, int uid, const string& requests) const; + + /** + * Sends an authorization request to the MAD: + * "AUTHENTICATE REQUEST_ID USER_ID USER_NAME PASSWORD XMLRPC_TOKEN" + * @param oid an id to identify the request. + * @param uid the user id. + * @param username + * @param password + * @param session token from the xml-rpc parameter + */ + void authenticate(int oid, + int uid, + const string& username, + const string& password, + const string& session) const; +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +#endif /*AUTH_MANAGER_DRIVER_H_*/ + diff --git a/include/DispatchManager.h b/include/DispatchManager.h index dfb388fd1c..789acd1ba2 100644 --- a/include/DispatchManager.h +++ b/include/DispatchManager.h @@ -55,7 +55,7 @@ public: * Triggers specific actions to the Dispatch Manager. This function * wraps the ActionManager trigger function. * @param action the DM action - * @param vid VM unique id. This is the argument of the passed to the + * @param vid VM unique id. This is the argument of the passed to the * invoked action. */ void trigger( @@ -63,12 +63,12 @@ public: int _vid); /** - * This functions creates a new thread for the Dispatch Manager. This + * This functions creates a new thread for the Dispatch Manager. This * thread will wait in an action loop till it receives ACTION_FINALIZE. * @return 0 on success. */ int start(); - + /** * Gets the thread identification. * @return pthread_t for the manager thread (that in the action loop). @@ -81,132 +81,122 @@ public: //-------------------------------------------------------------------------- // DM Actions, the RM and the Scheduler will invoke this methods //-------------------------------------------------------------------------- - - /** - * Allocates a new virtual machine - * @return 0 on success - */ - int allocate ( - int uid, - const string& stemplate, - int * oid); - /** * Deploys a VM. A new history record MUST be added before calling this * function. Also the VM MUST have its mutex locked. If the function fails * the calling funtion is responsible for recovering from the error. * @param vm pointer to a VirtualMachine with its mutex locked. - * @return 0 on success + * @return 0 on success */ int deploy ( VirtualMachine * vm); /** - * Migrates a VM. The following actions must be performed before calling - * this function: + * Migrates a VM. The following actions must be performed before calling + * this function: * - Lock the VM mutex. * - Update the History statistics of the current host. - * - Add a new History record with the new host. - * If the function fails the calling funtion is responsible for recovering + * - Add a new History record with the new host. + * If the function fails the calling funtion is responsible for recovering * from the error. * @param vm pointer to a VirtualMachine with its mutex locked. - * @return 0 on success + * @return 0 on success */ int migrate( VirtualMachine * vm); /** - * Migrates a VM. The following actions must be performed before calling - * this function: + * Migrates a VM. The following actions must be performed before calling + * this function: * - Lock the VM mutex. * - Update the History statistics of the current host. - * - Add a new History record with the new host. - * If the function fails the calling funtion is responsible for recovering + * - Add a new History record with the new host. + * If the function fails the calling funtion is responsible for recovering * from the error. * @param vm pointer to a VirtualMachine with its mutex locked. - * @return 0 on success + * @return 0 on success */ int live_migrate( VirtualMachine * vm); - + /** * Shuts down a VM. * @param vid VirtualMachine identification - * @return 0 on success, -1 if the VM does not exits or -2 if the VM is - * in a wrong a state - */ + * @return 0 on success, -1 if the VM does not exits or -2 if the VM is + * in a wrong a state + */ int shutdown ( int vid); /** * Holds a VM. * @param vid VirtualMachine identification - * @return 0 on success, -1 if the VM does not exits or -2 if the VM is - * in a wrong a state - */ + * @return 0 on success, -1 if the VM does not exits or -2 if the VM is + * in a wrong a state + */ int hold( int vid); /** * Releases a VM. * @param vid VirtualMachine identification - * @return 0 on success, -1 if the VM does not exits or -2 if the VM is - * in a wrong a state - */ + * @return 0 on success, -1 if the VM does not exits or -2 if the VM is + * in a wrong a state + */ int release( int vid); /** * Stops a VM. * @param vid VirtualMachine identification - * @return 0 on success, -1 if the VM does not exits or -2 if the VM is - * in a wrong a state - */ + * @return 0 on success, -1 if the VM does not exits or -2 if the VM is + * in a wrong a state + */ int stop( int vid); /** * Cancels a VM. * @param vid VirtualMachine identification - * @return 0 on success, -1 if the VM does not exits or -2 if the VM is - * in a wrong a state - */ + * @return 0 on success, -1 if the VM does not exits or -2 if the VM is + * in a wrong a state + */ int cancel( int vid); /** * Suspends a VM. * @param vid VirtualMachine identification - * @return 0 on success, -1 if the VM does not exits or -2 if the VM is - * in a wrong a state - */ + * @return 0 on success, -1 if the VM does not exits or -2 if the VM is + * in a wrong a state + */ int suspend( int vid); /** * Resumes a VM. * @param vid VirtualMachine identification - * @return 0 on success, -1 if the VM does not exits or -2 if the VM is - * in a wrong a state - */ + * @return 0 on success, -1 if the VM does not exits or -2 if the VM is + * in a wrong a state + */ int resume( int vid); - + /** * Restart a previusly deployed VM. * @param vid VirtualMachine identification - * @return 0 on success, -1 if the VM does not exits or -2 if the VM is - * in a wrong a state - */ + * @return 0 on success, -1 if the VM does not exits or -2 if the VM is + * in a wrong a state + */ int restart( int vid); /** * Ends a VM life cycle inside ONE. * @param vid VirtualMachine identification - * @return 0 on success, -1 if the VM does not exits or -2 if the VM is - * in a wrong a state - */ + * @return 0 on success, -1 if the VM does not exits or -2 if the VM is + * in a wrong a state + */ int finalize( int vid); @@ -232,7 +222,7 @@ private: ActionManager am; /** - * Function to execute the Manager action loop method within a new pthread + * Function to execute the Manager action loop method within a new pthread * (requires C linkage) */ friend void * dm_action_loop(void *arg); @@ -249,14 +239,14 @@ private: //-------------------------------------------------------------------------- // DM Actions associated with a VM state transition //-------------------------------------------------------------------------- - + void suspend_success_action(int vid); void stop_success_action(int vid); void done_action(int vid); - void failed_action(int vid); + void failed_action(int vid); }; #endif /*DISPATCH_MANAGER_H*/ diff --git a/include/HookManager.h b/include/HookManager.h index 453d371dc5..5495cbd549 100644 --- a/include/HookManager.h +++ b/include/HookManager.h @@ -31,20 +31,15 @@ class HookManager : public MadManager, public ActionListener public: HookManager(vector& _mads, VirtualMachinePool * _vmpool) - :MadManager(_mads),vmpool(_vmpool) + :MadManager(_mads),vmpool(_vmpool) { am.addListener(this); }; ~HookManager(){}; - - /** - * Generic name for the Hook driver - */ - static const char * hook_driver_name; /** - * This functions starts the associated listener thread, and creates a + * This functions starts the associated listener thread, and creates a * new thread for the Hook Manager. This thread will wait in * an action loop till it receives ACTION_FINALIZE. * @return 0 on success. @@ -61,12 +56,12 @@ public: }; /** - * + * */ void load_mads(int uid=0); /** - * + * */ void finalize() { @@ -74,39 +69,43 @@ public: }; /** - * Returns a pointer to a Information Manager MAD. The driver is + * Returns a pointer to a Information Manager MAD. The driver is * searched by its name and owned by oneadmin with uid=0. * @param name of the driver - * @return the Hook driver owned by uid 0, with attribute "NAME" equal to + * @return the Hook driver owned by uid 0, with attribute "NAME" equal to * name or 0 in not found */ const HookManagerDriver * get() { string name("NAME"); - string hook_name(hook_driver_name); - + return static_cast (MadManager::get(0,name,hook_driver_name)); }; - + private: + /** + * Generic name for the Hook driver + */ + static const char * hook_driver_name; + /** * Pointer to the VirtualMachine Pool */ VirtualMachinePool * vmpool; - + /** * Thread id for the HookManager */ pthread_t hm_thread; - + /** * Action engine for the Manager */ ActionManager am; /** - * Function to execute the Manager action loop method within a new pthread + * Function to execute the Manager action loop method within a new pthread * (requires C linkage) */ friend void * hm_action_loop(void *arg); diff --git a/include/Image.h b/include/Image.h index 5d6258a151..63feb4f996 100644 --- a/include/Image.h +++ b/include/Image.h @@ -105,7 +105,7 @@ public: * Returns true if the image is public * @return true if the image is public */ - bool is_public() + bool isPublic() { return (public_img == 1); }; @@ -221,7 +221,7 @@ public: string& name, vector& values) const { - return image_template.get(name,values); + return image_template->get(name,values); }; /** @@ -235,7 +235,7 @@ public: vector& values) const { string str=name; - return image_template.get(str,values); + return image_template->get(str,values); }; /** @@ -248,7 +248,7 @@ public: string& value) const { string str=name; - image_template.get(str,value); + image_template->get(str,value); } /** @@ -261,7 +261,7 @@ public: int& value) const { string str=name; - image_template.get(str,value); + image_template->get(str,value); } /** @@ -270,7 +270,7 @@ public: */ int remove_template_attribute(SqlDB * db, const string& name) { - return image_template.remove_attribute(db, name); + return image_template->remove_attribute(db, name); } private: @@ -332,7 +332,7 @@ private: /** * The Image template, holds the Image attributes. */ - ImageTemplate image_template; + ImageTemplate * image_template; // ************************************************************************* @@ -382,7 +382,7 @@ protected: // Constructor // ************************************************************************* - Image(int id=-1); + Image(int uid=-1, ImageTemplate *img_template = 0); virtual ~Image(); diff --git a/include/ImagePool.h b/include/ImagePool.h index d46c09c4ae..968188178d 100644 --- a/include/ImagePool.h +++ b/include/ImagePool.h @@ -27,6 +27,8 @@ #include #include +class AuthRequest; + using namespace std; /** @@ -53,9 +55,9 @@ public: * -2 in case of template parse failure */ int allocate ( - int uid, - const string& stemplate, - int * oid); + int uid, + ImageTemplate * img_template, + int * oid); /** * Function to get a Image from the pool, if the object is not in memory @@ -131,7 +133,7 @@ public: { SingleAttribute * sattr = new SingleAttribute(name,value); - return image->image_template.replace_attribute(db,sattr); + return image->image_template->replace_attribute(db,sattr); } /** Delete an image attribute in the template (Image MUST be locked) @@ -143,7 +145,7 @@ public: Image * image, const string& name) { - return image->image_template.remove_attribute(db, name); + return image->image_template->remove_attribute(db, name); } /** @@ -168,31 +170,14 @@ public: * @param disk the disk to be generated * @return 0 on success, -1 error, -2 not using the pool */ - int disk_attribute(VectorAttribute * disk, int * index) - { - string source; - Image * img; + int disk_attribute(VectorAttribute * disk, int * index); - source = disk->vector_value("NAME"); - - if (source.empty()) - { - return -2; - } - - img = get(source,true); - - if (img == 0) - { - return -1; - } - - int rc = img->disk_attribute(disk,index); - - img->unlock(); - - return rc; - } + /** + * Generates an Authorization token for the DISK attribute + * @param disk the disk to be authorized + * @param ar the AuthRequest + */ + void authorize_disk(VectorAttribute * disk, AuthRequest * ar); static const string& source_prefix() { diff --git a/include/Nebula.h b/include/Nebula.h index 37d51b59af..d3baf79f70 100644 --- a/include/Nebula.h +++ b/include/Nebula.h @@ -33,6 +33,7 @@ #include "DispatchManager.h" #include "RequestManager.h" #include "HookManager.h" +#include "AuthManager.h" class Nebula { @@ -108,6 +109,12 @@ public: return hm; }; + + AuthManager * get_authm() + { + return authm; + }; + // -------------------------------------------------------------- // Environment & Configuration // -------------------------------------------------------------- @@ -217,7 +224,7 @@ private: // ----------------------------------------------------------------------- Nebula():nebula_configuration(0),db(0),vmpool(0),hpool(0),vnpool(0),upool(0), - ipool(0),lcm(0),vmm(0),im(0),tm(0),dm(0),rm(0) + ipool(0),lcm(0),vmm(0),im(0),tm(0),dm(0),rm(0),hm(0),authm(0) { const char * nl = getenv("ONE_LOCATION"); @@ -308,6 +315,11 @@ private: delete hm; } + if ( authm != 0) + { + delete authm; + } + if ( nebula_configuration != 0) { delete nebula_configuration; @@ -363,6 +375,7 @@ private: DispatchManager * dm; RequestManager * rm; HookManager * hm; + AuthManager * authm; // --------------------------------------------------------------- // Implementation functions diff --git a/include/RequestManager.h b/include/RequestManager.h index 29d62374b1..f76af653d8 100644 --- a/include/RequestManager.h +++ b/include/RequestManager.h @@ -166,7 +166,130 @@ private: 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 != (int)NULL ) + { + oss << " Returned error code [" << rc << "]."; + } + + return oss.str(); + } + // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- // XML-RPC Methods @@ -180,8 +303,14 @@ private: { public: VirtualMachineAllocate( - UserPool * _upool): - upool(_upool) + VirtualMachinePool * _vmpool, + VirtualNetworkPool * _vnpool, + ImagePool * _ipool, + UserPool * _upool): + vmpool(_vmpool), + vnpool(_vnpool), + ipool(_ipool), + upool(_upool) { _signature="A:ss"; _help="Allocates a virtual machine in the pool"; @@ -193,6 +322,9 @@ private: xmlrpc_c::paramList const& paramList, xmlrpc_c::value * const retval); private: + VirtualMachinePool * vmpool; + VirtualNetworkPool * vnpool; + ImagePool * ipool; UserPool * upool; }; @@ -203,8 +335,8 @@ private: public: VirtualMachineDeploy( VirtualMachinePool * _vmpool, - HostPool * _hpool, - UserPool * _upool): + HostPool * _hpool, + UserPool * _upool): vmpool(_vmpool), hpool(_hpool), upool(_upool) @@ -779,28 +911,6 @@ private: UserPool * upool; }; - - /* ---------------------------------------------------------------------- */ - - class UserInfo: public xmlrpc_c::method - { - public: - UserInfo(UserPool * _upool):upool(_upool) - { - _signature="A:si"; - _help="Returns the Info of the user"; - }; - - ~UserInfo(){}; - - void execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retvalP); - - private: - UserPool * upool; - }; - /* ---------------------------------------------------------------------- */ class UserDelete: public xmlrpc_c::method diff --git a/include/User.h b/include/User.h index 77d536ab51..b4dc75f597 100644 --- a/include/User.h +++ b/include/User.h @@ -50,7 +50,6 @@ public: */ string& to_xml(string& xml) const; - /** * Get the User unique identifier UID, that matches the OID of the object * @return UID User identifier @@ -119,12 +118,6 @@ public: password = _password; }; - /** - * Looks for a match between _password and user password - * @return -1 if disabled or wrong password, uid otherwise - **/ - int authenticate(string _password); - /** * Splits an authentication token (:) * @param secret, the authentication token diff --git a/include/UserPool.h b/include/UserPool.h index 73ecf072b5..1c4fc3eb49 100644 --- a/include/UserPool.h +++ b/include/UserPool.h @@ -29,6 +29,8 @@ using namespace std; +class AuthRequest; //Forward definition of AuthRequest + /** * The User Pool class. ... */ @@ -127,10 +129,17 @@ public: /** * Returns whether there is a user with given username/password or not * @param session, colon separated username and password string - * @return -1 if there is no such a user, uid of the user if it exists + * @return -1 if authn failed, uid of the user in other case */ int authenticate(string& session); + /** + * Returns whether there is a user with given username/password or not + * @param ar, an Authorization Request + * @return -1 if authz failed, 0 otherwise + */ + static int authorize(AuthRequest& ar); + /** * Dumps the User pool in XML format. A filter can be also added to the * query diff --git a/include/VirtualMachine.h b/include/VirtualMachine.h index b56f4bb8ef..af7c76e551 100644 --- a/include/VirtualMachine.h +++ b/include/VirtualMachine.h @@ -553,7 +553,7 @@ public: string& name, vector& values) const { - return vm_template.get(name,values); + return vm_template->get(name,values); }; /** @@ -567,7 +567,7 @@ public: vector& values) const { string str=name; - return vm_template.get(str,values); + return vm_template->get(str,values); }; /** @@ -581,7 +581,7 @@ public: string& value) const { string str=name; - vm_template.get(str,value); + vm_template->get(str,value); } /** @@ -595,7 +595,7 @@ public: int& value) const { string str=name; - vm_template.get(str,value); + vm_template->get(str,value); } /** @@ -604,7 +604,7 @@ public: */ void template_to_xml(string &xml) const { - vm_template.to_xml(xml); + vm_template->to_xml(xml); } /** @@ -771,7 +771,7 @@ private: /** * The Virtual Machine template, holds the VM attributes. */ - VirtualMachineTemplate vm_template; + VirtualMachineTemplate* vm_template; // Dynamic state of the Virtual Machine @@ -930,7 +930,7 @@ private: int rc; sattr = new SingleAttribute(name,value); - rc = vm_template.replace_attribute(db,sattr); + rc = vm_template->replace_attribute(db,sattr); if (rc != 0) { @@ -949,7 +949,7 @@ private: */ int insert_template_attribute(SqlDB * db, Attribute * attribute) { - return vm_template.insert_attribute(db,attribute); + return vm_template->insert_attribute(db,attribute); } // ------------------------------------------------------------------------- @@ -987,7 +987,7 @@ protected: // Constructor //************************************************************************** - VirtualMachine(int id=-1); + VirtualMachine(int id=-1, VirtualMachineTemplate * _vm_template = 0); virtual ~VirtualMachine(); diff --git a/include/VirtualMachinePool.h b/include/VirtualMachinePool.h index 685179e76a..fe8ca25bae 100644 --- a/include/VirtualMachinePool.h +++ b/include/VirtualMachinePool.h @@ -39,7 +39,7 @@ public: /** * Function to allocate a new VM object * @param uid user id (the owner of the VM) - * @param stemplate a string describing the VM + * @param vm_template a VM Template object describing the VM * @param oid the id assigned to the VM (output) * @param on_hold flag to submit on hold * @return oid on success, -1 error inserting in DB or -2 error parsing @@ -47,7 +47,7 @@ public: */ int allocate ( int uid, - const string& stemplate, + VirtualMachineTemplate *vm_template, int * oid, bool on_hold = false); @@ -99,9 +99,9 @@ public: * @return 0 on success */ int update_template_attribute( - VirtualMachine * vm, - string& name, - string& value) + VirtualMachine * vm, + string& name, + string& value) { return vm->update_template_attribute(db,name,value); } diff --git a/include/VirtualNetwork.h b/include/VirtualNetwork.h index 87841fb94e..cf37a96753 100644 --- a/include/VirtualNetwork.h +++ b/include/VirtualNetwork.h @@ -58,6 +58,15 @@ public: // Virtual Network Public Methods // ************************************************************************* + /** + * Get the Vnet unique identifier VNID, that matches the OID of the object + * @return VNID Image identifier + */ + int get_vnid() const + { + return oid; + }; + /** * Gets the uid of the owner of the Virtual Network * @return uid @@ -71,7 +80,7 @@ public: * Returns true if the Virtual Network is public * @return true if the Virtual Network is public */ - bool is_public() + bool isPublic() { return (public_vnet == 1); }; @@ -186,7 +195,7 @@ public: string& name, vector& values) const { - return vn_template.get(name,values); + return vn_template->get(name,values); }; /** @@ -200,7 +209,7 @@ public: vector& values) const { string str=name; - return vn_template.get(str,values); + return vn_template->get(str,values); }; /** @@ -213,7 +222,7 @@ public: string& value) const { string str=name; - vn_template.get(str,value); + vn_template->get(str,value); } /** @@ -226,7 +235,7 @@ public: int& value) const { string str=name; - vn_template.get(str,value); + vn_template->get(str,value); } private: @@ -284,7 +293,7 @@ private: /** * The Virtual Network template, holds the VNW attributes. */ - VirtualNetworkTemplate vn_template; + VirtualNetworkTemplate * vn_template; // ************************************************************************* // DataBase implementation (Private) @@ -346,7 +355,7 @@ private: int rc; sattr = new SingleAttribute(name,value); - rc = vn_template.replace_attribute(db,sattr); + rc = vn_template->replace_attribute(db,sattr); if (rc != 0) { @@ -362,7 +371,7 @@ protected: // Constructor //************************************************************************** - VirtualNetwork(); + VirtualNetwork(VirtualNetworkTemplate * _vn_template = 0); ~VirtualNetwork(); @@ -419,7 +428,7 @@ protected: { int rc; - rc = vn_template.drop(db); + rc = vn_template->drop(db); rc += leases->drop(db); diff --git a/include/VirtualNetworkPool.h b/include/VirtualNetworkPool.h index c5e0dd0816..f57c53037b 100644 --- a/include/VirtualNetworkPool.h +++ b/include/VirtualNetworkPool.h @@ -22,8 +22,9 @@ #include -using namespace std; +class AuthRequest; +using namespace std; /** * The Virtual Network Pool class. ... @@ -39,16 +40,15 @@ public: ~VirtualNetworkPool(){}; /** - * Function to allocate a new VN object + * Function to allocate a new VNET object * @param uid user identifier - * @param stemplate a string describing the VN + * @param vn_template a VirtualNetworkTemplate describing the VNET * @param oid the id assigned to the VM (output) - * @return oid on success, -1 error inserting in DB,-2 error parsing - * the template, -3 wrong attributes in template + * @return oid on success, -1 error */ int allocate ( int uid, - const string& stemplate, + VirtualNetworkTemplate * vn_template, int * oid); /** @@ -87,31 +87,14 @@ public: * @param vid of the VM requesting the lease * @return 0 on success, -1 error, -2 not using the pool */ - int nic_attribute(VectorAttribute * nic, int vid) - { - string network; - VirtualNetwork * vnet; + int nic_attribute(VectorAttribute * nic, int vid); - network = nic->vector_value("NETWORK"); - - if (network.empty()) - { - return -2; - } - - vnet = get(network,true); - - if (vnet == 0) - { - return -1; - } - - int rc = vnet->nic_attribute(nic,vid); - - vnet->unlock(); - - return rc; - } + /** + * Generates an Authorization token for a NIC attribute + * @param nic the nic to be authorized + * @param ar the AuthRequest + */ + void authorize_nic(VectorAttribute * nic, AuthRequest * ar); /** * Updates the template of a VN, adding a new attribute (replacing it if diff --git a/install.sh b/install.sh index fd312a305e..733ab6bb53 100755 --- a/install.sh +++ b/install.sh @@ -157,6 +157,7 @@ ETC_DIRS="$ETC_LOCATION/im_kvm \ $ETC_LOCATION/tm_dummy \ $ETC_LOCATION/tm_lvm \ $ETC_LOCATION/hm \ + $ETC_LOCATION/auth \ $ETC_LOCATION/ec2query_templates \ $ETC_LOCATION/occi_templates" @@ -240,10 +241,11 @@ INSTALL_ETC_FILES[10]="TM_SSH_ETC_FILES:$ETC_LOCATION/tm_ssh" INSTALL_ETC_FILES[11]="TM_DUMMY_ETC_FILES:$ETC_LOCATION/tm_dummy" INSTALL_ETC_FILES[12]="TM_LVM_ETC_FILES:$ETC_LOCATION/tm_lvm" INSTALL_ETC_FILES[13]="HM_ETC_FILES:$ETC_LOCATION/hm" -INSTALL_ETC_FILES[14]="ECO_ETC_FILES:$ETC_LOCATION" -INSTALL_ETC_FILES[15]="ECO_ETC_TEMPLATE_FILES:$ETC_LOCATION/ec2query_templates" -INSTALL_ETC_FILES[16]="OCCI_ETC_FILES:$ETC_LOCATION" -INSTALL_ETC_FILES[17]="OCCI_ETC_TEMPLATE_FILES:$ETC_LOCATION/occi_templates" +INSTALL_ETC_FILES[14]="AUTH_ETC_FILES:$ETC_LOCATION/auth" +INSTALL_ETC_FILES[15]="ECO_ETC_FILES:$ETC_LOCATION" +INSTALL_ETC_FILES[16]="ECO_ETC_TEMPLATE_FILES:$ETC_LOCATION/ec2query_templates" +INSTALL_ETC_FILES[17]="OCCI_ETC_FILES:$ETC_LOCATION" +INSTALL_ETC_FILES[18]="OCCI_ETC_TEMPLATE_FILES:$ETC_LOCATION/occi_templates" #------------------------------------------------------------------------------- # Binary files, to be installed under $BIN_LOCATION @@ -282,7 +284,11 @@ RUBY_LIB_FILES="src/mad/ruby/one_mad.rb \ src/cli/client_utilities.rb \ src/cli/command_parse.rb \ src/oca/ruby/OpenNebula.rb \ - src/tm_mad/TMScript.rb" + src/tm_mad/TMScript.rb \ + src/authm_mad/one_usage.rb \ + src/authm_mad/quota.rb \ + src/authm_mad/simple_auth.rb \ + src/authm_mad/simple_permissions.rb" RUBY_OPENNEBULA_LIB_FILES="src/oca/ruby/OpenNebula/Host.rb \ src/oca/ruby/OpenNebula/HostPool.rb \ @@ -321,7 +327,9 @@ MADS_LIB_FILES="src/mad/sh/madcommon.sh \ src/tm_mad/one_tm \ src/tm_mad/one_tm.rb \ src/hm_mad/one_hm.rb \ - src/hm_mad/one_hm" + src/hm_mad/one_hm \ + src/authm_mad/one_auth_mad.rb \ + src/authm_mad/one_auth_mad" #------------------------------------------------------------------------------- # Information Manager Probes, to be installed under $LIB_LOCATION/im_probes @@ -439,6 +447,13 @@ TM_LVM_ETC_FILES="src/tm_mad/lvm/tm_lvm.conf \ HM_ETC_FILES="src/hm_mad/hmrc" +#------------------------------------------------------------------------------- +# Hook Manager driver config. files, to be installed under $ETC_LOCATION/hm +#------------------------------------------------------------------------------- + +AUTH_ETC_FILES="src/authm_mad/auth_mad \ + src/authm_mad/auth.conf" + #------------------------------------------------------------------------------- # Sample files, to be installed under $SHARE_LOCATION/examples #------------------------------------------------------------------------------- diff --git a/share/etc/oned.conf b/share/etc/oned.conf index c719da67cd..0e356e4c04 100644 --- a/share/etc/oned.conf +++ b/share/etc/oned.conf @@ -258,12 +258,12 @@ TM_MAD = [ HM_MAD = [ executable = "one_hm" ] - + #-------------------------------- Image Hook ----------------------------------- # This hook is used to handle image saving and overwriting when virtual machines -# reach the DONE state after being shutdown. -# +# reach the DONE state after being shutdown. +# # Uncomment one of the following: # # Self-contained (substitute [ONE_LOCATION] with its proper path) @@ -302,3 +302,21 @@ HM_MAD = [ # arguments = "$VMID $NAME", # remote = "no" ] #------------------------------------------------------------------------------ + +#******************************************************************************* +# Auth Manager Configuration +#******************************************************************************* +# The Driver (AUTHM_MAD) that will be used to authenticate and authorize +# OpenNebula requests. If not defined OpenNebula will use the built-in auth +# policies +# executable: path of the auth driver executable, can be an +# absolute path or relative to $ONE_LOCATION/lib/mads (or +# /usr/lib/one/mads/ if OpenNebula was installed in /) +# +# arguments : for the driver executable, can be an absolute path or relative +# to $ONE_LOCATION/etc (or /etc/one/ if OpenNebula was installed +# in /) +#------------------------------------------------------------------------------- + +#AUTH_MAD = [ +# executable = "" ] \ No newline at end of file diff --git a/share/test/do_tests.sh b/share/test/do_tests.sh index 5bfedf7b97..8d5c766099 100755 --- a/share/test/do_tests.sh +++ b/share/test/do_tests.sh @@ -62,8 +62,10 @@ done if [ "$MYSQL" = "yes" ] ; then TEST_ARGS="-m" + BUILD_ARGS="mysql=yes sqlite=no" else TEST_ARGS="-s" + BUILD_ARGS="mysql=no sqlite=yes" fi if [ "$LOGS" = "yes" ] ; then @@ -78,7 +80,7 @@ elif [ "$VAL_CALL" = "yes" ] ; then CALLER="valgrind --tool=callgrind" fi -TESTS=`find $TWD_DIR -name test -type d` +TESTS=`find $TWD_DIR -name test -type d | grep -v ruby` for i in $TESTS ; do cd $BASE_DIR @@ -88,9 +90,9 @@ for i in $TESTS ; do if [ "$CLEAR" = "yes" ] ; then scons -c - rm -f callgrind.out* test.db* test.log* memgrid.out* + rm -f callgrind.out* test.db* *.log* memgrid.out* elif [ "$BUILD" = "yes" ] ; then - scons + scons $BUILD_ARGS else for j in `ls test*` ; do $CALLER ./$j $TEST_ARGS diff --git a/src/authm/AuthManager.cc b/src/authm/AuthManager.cc new file mode 100644 index 0000000000..d3ccf6a6d4 --- /dev/null +++ b/src/authm/AuthManager.cc @@ -0,0 +1,513 @@ +/* -------------------------------------------------------------------------- */ +/* 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 "AuthManager.h" +#include "NebulaLog.h" + +#include "Nebula.h" + +#include +#include +#include +#include +#include + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +time_t AuthManager::_time_out; + +const char * AuthManager::auth_driver_name = "auth_exe"; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +string * AuthRequest::base64_encode(const string& in) +{ + BIO * bio_mem; + BIO * bio_64; + + char * encoded_c; + long int size; + + bio_64 = BIO_new(BIO_f_base64()); + bio_mem = BIO_new(BIO_s_mem()); + + BIO_push(bio_64, bio_mem); + + BIO_set_flags(bio_64,BIO_FLAGS_BASE64_NO_NL); + + BIO_write(bio_64, in.c_str(), in.length()); + + if (BIO_flush(bio_64) != 1) + { + return 0; + } + + size = BIO_get_mem_data(bio_mem,&encoded_c); + + string * encoded = new string(encoded_c,size); + + BIO_free_all(bio_64); + + return encoded; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AuthRequest::add_auth(Object ob, + const string& ob_id, + Operation op, + int owner, + bool pub) +{ + ostringstream oss; + bool auth; + + switch (ob) + { + case VM: oss << "VM:" ; break; + case HOST: oss << "HOST:" ; break; + case NET: oss << "NET:" ; break; + case IMAGE: oss << "IMAGE:" ; break; + case USER: oss << "USER:" ; break; + case CLUSTER: oss << "CLUSTER:" ; break; + } + + if (op == CREATE) //encode the ob_id, it is a template + { + string * encoded_id = base64_encode(ob_id); + + if (encoded_id != 0) + { + oss << *encoded_id << ":"; + delete (encoded_id); + } + else + { + oss << "-:"; + } + } + else + { + oss << ob_id << ":"; + } + + switch (op) + { + case CREATE: + oss << "CREATE:" ; + break; + + case DELETE: + oss << "DELETE:" ; + break; + + case USE: + oss << "USE:" ; + break; + + case MANAGE: + oss << "MANAGE:" ; + break; + + case INFO: + oss << "INFO:" ; + break; + } + + oss << owner << ":" << pub; + + // ------------------------------------------------------------------------- + // Authorize the request for self authorization + // ------------------------------------------------------------------------- + + if ( uid == 0 ) + { + auth = true; + } + else + { + auth = false; + + switch (op) + { + case CREATE: + if ( ob == VM || ob == NET || ob == IMAGE ) + { + auth = true; + } + break; + + case DELETE: + auth = owner == uid; + break; + + case USE: + if (ob == NET || ob == IMAGE) + { + auth = (owner == uid) || pub; + } + else if (ob == HOST) + { + auth = true; + } + break; + + case MANAGE: + auth = owner == uid; + break; + + case INFO: // This is for completeness, as the only INFO existing + // is for UserPool, and just oneadmin can see it + break; + } + } + + self_authorize = self_authorize && auth; + + auths.push_back(oss.str()); +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +extern "C" void * authm_action_loop(void *arg) +{ + AuthManager * authm; + + if ( arg == 0 ) + { + return 0; + } + + authm = static_cast(arg); + + NebulaLog::log("AuM",Log::INFO,"Authorization Manager started."); + + authm->am.loop(authm->timer_period,0); + + NebulaLog::log("AuM",Log::INFO,"Authorization Manager stopped."); + + return 0; +} + +/* -------------------------------------------------------------------------- */ + +int AuthManager::start() +{ + int rc; + pthread_attr_t pattr; + + rc = MadManager::start(); + + if ( rc != 0 ) + { + return -1; + } + + NebulaLog::log("AuM",Log::INFO,"Starting Auth Manager..."); + + pthread_attr_init (&pattr); + pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE); + + rc = pthread_create(&authm_thread,&pattr,authm_action_loop,(void *) this); + + return rc; +}; + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AuthManager::trigger(Actions action, AuthRequest * request) +{ + string aname; + + switch (action) + { + case AUTHENTICATE: + aname = "AUTHENTICATE"; + break; + + case AUTHORIZE: + aname = "AUTHORIZE"; + break; + + case FINALIZE: + aname = ACTION_FINALIZE; + break; + + default: + return; + } + + am.trigger(aname,request); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AuthManager::do_action(const string &action, void * arg) +{ + AuthRequest * request; + + request = static_cast(arg); + + if (action == "AUTHENTICATE" && request != 0) + { + authenticate_action(request); + } + else if (action == "AUTHORIZE" && request != 0) + { + authorize_action(request); + } + else if (action == ACTION_TIMER) + { + timer_action(); + } + else if (action == ACTION_FINALIZE) + { + NebulaLog::log("AuM",Log::INFO,"Stopping Authorization Manager..."); + + MadManager::stop(); + } + else + { + ostringstream oss; + oss << "Unknown action name: " << action; + + NebulaLog::log("AuM", Log::ERROR, oss); + } +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AuthManager::authenticate_action(AuthRequest * ar) +{ + const AuthManagerDriver * authm_md; + + // ------------------------------------------------------------------------ + // Get the driver + // ------------------------------------------------------------------------ + + authm_md = get(); + + if (authm_md == 0) + { + goto error_driver; + } + + // ------------------------------------------------------------------------ + // Queue the request + // ------------------------------------------------------------------------ + + ar->id = add_request(ar); + + // ------------------------------------------------------------------------ + // Make the request to the driver + // ---- -------------------------------------------------------------------- + + + authm_md->authenticate(ar->id, + ar->uid, + ar->username, + ar->password, + ar->session); + return; + +error_driver: + ar->result = false; + ar->message = "Could not find Authorization driver"; + ar->notify(); +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AuthManager::authorize_action(AuthRequest * ar) +{ + const AuthManagerDriver * authm_md; + string auths; + + // ------------------------------------------------------------------------ + // Get the driver + // ------------------------------------------------------------------------ + + authm_md = get(); + + if (authm_md == 0) + { + goto error_driver; + } + + // ------------------------------------------------------------------------ + // Queue the request + // ------------------------------------------------------------------------ + + ar->id = add_request(ar); + + // ------------------------------------------------------------------------ + // Make the request to the driver + // ------------------------------------------------------------------------ + + auths = ar->get_auths(); + + authm_md->authorize(ar->id, ar->uid, auths); + + return; + +error_driver: + ar->result = false; + ar->message = "Could not find Authorization driver"; + ar->notify(); +} +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AuthManager::timer_action() +{ + map::iterator it; + + time_t the_time = time(0); + + lock(); + + for (it=auth_requests.begin();it!=auth_requests.end();it++) + { + if (the_time > it->second->time_out) + { + AuthRequest * ar = it->second; + auth_requests.erase(it); + + ar->result = false; + ar->timeout = true; + ar->message = "Auth request timeout"; + + ar->notify(); + } + } + + unlock(); + +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int AuthManager::add_request(AuthRequest *ar) +{ + static int auth_id = 0; + int id; + + lock(); + + id = auth_id++; + + auth_requests.insert(auth_requests.end(),make_pair(id,ar)); + + unlock(); + + return id; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +AuthRequest * AuthManager::get_request(int id) +{ + AuthRequest * ar = 0; + map::iterator it; + ostringstream oss; + + lock(); + + it=auth_requests.find(id); + + if ( it != auth_requests.end()) + { + ar = it->second; + + auth_requests.erase(it); + } + + unlock(); + + return ar; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AuthManager::notify_request(int auth_id,bool result,const string& message) +{ + + AuthRequest * ar; + + ar = get_request(auth_id); + + if ( ar == 0 ) + { + return; + } + + ar->result = result; + ar->message= message; + + ar->notify(); +} + +/* ************************************************************************** */ +/* MAD Loading */ +/* ************************************************************************** */ + +void AuthManager::load_mads(int uid) +{ + ostringstream oss; + const VectorAttribute * vattr; + int rc; + string name; + AuthManagerDriver * authm_driver = 0; + + oss << "Loading Auth. Manager driver."; + + NebulaLog::log("AuM",Log::INFO,oss); + + vattr = static_cast(mad_conf[0]); + + if ( vattr == 0 ) + { + NebulaLog::log("AuM",Log::ERROR,"Failed to load Auth. Manager driver."); + return; + } + + VectorAttribute auth_conf("AUTH_MAD",vattr->value()); + + auth_conf.replace("NAME",auth_driver_name); + + authm_driver = new AuthManagerDriver(uid,auth_conf.value(),(uid!=0),this); + + rc = add(authm_driver); + + if ( rc == 0 ) + { + oss.str(""); + oss << "\tAuth Manager loaded"; + + NebulaLog::log("AuM",Log::INFO,oss); + } +} diff --git a/src/authm/AuthManagerDriver.cc b/src/authm/AuthManagerDriver.cc new file mode 100644 index 0000000000..b45d42cda9 --- /dev/null +++ b/src/authm/AuthManagerDriver.cc @@ -0,0 +1,127 @@ +/* -------------------------------------------------------------------------- */ +/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) */ +/* */ +/* Licensed under the Apache License, Version 2.0 (the "License"); you may */ +/* not use this file except in compliance with the License. You may obtain */ +/* a copy of the License at */ +/* */ +/* http://www.apache.org/licenses/LICENSE-2.0 */ +/* */ +/* Unless required by applicable law or agreed to in writing, software */ +/* distributed under the License is distributed on an "AS IS" BASIS, */ +/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ +/* See the License for the specific language governing permissions and */ +/* limitations under the License. */ +/* -------------------------------------------------------------------------- */ + +#include "AuthManagerDriver.h" +#include "AuthManager.h" +#include "NebulaLog.h" + +#include "Nebula.h" +#include + +/* ************************************************************************** */ +/* Driver ASCII Protocol Implementation */ +/* ************************************************************************** */ + +void AuthManagerDriver::authorize(int oid, int uid, const string& reqs) const +{ + ostringstream os; + + os << "AUTHORIZE " << oid << " " << uid << " " << reqs << endl; + + write(os); +} + +void AuthManagerDriver::authenticate(int oid, + int uid, + const string& username, + const string& password, + const string& session) const +{ + ostringstream os; + + os << "AUTHENTICATE " << oid << " " + << uid << " " + << username << " " + << password << " " + << session << endl; + + write(os); +} + +/* ************************************************************************** */ +/* MAD Interface */ +/* ************************************************************************** */ + +void AuthManagerDriver::protocol( + string& message) +{ + istringstream is(message); + ostringstream os; + + string action; + string result; + string info=""; + + int id; + + os << "Message received: " << message; + NebulaLog::log("AuM", Log::DEBUG, os); + + // Parse the driver message + if ( is.good() ) + is >> action >> ws; + else + return; + + if ( is.good() ) + is >> result >> ws; + else + return; + + if ( is.good() ) + { + is >> id >> ws; + + if ( is.fail() ) + { + if ( action == "LOG" ) + { + is.clear(); + getline(is,info); + NebulaLog::log("AuM",Log::INFO, info.c_str()); + } + + return; + } + } + else + return; + + if (action == "LOG") + { + getline(is,info); + NebulaLog::log("AuM",Log::INFO,info.c_str()); + } + else if (result == "SUCCESS") + { + authm->notify_request(id,true,info); + } + else + { + getline(is,info); + authm->notify_request(id,false,info); + } + + return; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void AuthManagerDriver::recover() +{ + NebulaLog::log("AuM",Log::INFO,"Recovering Authorization drivers"); +} diff --git a/src/authm/SConstruct b/src/authm/SConstruct new file mode 100644 index 0000000000..fd2c542edb --- /dev/null +++ b/src/authm/SConstruct @@ -0,0 +1,30 @@ +# SConstruct for src/vm + +# -------------------------------------------------------------------------- # +# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # + +Import('env') + +lib_name='nebula_authm' + +# Sources to generate the library +source_files=[ + 'AuthManager.cc', + 'AuthManagerDriver.cc' +] + +# Build library +env.StaticLibrary(lib_name, source_files) diff --git a/src/authm/test/AuthManagerTest.cc b/src/authm/test/AuthManagerTest.cc new file mode 100644 index 0000000000..c2c13435fe --- /dev/null +++ b/src/authm/test/AuthManagerTest.cc @@ -0,0 +1,292 @@ +/* -------------------------------------------------------------------------- */ +/* 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 +#include + +#include "AuthManager.h" +#include "Template.h" +#include "NebulaLog.h" + +#include +#include +#include +#include +#include +#include + +using namespace std; + + +/* ************************************************************************* */ +/* ************************************************************************* */ + +class AuthManagerTest : public CppUnit::TestFixture +{ + CPPUNIT_TEST_SUITE (AuthManagerTest); + + CPPUNIT_TEST (load); + //CPPUNIT_TEST (timeout); + CPPUNIT_TEST (authenticate); + CPPUNIT_TEST (authorize); + CPPUNIT_TEST (self_authorize); + CPPUNIT_TEST (self_authenticate); + + CPPUNIT_TEST_SUITE_END (); + + +public: + AuthManagerTest(){}; + + ~AuthManagerTest(){}; + + + /* ********************************************************************* */ + /* ********************************************************************* */ + void setUp() + { + + ostringstream oss; + vector am_mads; + char *error = 0; + + MadManager::mad_manager_system_init(); + + oss << "AUTH_MAD = [ executable=\"/" << getenv("PWD") + << "/dummy\"]" << endl; + + t = new Template(); + + t->parse(oss.str(),&error); + + t->get("AUTH_MAD", am_mads); + + am = new AuthManager(1,3,am_mads); + }; + + void tearDown() + { + delete am; + delete t; + }; + + void load() + { + int rc; + + rc = am->start(); + + CPPUNIT_ASSERT(rc==0); + + am->load_mads(0); + + am->trigger(AuthManager::FINALIZE,0); + + pthread_join(am->get_thread_id(),0); + + CPPUNIT_ASSERT(0==0); + } + + //This test needs a driver that takes more than 3 secs to AUTHENTICATE + void timeout() + { + int rc; + AuthRequest ar(2); + + rc = am->start(); + + CPPUNIT_ASSERT(rc==0); + + am->load_mads(0); + + ar.add_authenticate("the_user","the_pass","the_secret"); + + am->trigger(AuthManager::AUTHENTICATE,&ar); + + ar.wait(); + + CPPUNIT_ASSERT(ar.result==false); + CPPUNIT_ASSERT(ar.timeout==true); + + am->discard_request(ar.id); + + am->trigger(AuthManager::FINALIZE,0); + + pthread_join(am->get_thread_id(),0); + + CPPUNIT_ASSERT(0==0); + } + + void authenticate() + { + int rc; + AuthRequest ar(2); + + rc = am->start(); + + CPPUNIT_ASSERT(rc==0); + + am->load_mads(0); + + ar.add_authenticate("the_user","the_pass","the_secret"); + + am->trigger(AuthManager::AUTHENTICATE,&ar); + ar.wait(); + + CPPUNIT_ASSERT(ar.result==true); + + am->trigger(AuthManager::FINALIZE,0); + + pthread_join(am->get_thread_id(),0); + + CPPUNIT_ASSERT(0==0); + } + + + void authorize() + { + int rc; + AuthRequest ar(2); + + rc = am->start(); + + CPPUNIT_ASSERT(rc==0); + + am->load_mads(0); + + //OBJECT:OBJECT_ID:ACTION:OWNER:PUBLIC + + string astr="VM:VGhpcyBpcyBhIHRlbXBsYXRlCg==:CREATE:-1:0 " + "IMAGE:2:USE:3:0 " + "NET:4:DELETE:5:1 " + "HOST:6:MANAGE:7:1"; + + ar.add_auth(AuthRequest::VM, + "This is a template\n", + AuthRequest::CREATE, + -1, + false); + + ar.add_auth(AuthRequest::IMAGE, + 2, + AuthRequest::USE, + 3, + false); + + ar.add_auth(AuthRequest::NET, + 4, + AuthRequest::DELETE, + 5, + true); + + ar.add_auth(AuthRequest::HOST, + 6, + AuthRequest::MANAGE, + 7, + true); + + am->trigger(AuthManager::AUTHORIZE,&ar); + ar.wait(); + + CPPUNIT_ASSERT(ar.result==false); + CPPUNIT_ASSERT(ar.message==astr); + + am->trigger(AuthManager::FINALIZE,0); + + pthread_join(am->get_thread_id(),0); + + CPPUNIT_ASSERT(0==0); + } + + + void self_authorize() + { + AuthRequest ar(2); + AuthRequest ar1(2); + AuthRequest ar2(3); + AuthRequest ar3(4); + AuthRequest ar4(2); + AuthRequest ar5(0); + AuthRequest ar6(0); + + ar.add_auth(AuthRequest::VM,"dGhpcy",AuthRequest::CREATE,2,false); + ar.add_auth(AuthRequest::NET,2,AuthRequest::USE,2,false); + ar.add_auth(AuthRequest::IMAGE,3,AuthRequest::USE,4,true); + + CPPUNIT_ASSERT(ar.plain_authorize() == true); + + ar1.add_auth(AuthRequest::VM,"dGhpcy",AuthRequest::CREATE,2,false); + ar1.add_auth(AuthRequest::NET,2,AuthRequest::USE,2,false); + ar1.add_auth(AuthRequest::IMAGE,3,AuthRequest::USE,4,false); + + CPPUNIT_ASSERT(ar1.plain_authorize() == false); + + ar2.add_auth(AuthRequest::HOST,"dGhpcy",AuthRequest::CREATE,0,false); + CPPUNIT_ASSERT(ar2.plain_authorize() == false); + + ar3.add_auth(AuthRequest::VM,5,AuthRequest::MANAGE,2,false); + CPPUNIT_ASSERT(ar3.plain_authorize() == false); + + ar4.add_auth(AuthRequest::VM,4,AuthRequest::MANAGE,2,false); + CPPUNIT_ASSERT(ar4.plain_authorize() == true); + + ar5.add_auth(AuthRequest::HOST,4,AuthRequest::MANAGE,0,false); + CPPUNIT_ASSERT(ar5.plain_authorize() == true); + + ar6.add_auth(AuthRequest::HOST,4,AuthRequest::CREATE,0,false); + CPPUNIT_ASSERT(ar6.plain_authorize() == true); + } + + void self_authenticate() + { + AuthRequest ar(2); + AuthRequest ar1(2); + + ar.add_authenticate("the_user","the_pass","the_secret"); + CPPUNIT_ASSERT(ar.plain_authenticate() == false); + + ar1.add_authenticate("the_user","the_pass","the_pass"); + CPPUNIT_ASSERT(ar1.plain_authenticate() == true); + } + +private: + AuthManager * am; + + Template * t; +}; + + +/* ************************************************************************* */ +/* ************************************************************************* */ + +int main(int argc, char ** argv) +{ + CppUnit::TextUi::TestRunner runner; + + NebulaLog::init_log_system(NebulaLog::FILE, Log::DEBUG,"test.log"); + NebulaLog::log("Test", Log::INFO, "Test started"); + + runner.addTest(AuthManagerTest::suite()); + + runner.run(); + + NebulaLog::finalize_log_system(); + + return 0; +} diff --git a/src/authm/test/SConstruct b/src/authm/test/SConstruct new file mode 100644 index 0000000000..827237c72b --- /dev/null +++ b/src/authm/test/SConstruct @@ -0,0 +1,88 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2009, Distributed Systems Architecture Group, Universidad # +# Complutense de Madrid (dsa-research.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 os +import sys +import shutil +sys.path.append("../../../share/scons") +from lex_bison import * + +# This is the absolute path where the project is located +cwd="../../../" + +# Environment that will be applied to each scons child +main_env=Environment() +main_env['ENV']['PATH']=os.environ['PATH'] + +# Add builders for flex and bison +add_lex(main_env) +add_bison(main_env) + +# Include dirs +main_env.Append(CPPPATH=[ + cwd + '/include', + '/usr/include/cppunit/' +]) + +# Library dirs +main_env.Append(LIBPATH=[ + cwd + '/src/common', + cwd + '/src/template', + cwd + '/src/mad', + cwd + '/src/nebula', + cwd + '/src/authm', + cwd + '/src/sql', + cwd + '/src/log', +]) + +main_env.Append(LIBS=[ + 'nebula_template', + 'nebula_common', + 'nebula_core', + 'nebula_mad', + 'nebula_authm', + 'nebula_sql', + 'nebula_log', + 'cppunit', + 'dl', + 'pthread', + 'ssl' +]) + +# Compile flags +main_env.Append(CPPFLAGS=[ + "-g", + "-Wall" +]) + +# MYSQL +main_env.Append(LIBPATH=["/usr/lib/mysql"]) +main_env.Append(CPPPATH=["/usr/include/mysql"]) + +sqlite=ARGUMENTS.get('sqlite', 'yes') +if sqlite=='yes': + main_env.Append(CPPFLAGS=["-DSQLITE_DB"]) + main_env.Append(LIBS=[ 'sqlite3', ]) + +# MySQL +mysql=ARGUMENTS.get('mysql', 'no') +if mysql=='yes': + main_env.Append(CPPFLAGS=["-DMYSQL_DB"]) + main_env.Append(LIBS=[ 'mysqlclient', ]) + +main_env.Program('test','AuthManagerTest.cc') +# diff --git a/src/authm/test/dummy b/src/authm/test/dummy new file mode 100755 index 0000000000..00f1caef56 --- /dev/null +++ b/src/authm/test/dummy @@ -0,0 +1,44 @@ +#!/bin/bash + +# -------------------------------------------------------------------------- +# Copyright 2002-2006 GridWay Team, Distributed Systems Architecture +# Group, Universidad Complutense de Madrid +# +# 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 + case $COMMAND in + "INIT") + echo "INIT SUCCESS" + ;; + "FINALIZE") + echo "FINALIZE SUCCESS" + exit 0 + ;; + "AUTHORIZE") + echo "AUTHORIZE FAILURE $ARG1 $ARG3" + ;; + "AUTHENTICATE") + echo "AUTHENTICATE SUCCESS $ARG1" + ;; + *) + echo "$COMMAND - FAILURE Unknown command" + ;; + esac +done diff --git a/src/authm_mad/auth.conf b/src/authm_mad/auth.conf new file mode 100644 index 0000000000..633bed5302 --- /dev/null +++ b/src/authm_mad/auth.conf @@ -0,0 +1,5 @@ +:database: sqlite://auth.db +:quota: + :defaults: + :cpu: 10.0 + :memory: 1048576 \ No newline at end of file diff --git a/src/authm_mad/auth_mad b/src/authm_mad/auth_mad new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/src/authm_mad/auth_mad @@ -0,0 +1 @@ + diff --git a/src/authm_mad/one_auth_mad b/src/authm_mad/one_auth_mad new file mode 100755 index 0000000000..58df732596 --- /dev/null +++ b/src/authm_mad/one_auth_mad @@ -0,0 +1,39 @@ +#!/bin/bash + +# -------------------------------------------------------------------------- # +# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # + +if [ -z "${ONE_LOCATION}" ]; then + DRIVERRC=/etc/one/auth/authrc + MADCOMMON=/usr/lib/one/mads/madcommon.sh + VAR_LOCATION=/var/lib/one +else + DRIVERRC=$ONE_LOCATION/etc/auth/authrc + MADCOMMON=$ONE_LOCATION/lib/mads/madcommon.sh + VAR_LOCATION=$ONE_LOCATION/var +fi + +. $MADCOMMON + +# Export the vmm_mad specific rc +export_rc_vars $DRIVERRC + +# Go to ONE_LOCATION +cd $VAR_LOCATION + +# Execute the actual MAD +execute_mad $* + diff --git a/src/authm_mad/one_auth_mad.rb b/src/authm_mad/one_auth_mad.rb new file mode 100755 index 0000000000..eb4deefb5d --- /dev/null +++ b/src/authm_mad/one_auth_mad.rb @@ -0,0 +1,87 @@ +#!/usr/bin/env ruby + +# -------------------------------------------------------------------------- # +# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # + +ONE_LOCATION=ENV["ONE_LOCATION"] + +if !ONE_LOCATION + RUBY_LIB_LOCATION="/usr/lib/one/ruby" + ETC_LOCATION="/etc/one/" +else + RUBY_LIB_LOCATION=ONE_LOCATION+"/lib/ruby" + ETC_LOCATION=ONE_LOCATION+"/etc/" +end + +$: << RUBY_LIB_LOCATION + +require 'pp' + +require 'rubygems' +require 'OpenNebulaDriver' +require 'simple_auth' +require 'simple_permissions' +require 'yaml' +require 'sequel' + +class AuthorizationManager < OpenNebulaDriver + def initialize + super(1, false) + + config_data=File.read(ETC_LOCATION+'/auth/auth.conf') + STDERR.puts(config_data) + @config=YAML::load(config_data) + + STDERR.puts @config.inspect + + database_url=@config[:database] + @db=Sequel.connect(database_url) + + @authenticate=SimpleAuth.new + @permissions=SimplePermissions.new(@db, OpenNebula::Client.new, + @config) + + register_action(:AUTHENTICATE, method('action_authenticate')) + register_action(:AUTHORIZE, method('action_authorize')) + end + + def action_authenticate(request_id, user_id, user, password, token) + auth=@authenticate.auth(user_id, user, password, token) + if auth==true + send_message('AUTHENTICATE', RESULT[:success], + request_id, 'Successfully authenticated') + else + send_message('AUTHENTICATE', RESULT[:failure], + request_id, auth) + end + end + + def action_authorize(request_id, user_id, *tokens) + auth=@permissions.auth(user_id, tokens.flatten) + if auth==true + send_message('AUTHORIZE', RESULT[:success], + request_id, 'success') + else + send_message('AUTHORIZE', RESULT[:failure], + request_id, auth) + end + end +end + + +am=AuthorizationManager.new +am.start_driver + diff --git a/src/authm_mad/one_usage.rb b/src/authm_mad/one_usage.rb new file mode 100644 index 0000000000..49c8ee9e28 --- /dev/null +++ b/src/authm_mad/one_usage.rb @@ -0,0 +1,86 @@ +# -------------------------------------------------------------------------- # +# 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. # +#--------------------------------------------------------------------------- # + +require 'OpenNebula' + +# This class holds usage information for a virtual machine or +# total usage for a user. Variables inside are cpu and memory +# consumption +class VmUsage + attr_accessor :cpu, :memory + def initialize(cpu, memory) + @cpu=cpu + @memory=memory + end +end + +# This class retrieves and caches vms and its consuption grouped +# by users. 'update_user' method should be called to fill data for +# a user before any calculation is made +class OneUsage + # 'client' is an OpenNebula::Client object used to connect + # to OpenNebula daemon. Ideally it should connect as user 0 + def initialize(client) + @client=client + @users=Hash.new + end + + # Gets information about VMs defined for a user. It caches new + # VMs and takes out from the cache deleted VMs + def update_user(user) + @users[user]=Hash.new if !@users[user] + + vmpool=OpenNebula::VirtualMachinePool.new(@client, user) + vmpool.info + + one_ids=vmpool.map {|vm| vm.id } + vms=@users[user] + user_ids=vms.keys + + deleted_vms=user_ids-one_ids + added_vms=one_ids-user_ids + + deleted_vms.each {|vmid| vms.delete(vmid) } + added_vms.each do |vmid| + vm=OpenNebula::VirtualMachine.new( + OpenNebula::VirtualMachine.build_xml(vmid), @client) + vm.info + hash=vm.to_hash['VM']['TEMPLATE'] + usage=VmUsage.new(hash['CPU'].to_f, hash['MEMORY'].to_i) + vms[vmid.to_i]=usage + end + end + + # Returns the cache of defined VMs for a user. It is a hash with + # VM id as key and VmUsage as value + def vms(user) + vms=@users[user] + @users[user]=vms=Hash.new if !vms + vms + end + + # Returns total consumption by a user into a VmUsage object + def total(user) + usage=VmUsage.new(0.0, 0) + + @users[user].each do |id, vm| + usage.cpu+=vm.cpu + usage.memory+=vm.memory + end + + usage + end +end diff --git a/src/authm_mad/quota.rb b/src/authm_mad/quota.rb new file mode 100644 index 0000000000..f1e7a02d1f --- /dev/null +++ b/src/authm_mad/quota.rb @@ -0,0 +1,115 @@ +# -------------------------------------------------------------------------- # +# 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. # +#--------------------------------------------------------------------------- # + +require 'one_usage' + +# Quota functionality for auth driver. Stores in database limits for each +# user and using OneUsage is able to retrieve resource usage from +# OpenNebula daemon and check if it is below limits +class Quota + attr_accessor :defaults + + TABLE_NAME=:quotas + + # 'db' is a Sequel database where to store user limits and client + # is OpenNebula::Client used to connect to OpenNebula daemon + def initialize(db, client, conf={}) + @db=db + @client=client + @conf={ + :defaults => { + :cpu => nil, + :memory => nil + } + }.merge(conf) + + STDERR.puts conf.inspect + STDERR.puts @conf.inspect + + @defaults=@conf[:defaults] + + @usage=OneUsage.new(@client) + + create_table + @table=@db[TABLE_NAME] + end + + # Creates database quota table if it does not exist + def create_table + @db.create_table?(TABLE_NAME) do + primary_key :id + Integer :uid + Float :cpu + Integer :memory + Integer :num_vms + index :uid + end + end + + # Adds new user limits + def set(uid, cpu, memory, num_vms) + data={ + :cpu => cpu, + :memory => memory, + :num_vms => num_vms + } + + quotas=@table.filter(:uid => uid) + + if quotas.first + quotas.update(data) + else + @table.insert(data.merge!(:uid => uid)) + end + end + + # Gets user limits + def get(uid) + limit=@table.filter(:uid => uid).first + if limit + limit + else + @defaults + end + end + + # Checks if the user is below resource limits. If new_vm is defined + # checks if its requirements fit in limits + def check(user, new_vm=nil) + usage=@usage.total(user) + user_quota=get(user) + if new_vm + usage.cpu+=new_vm.cpu + usage.memory+=new_vm.memory + end + + STDERR.puts [user_quota, usage, new_vm].inspect + + (!user_quota[:cpu] || usage.cpu<=user_quota[:cpu]) && + (!user_quota[:memory] || usage.memory<=user_quota[:memory]) + end + + # Updates user resource consuption + def update(user) + @usage.update_user(user) + end + + # Get cache for the user + def get_user(user) + @usage.vms(user) + end +end + diff --git a/src/authm_mad/simple_auth.rb b/src/authm_mad/simple_auth.rb new file mode 100644 index 0000000000..793890c6c2 --- /dev/null +++ b/src/authm_mad/simple_auth.rb @@ -0,0 +1,33 @@ +# -------------------------------------------------------------------------- # +# 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. # +#--------------------------------------------------------------------------- # + + +class SimpleAuth + def initialize + end + + def auth(user_id, user, password, token) + STDERR.puts [user_id, user, password, token].inspect + STDERR.flush + t_user, t_password=token.split(':') + #auth=(user==t_user && password==t_password) + auth=(password==token) + auth="Invalid credentials" if auth!=true + auth + end +end + + diff --git a/src/authm_mad/simple_permissions.rb b/src/authm_mad/simple_permissions.rb new file mode 100644 index 0000000000..62f418b51b --- /dev/null +++ b/src/authm_mad/simple_permissions.rb @@ -0,0 +1,87 @@ + +require 'quota' +require 'base64' + +class SimplePermissions + + def initialize(database, client, conf={}) + @quota=Quota.new(database, client, conf[:quota] || {}) + end + + def auth_message(result, message) + result ? true : message + end + + def get_vm_usage(data) + vm_xml=Base64::decode64(data) + vm=OpenNebula::VirtualMachine.new(vm_xml) + vm_hash=vm.to_hash + + # Should set more sensible defaults or get driver configuration + cpu=vm_hash['TEMPLATE']['CPU'] + cpu||=1.0 + + memory=vm_hash['TEMPLATE']['MEMORY'] + memory||=64 + + VmUsage.new(cpu, memory) + end + + def auth(uid, tokens) + STDERR.puts [uid, tokens].inspect + + result=true + + tokens.each do |token| + object, id, action, owner, pub=token.split(':') + result=auth_object(uid.to_s, object, id, action, owner, pub) + break result if result!=true + end + + result + end + + def auth_object(uid, object, id, action, owner, pub) + return true if uid=='0' + + case object + when 'VM' + return auth_vm(uid, object, id, action, owner, pub) + when 'HOST' + return auth_host(uid, object, id, action, owner, pub) + else + return auth_generic(uid, object, id, action, owner, pub) + end + end + + def auth_vm(uid, object, id, action, owner, pub) + case action + when 'CREATE' + STDERR.puts "create vm" + if @quota.check(uid, get_vm_usage(id)) + return true + else + return "Quota exceeded" + end + else + auth_message(uid==owner, "You cannot manage VM #{id}") + end + end + + def auth_host(uid, object, id, action, owner, pub) + auth_message(action=='USE', 'Only oneadmin can manage hosts') + end + + def auth_generic(uid, object, id, action, owner, pub) + case action + when 'CREATE' + true + when 'USE' + auth_message(uid==owner || pub=='1', "You are not allowed to "<< + "#{action} #{object} #{id}") + else + auth_message(uid==owner, "You are not allowed to "<< + "#{action} #{object} #{id}") + end + end +end \ No newline at end of file diff --git a/src/authm_mad/spec/client_mock.rb b/src/authm_mad/spec/client_mock.rb new file mode 100644 index 0000000000..fed78630bd --- /dev/null +++ b/src/authm_mad/spec/client_mock.rb @@ -0,0 +1,55 @@ +# -------------------------------------------------------------------------- # +# 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. # +#--------------------------------------------------------------------------- # + +class ClientMock + def initialize(mock_data) + @mock_data=mock_data + end + + def search_method(methods, args) + keys=methods.keys + + if keys.include? args[0] + value=methods[args[0]] + if value.class != Hash + return value + elsif args.length>1 + return search_method(value, args[1..-1]) + else + nil + end + else + nil + end + end + + def call(action, *args) + value=search_method(@mock_data, [action]+args.flatten) + if value + if value.class==Proc + value.call(action, args.flatten) + else + value + end + else + message="Action '#{action}(#{args.join(',')})' not defined" + STDERR.puts message + OpenNebula::Error.new(message) + end + end +end + + diff --git a/src/authm_mad/spec/db_helpers.rb b/src/authm_mad/spec/db_helpers.rb new file mode 100644 index 0000000000..ea3ca3f7a5 --- /dev/null +++ b/src/authm_mad/spec/db_helpers.rb @@ -0,0 +1,25 @@ +# -------------------------------------------------------------------------- # +# 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. # +#--------------------------------------------------------------------------- # + +require 'rubygems' +require 'sequel' + +def check_column(schema, column) + schema.find {|c| c[0] == column }.should_not == nil +end + + + diff --git a/src/authm_mad/spec/oca_vms.yaml b/src/authm_mad/spec/oca_vms.yaml new file mode 100644 index 0000000000..b69377b77a --- /dev/null +++ b/src/authm_mad/spec/oca_vms.yaml @@ -0,0 +1,551 @@ + +vmpool.info: + 0: " + + + 0 + + + 0 + + + jfontan + + + test + + + 0 + + + 1 + + + 0 + + + 1278433840 + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 1 + + + 0 + + + jfontan + + + test + + + 0 + + + 1 + + + 0 + + + 1278433841 + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + " + 1: " + + + 2 + + + 1 + + + lero + + + test + + + 0 + + + 1 + + + 0 + + + 1278433868 + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 3 + + + 1 + + + lero + + + test + + + 0 + + + 1 + + + 0 + + + 1278433869 + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + " +vm.info: + 0: " + + 0 + + + 0 + + + test + + + 0 + + + 1 + + + 0 + + + 1278433840 + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + " + 1: " + + 1 + + + 0 + + + test + + + 0 + + + 1 + + + 0 + + + 1278433841 + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + " + 2: " + + 2 + + + 1 + + + test + + + 0 + + + 1 + + + 0 + + + 1278433868 + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + " + 3: " + + 3 + + + 1 + + + test + + + 0 + + + 1 + + + 0 + + + 1278433869 + + + 0 + + + + 0 + + + 0 + + + 0 + + + 0 + + + " \ No newline at end of file diff --git a/src/authm_mad/spec/one_usage_spec.rb b/src/authm_mad/spec/one_usage_spec.rb new file mode 100644 index 0000000000..f20b6d111d --- /dev/null +++ b/src/authm_mad/spec/one_usage_spec.rb @@ -0,0 +1,75 @@ +# -------------------------------------------------------------------------- # +# Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org) # +# # +# Licensed under the Apache License, Version 2.0 (the "License"); you may # +# not use this file except in compliance with the License. You may obtain # +# a copy of the License at # +# # +# http://www.apache.org/licenses/LICENSE-2.0 # +# # +# Unless required by applicable law or agreed to in writing, software # +# distributed under the License is distributed on an "AS IS" BASIS, # +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # +# See the License for the specific language governing permissions and # +# limitations under the License. # +#--------------------------------------------------------------------------- # + +require 'spec_common' + +require 'client_mock' +require 'one_usage' + +describe "OneUsage" do + before(:all) do + mock_data=YAML::load(File.read('spec/oca_vms.yaml')) + client=ClientMock.new(mock_data) + @one_usage=OneUsage.new(client) + end + + it "should get information about vm users" do + @one_usage.update_user(0) + vms=@one_usage.vms(0) + + vms.size.should == 2 + vms[0].cpu.should == 0.5 + vms[0].memory.should == 64 + vms[1].cpu.should == 1.0 + vms[1].memory.should == 256 + + usage=@one_usage.total(0) + usage.cpu.should == 1.5 + usage.memory.should == 64+256 + + @one_usage.update_user(1) + vms=@one_usage.vms(1) + + vms.size.should == 2 + vms[2].cpu.should == 1.5 + vms[2].memory.should == 512 + vms[3].cpu.should == 2.0 + vms[3].memory.should == 1024 + + usage=@one_usage.total(1) + usage.cpu.should == 3.5 + usage.memory.should == 512+1024 + end + + it "should update information" do + vms=@one_usage.vms(1) + vms[4]=VmUsage.new(4.0, 2048) + + usage=@one_usage.total(1) + usage.cpu.should == 1.5 + 2.0 + 4.0 + usage.memory.should == 512+1024+2048 + + vms.delete(3) + usage=@one_usage.total(1) + usage.cpu.should == 1.5 + 4.0 + usage.memory.should == 512+2048 + + @one_usage.update_user(1) + usage=@one_usage.total(1) + usage.cpu.should == 1.5 + 2.0 + usage.memory.should == 512+1024 + end +end diff --git a/src/authm_mad/spec/quota_spec.rb b/src/authm_mad/spec/quota_spec.rb new file mode 100644 index 0000000000..e4e796f888 --- /dev/null +++ b/src/authm_mad/spec/quota_spec.rb @@ -0,0 +1,95 @@ +# -------------------------------------------------------------------------- # +# 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. # +#--------------------------------------------------------------------------- # + +require 'spec_common' + +require 'client_mock' +require 'quota' + +def check_quota(uid, cpu, memory, num_vms) + quota=@quota.get(uid) + quota.should_not == nil + quota[:cpu].should == cpu + quota[:memory].should == memory + quota[:num_vms].should == num_vms +end + +describe 'Quota' do + before(:all) do + @db=Sequel.sqlite + mock_data=YAML::load(File.read('spec/oca_vms.yaml')) + client=ClientMock.new(mock_data) + @quota=Quota.new(@db, client) + end + + it 'should create table' do + @db.table_exists?(:quotas).should == true + + schema=@db.schema(:quotas) + check_column(schema, :uid) + check_column(schema, :cpu) + check_column(schema, :memory) + check_column(schema, :num_vms) + end + + it 'should let add and retrieve quotas' do + @quota.set(0, 10.0, 1024, 10) + @quota.set(1, 20.0, 2048, 20) + @quota.set(2, 40.0, 4096, 40) + + check_quota(0, 10.0, 1024, 10) + check_quota(1, 20.0, 2048, 20) + check_quota(2, 40.0, 4096, 40) + + @quota.get(3).should == @quota.defaults + end + + it 'should check for quotas' do + @quota.update(0) + @quota.update(1) + @quota.check(0).should == true + @quota.check(1).should == true + + vms=@quota.get_user(0) + vms[5]=VmUsage.new(40.0, 8192) + + vms=@quota.get_user(1) + vms[6]=VmUsage.new(40.0, 8192) + + @quota.check(0).should == false + @quota.check(1).should == false + + @quota.update(0) + @quota.update(1) + @quota.check(0).should == true + @quota.check(1).should == true + end + + it 'should let update limits' do + @quota.set(0, nil, nil, nil) + check_quota(0, nil, nil, nil) + end + + it 'should understand unlimited quotas' do + vms=@quota.get_user(0) + vms[7]=VmUsage.new(9999999999.0, 99999999999) + @quota.check(0).should == true + @quota.check(0, VmUsage.new(999999999.0, 99999999)).should == true + end + +end + + diff --git a/src/authm_mad/spec/simple_permissions_spec.rb b/src/authm_mad/spec/simple_permissions_spec.rb new file mode 100644 index 0000000000..67f6401c05 --- /dev/null +++ b/src/authm_mad/spec/simple_permissions_spec.rb @@ -0,0 +1,91 @@ +# -------------------------------------------------------------------------- # +# 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. # +#--------------------------------------------------------------------------- # + +require 'spec_common' + +require 'client_mock' +require 'simple_permissions' + +def gen_tokens(user_, action_, options={}) + user=user_.to_s + action=action_.to_s.upcase + + options={ + :vm => true, + :host => true + }.merge!(options) + + pub=(options[:public] ? '1' : '0') + id=(options[:id] ? options[:id].to_s : '1') + #owner=(options[:owner] ? options[:owner].to_s : '1') + + if action=='CREATE' + vmowner='-' + vmid='-' + else + vmowner=user + vmid=user + end + + tokens=[] + tokens<<"VM:#{vmid}:#{action}:#{vmowner}:#{pub}" if options[:vm] + tokens+=[ + "NET:#{id}:#{action}:#{user}:#{pub}", + "IMAGE:#{id}:#{action}:#{user}:#{pub}" + ] + tokens<<"HOST:#{id}:#{action}:#{user}:#{pub}" if options[:host] + + #pp tokens + + tokens +end + +describe SimplePermissions do + before(:all) do + @db=Sequel.sqlite + mock_data=YAML::load(File.read('spec/oca_vms.yaml')) + client=ClientMock.new(mock_data) + @perm=SimplePermissions.new(@db, client) + end + + it 'should let root manage everything' do + @perm.auth(0, gen_tokens(1, :create)).should == true + @perm.auth(0, gen_tokens(1, :delete)).should == true + @perm.auth(0, gen_tokens(1, :manage)).should == true + @perm.auth(0, gen_tokens(1, :use)).should == true + end + + it 'should let anyone use public objects' do + @perm.auth(2, gen_tokens(1, :delete, :public => true)). + should_not == true + @perm.auth(2, gen_tokens(1, :manage, :public => true)). + should_not == true + + # take out vm create (the first token) as it can not be "used" by + # other users even if public + @perm.auth(2, gen_tokens(1, :use, :public => true, :vm => false)). + should == true + end + + it 'should let users use their own objects' do + @perm.auth(1, gen_tokens(1, :create, :host => false)).should == true + @perm.auth(1, gen_tokens(1, :delete, :host => false)).should == true + @perm.auth(1, gen_tokens(1, :manage, :host => false)).should == true + @perm.auth(1, gen_tokens(1, :use)).should == true + end +end + + diff --git a/src/authm_mad/spec/spec_common.rb b/src/authm_mad/spec/spec_common.rb new file mode 100644 index 0000000000..7fffd828f0 --- /dev/null +++ b/src/authm_mad/spec/spec_common.rb @@ -0,0 +1,26 @@ +# -------------------------------------------------------------------------- # +# 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. # +#--------------------------------------------------------------------------- # + +require 'pp' + +require 'db_helpers' + +$: << '../oca/ruby' +$: << './spec' + + + + diff --git a/src/dm/DispatchManagerActions.cc b/src/dm/DispatchManagerActions.cc index b23eaa8fca..a82485f14e 100644 --- a/src/dm/DispatchManagerActions.cc +++ b/src/dm/DispatchManagerActions.cc @@ -18,18 +18,6 @@ #include "NebulaLog.h" #include "Nebula.h" -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -int DispatchManager::allocate ( - int uid, - const string& stemplate, - int * oid) -{ - NebulaLog::log("DiM",Log::DEBUG,"Allocating a new VM"); - - return vmpool->allocate(uid,stemplate,oid); -}; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ diff --git a/src/hm/HookManager.cc b/src/hm/HookManager.cc index 3071249761..1fa91e9dc1 100644 --- a/src/hm/HookManager.cc +++ b/src/hm/HookManager.cc @@ -34,28 +34,28 @@ extern "C" void * hm_action_loop(void *arg) NebulaLog::log("HKM",Log::INFO,"Hook Manager started."); hm = static_cast(arg); - + hm->am.loop(0,0); NebulaLog::log("HKM",Log::INFO,"Hook Manager stopped."); - + return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -void HookManager::load_mads(int uid) +void HookManager::load_mads(int uid) { HookManagerDriver * hm_mad; ostringstream oss; const VectorAttribute * vattr; int rc; - + NebulaLog::log("HKM",Log::INFO,"Loading Hook Manager driver."); - + vattr = static_cast(mad_conf[0]); - + if ( vattr == 0 ) { NebulaLog::log("HKM",Log::INFO,"Failed to load Hook Manager driver."); @@ -63,18 +63,18 @@ void HookManager::load_mads(int uid) } VectorAttribute hook_conf("HOOK_MAD",vattr->value()); - + hook_conf.replace("NAME",hook_driver_name); - + hm_mad = new HookManagerDriver(0,hook_conf.value(),false,vmpool); - + rc = add(hm_mad); - + if ( rc == 0 ) { - oss.str(""); + oss.str(""); oss << "\tHook Manager loaded"; - + NebulaLog::log("HKM",Log::INFO,oss); } } @@ -95,7 +95,7 @@ int HookManager::start() } NebulaLog::log("HKM",Log::INFO,"Starting Hook Manager..."); - + pthread_attr_init (&pattr); pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE); @@ -112,14 +112,14 @@ void HookManager::do_action(const string &action, void * arg) if (action == ACTION_FINALIZE) { NebulaLog::log("HKM",Log::INFO,"Stopping Hook Manager..."); - - MadManager::stop(); + + MadManager::stop(); } else { ostringstream oss; oss << "Unknown action name: " << action; - + NebulaLog::log("HKM", Log::ERROR, oss); } } diff --git a/src/host/ClusterPool.cc b/src/host/ClusterPool.cc index 350dc0e01a..ff91cc98e2 100644 --- a/src/host/ClusterPool.cc +++ b/src/host/ClusterPool.cc @@ -15,6 +15,7 @@ /* -------------------------------------------------------------------------- */ #include "ClusterPool.h" +#include "NebulaLog.h" const char * ClusterPool::table = "cluster_pool"; @@ -31,10 +32,11 @@ const string ClusterPool::DEFAULT_CLUSTER_NAME = "default"; int ClusterPool::allocate(int * clid, string name, SqlDB *db) { - int rc; - + int rc; map::iterator it; + ostringstream oss; + // Return error if name already exists for(it=cluster_names.begin();it!=cluster_names.end();it++) { @@ -56,10 +58,20 @@ int ClusterPool::allocate(int * clid, string name, SqlDB *db) return *clid; -// TODO: LOG ERRORS + error_existing_name: + oss << "Could not allocate new cluster: Name \"" + << name << "\" already exists."; + + goto error_common; error_db: + oss << "Could not allocate new cluster \"" << name + << "\": Database returned error code " << rc << "."; + goto error_common; + error_common: + NebulaLog::log("CLUSTER", Log::ERROR, oss); + *clid = -1; return *clid; } diff --git a/src/host/test/HostPoolTest.cc b/src/host/test/HostPoolTest.cc index b2630bd40e..5d72de6f9b 100644 --- a/src/host/test/HostPoolTest.cc +++ b/src/host/test/HostPoolTest.cc @@ -336,7 +336,8 @@ public: } // Discover the enabled hosts - rc = hp->discover(&dh, 100); + rc = hp->discover(&dh,100); + CPPUNIT_ASSERT(rc == 0); CPPUNIT_ASSERT(dh.size() == 8); diff --git a/src/image/Image.cc b/src/image/Image.cc index 3b419df06b..fd983e6d7b 100644 --- a/src/image/Image.cc +++ b/src/image/Image.cc @@ -25,12 +25,14 @@ #include "Image.h" #include "ImagePool.h" +#include "AuthManager.h" +#include "UserPool.h" /* ************************************************************************ */ /* Image :: Constructor/Destructor */ /* ************************************************************************ */ -Image::Image(int _uid): +Image::Image(int _uid, ImageTemplate * _image_template): PoolObjectSQL(-1), uid(_uid), name(""), @@ -39,9 +41,24 @@ Image::Image(int _uid): source(""), state(INIT), running_vms(0) - {}; +{ + if (_image_template != 0) + { + image_template = _image_template; + } + else + { + image_template = new ImageTemplate; + } +}; -Image::~Image(){}; +Image::~Image() +{ + if (image_template != 0) + { + delete image_template; + } +}; /* ************************************************************************ */ /* Image :: Database Access Functions */ @@ -91,7 +108,7 @@ int Image::select_cb(void * nil, int num, char **values, char ** names) running_vms = atoi(values[RUNNING_VMS]); - image_template.id = oid; + image_template->id = oid; return 0; } @@ -121,7 +138,7 @@ int Image::select(SqlDB *db) // Get the template - rc = image_template.select(db); + rc = image_template->select(db); if ( rc != 0 ) { @@ -180,7 +197,7 @@ int Image::insert(SqlDB *db) // ------------ PUBLIC -------------------- get_template_attribute("PUBLIC", public_attr); - image_template.erase("PUBLIC"); + image_template->erase("PUBLIC"); transform (public_attr.begin(), public_attr.end(), public_attr.begin(), (int(*)(int))toupper); @@ -196,7 +213,7 @@ int Image::insert(SqlDB *db) SingleAttribute * dev_att = new SingleAttribute("DEV_PREFIX", ImagePool::default_dev_prefix()); - image_template.set(dev_att); + image_template->set(dev_att); } // ------------ SOURCE (path to store the image)-------------------- @@ -208,29 +225,31 @@ int Image::insert(SqlDB *db) source = tmp_sourcestream.str(); + // ------------ INSERT THE TEMPLATE -------------------- - // Set up the template ID, to insert it - if ( image_template.id == -1 ) + if ( image_template->id == -1 ) { - image_template.id = oid; + image_template->id = oid; } state = DISABLED; - // Insert the Template - rc = image_template.insert(db); + rc = image_template->insert(db); if ( rc != 0 ) { return rc; } - //Insert the Image + //-------------------------------------------------------------------------- + // Insert the Image + //-------------------------------------------------------------------------- + rc = insert_replace(db, false); if ( rc != 0 ) { - image_template.drop(db); + image_template->drop(db); return rc; } @@ -240,9 +259,11 @@ int Image::insert(SqlDB *db) error_name: NebulaLog::log("IMG", Log::ERROR, "NAME not present in image template"); goto error_common; + error_type: NebulaLog::log("IMG", Log::ERROR, "Incorrect TYPE in image template"); goto error_common; + error_common: return -1; } @@ -368,7 +389,7 @@ int Image::drop(SqlDB * db) return -1; } - image_template.drop(db); + image_template->drop(db); oss << "DELETE FROM " << table << " WHERE oid=" << oid; @@ -418,7 +439,7 @@ string& Image::to_xml(string& xml) const "" << source << "" << "" << state << "" << "" << running_vms << "" << - image_template.to_xml(template_xml) << + image_template->to_xml(template_xml) << ""; xml = oss.str(); @@ -446,7 +467,7 @@ string& Image::to_str(string& str) const "STATE = " << state << endl << "RUNNING_VMS = " << running_vms << endl << "TEMPLATE" << endl - << image_template.to_str(template_str) + << image_template->to_str(template_str) << endl; str = os.str(); @@ -529,12 +550,10 @@ int Image::disk_attribute(VectorAttribute * disk, int * index) { string overwrite; string saveas; - string name; string bus; ostringstream iid; - name = disk->vector_value("NAME"); overwrite = disk->vector_value("OVERWRITE"); saveas = disk->vector_value("SAVE_AS"); bus = disk->vector_value("BUS"); @@ -564,10 +583,9 @@ int Image::disk_attribute(VectorAttribute * disk, int * index) map new_disk; - new_disk.insert(make_pair("NAME",name)); - new_disk.insert(make_pair("IID", iid.str())); - - new_disk.insert(make_pair("SOURCE", source)); + new_disk.insert(make_pair("IMAGE", name)); + new_disk.insert(make_pair("IMAGE_ID", iid.str())); + new_disk.insert(make_pair("SOURCE", source)); if (!overwrite.empty()) { diff --git a/src/image/ImagePool.cc b/src/image/ImagePool.cc index da71fb9d98..6982dda21b 100644 --- a/src/image/ImagePool.cc +++ b/src/image/ImagePool.cc @@ -19,6 +19,7 @@ /* ************************************************************************** */ #include "ImagePool.h" +#include "AuthManager.h" /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -88,55 +89,31 @@ ImagePool::ImagePool( SqlDB * db, int ImagePool::allocate ( int uid, - const string& stemplate, + ImageTemplate* img_template, int * oid) { - int rc; Image * img; - string name; - char * error_msg; // --------------------------------------------------------------------- // Build a new Image object // --------------------------------------------------------------------- - img = new Image(uid); - - // --------------------------------------------------------------------- - // Parse template - // --------------------------------------------------------------------- - rc = img->image_template.parse(stemplate, &error_msg); - - if ( rc != 0 ) - { - ostringstream oss; - oss << "ImagePool template parse error: " << error_msg; - NebulaLog::log("IMG", Log::ERROR, oss); - - free(error_msg); - delete img; - - return -1; - } + img = new Image(uid,img_template); img->get_template_attribute("NAME", name); // --------------------------------------------------------------------- // Insert the Object in the pool // --------------------------------------------------------------------- - *oid = PoolSQL::allocate(img); - if ( *oid == -1 ) - { - return -1; - } - // --------------------------------------------------------------------- // Add the image name to the map of image_names // --------------------------------------------------------------------- - - image_names.insert(make_pair(name, *oid)); + if ( *oid != -1 ) + { + image_names.insert(make_pair(name, *oid)); + } return *oid; } @@ -187,3 +164,96 @@ int ImagePool::dump(ostringstream& oss, const string& where) /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ + +int ImagePool::disk_attribute(VectorAttribute * disk, int * index) +{ + string source; + Image * img = 0; + + source = disk->vector_value("IMAGE"); + + if (source.empty()) + { + istringstream is; + int image_id; + + source = disk->vector_value("IMAGE_ID"); + + if (source.empty()) + { + return -2; + } + + is.str(source); + is >> image_id; + + if( !is.fail() ) + { + img = get(image_id,true); + } + } + else + { + img = get(source,true); + } + + if (img == 0) + { + return -1; + } + + int rc = img->disk_attribute(disk,index); + + img->unlock(); + + return rc; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void ImagePool::authorize_disk(VectorAttribute * disk, AuthRequest * ar) +{ + string source; + Image * img = 0; + + source = disk->vector_value("IMAGE"); + + if (source.empty()) + { + istringstream is; + int image_id; + + source = disk->vector_value("IMAGE_ID"); + + if (source.empty()) + { + return; + } + + is.str(source); + is >> image_id; + + if( !is.fail() ) + { + img = get(image_id,true); + } + } + else + { + img = get(source,true); + } + + if (img == 0) + { + return; + } + + ar->add_auth(AuthRequest::IMAGE, + img->get_iid(), + AuthRequest::USE, + img->get_uid(), + img->isPublic()); + + img->unlock(); +} diff --git a/src/image/test/ImagePoolTest.cc b/src/image/test/ImagePoolTest.cc index a883c070d0..b7b097bbaa 100644 --- a/src/image/test/ImagePoolTest.cc +++ b/src/image/test/ImagePoolTest.cc @@ -65,6 +65,40 @@ const string xml_dump_where = const string replacement = "0000000000"; +class ImagePoolFriend : public ImagePool +{ +public: + ImagePoolFriend(SqlDB * db, + const string& _source_prefix, + const string& _default_type, + const string& _default_dev_prefix): + + ImagePool( db, + _source_prefix, + _default_type, + _default_dev_prefix){}; + + + int allocate(const int& uid, const std::string& stemplate, int* oid) + { + ImageTemplate * img_template; + char * error_msg = 0; + int rc; + + img_template = new ImageTemplate; + rc = img_template->parse(stemplate,&error_msg); + + if( rc == 0 ) + { + return ImagePool::allocate(uid, img_template, oid); + } + else + { + return -2; + } + }; +}; + /* ************************************************************************* */ /* ************************************************************************* */ @@ -86,6 +120,7 @@ class ImagePoolTest : public PoolTest CPPUNIT_TEST ( bus_source_assignment ); CPPUNIT_TEST ( public_attribute ); CPPUNIT_TEST ( disk_overwrite ); + CPPUNIT_TEST ( imagepool_disk_attribute ); CPPUNIT_TEST ( dump ); CPPUNIT_TEST ( dump_where ); @@ -100,13 +135,15 @@ protected: PoolSQL* create_pool(SqlDB* db) { - return new ImagePool(db, "source_prefix", "OS", "hd"); + ImagePoolFriend * imp = + new ImagePoolFriend(db, "source_prefix", "OS", "hd"); + return imp; }; int allocate(int index) { int oid; - return ((ImagePool*)pool)->allocate(uids[index], + return ((ImagePoolFriend*)pool)->allocate(uids[index], templates[index], &oid); @@ -320,7 +357,7 @@ public: void duplicates() { int rc, oid; - ImagePool * imp = static_cast(pool); + ImagePoolFriend * imp = static_cast(pool); // Allocate an image. rc = imp->allocate(uids[0], templates[0], &oid); @@ -371,7 +408,7 @@ public: void wrong_templates() { int rc; - ImagePool * imp = static_cast(pool); + ImagePoolFriend * imp = static_cast(pool); string templates[] = { @@ -410,7 +447,7 @@ public: void target_generation() { - ImagePool * imp = static_cast(pool); + ImagePoolFriend * imp = static_cast(pool); Image * img; VectorAttribute * disk; @@ -682,13 +719,85 @@ public: delete disk; } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + + void imagepool_disk_attribute() + { + ImagePoolFriend * imp = static_cast(pool); + Image * img; + + VectorAttribute * disk; + int oid_0, oid_1; + string value; + + // --------------------------------------------------------------------- + // Allocate 2 images, with different dev_prefix + + string template_0 = "NAME = \"Image 0\"\n" + "DEV_PREFIX = \"hd\"\n"; + + string template_1 = "NAME = \"Image 1\"\n" + "DEV_PREFIX = \"sd\"\n"; + + + imp->allocate(0, template_0, &oid_0); + CPPUNIT_ASSERT( oid_0 == 0 ); + + imp->allocate(0, template_1, &oid_1); + CPPUNIT_ASSERT( oid_1 == 1 ); + + + img = imp->get(oid_0, false); + CPPUNIT_ASSERT( img != 0 ); + img->enable(true); + + img = imp->get(oid_1, false); + CPPUNIT_ASSERT( img != 0 ); + img->enable(true); + + + // Disk using image 0 + disk = new VectorAttribute("DISK"); + disk->replace("IMAGE", "Image 0"); + + ((ImagePool*)imp)->disk_attribute(disk, 0); + + value = ""; + value = disk->vector_value("TARGET"); + CPPUNIT_ASSERT( value == "hda" ); + + value = ""; + value = disk->vector_value("IMAGE_ID"); + CPPUNIT_ASSERT( value == "0" ); + + delete disk; + + + // Disk using image 1 index + disk = new VectorAttribute("DISK"); + disk->replace("IMAGE_ID", "1"); + + ((ImagePool*)imp)->disk_attribute(disk, 0); + + value = ""; + value = disk->vector_value("TARGET"); + CPPUNIT_ASSERT( value == "sda" ); + + value = ""; + value = disk->vector_value("IMAGE"); + CPPUNIT_ASSERT( value == "Image 1" ); + + delete disk; + } + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ void public_attribute() { int oid; - ImagePool * imp = static_cast(pool); + ImagePoolFriend * imp = static_cast(pool); Image * img; string templates[] = @@ -754,7 +863,8 @@ public: img = imp->get( oid, false ); CPPUNIT_ASSERT( img != 0 ); //cout << endl << i << " : exp. " << results[i] << " got " << img->is_public(); - CPPUNIT_ASSERT( img->is_public() == results[i] ); + + CPPUNIT_ASSERT( img->isPublic() == results[i] ); i++; } diff --git a/src/image/test/SConstruct b/src/image/test/SConstruct index bf11121dbb..34f67f44a3 100644 --- a/src/image/test/SConstruct +++ b/src/image/test/SConstruct @@ -51,6 +51,7 @@ main_env.Append(LIBPATH=[ cwd + '/src/mad', cwd + '/src/vnm', cwd + '/src/um', + cwd + '/src/authm', cwd + '/src/image', '/usr/include/openssl/', ]) @@ -59,11 +60,12 @@ main_env.Append(LIBS=[ 'nebula_image', 'nebula_um', 'nebula_vm', - 'nebula_mad', 'nebula_hm', 'nebula_vnm', + 'nebula_authm', 'nebula_template', 'nebula_pool', + 'nebula_mad', 'nebula_common', 'nebula_log', 'nebula_core', diff --git a/src/nebula/Nebula.cc b/src/nebula/Nebula.cc index 9ae00b5a9a..d6ab6b64d3 100644 --- a/src/nebula/Nebula.cc +++ b/src/nebula/Nebula.cc @@ -233,19 +233,19 @@ void Nebula::start() vnpool = new VirtualNetworkPool(db,mac_prefix,size); upool = new UserPool(db); - + nebula_configuration->get("IMAGE_REPOSITORY_PATH", repository_path); - + if (repository_path.empty()) // Defaults to ONE_LOCATION/var { repository_path = var_location; } - + nebula_configuration->get("DEFAULT_IMAGE_TYPE", default_image_type); nebula_configuration->get("DEFAULT_DEVICE_PREFIX", default_device_prefix); - - ipool = new ImagePool(db, + + ipool = new ImagePool(db, repository_path, default_image_type, default_device_prefix); @@ -447,6 +447,38 @@ void Nebula::start() throw runtime_error("Could not start the Hook Manager"); } + // ---- Auth Manager ---- + try + { + vector auth_mads; + + nebula_configuration->get("AUTH_MAD", auth_mads); + + if (!auth_mads.empty()) + { + //Defaults 60s to timeout auth requests + authm = new AuthManager(timer_period,60,auth_mads); + } + else + { + authm = 0; //Built-in authm/authz + } + } + catch (bad_alloc&) + { + throw; + } + + if (authm != 0) + { + rc = authm->start(); + + if ( rc != 0 ) + { + throw runtime_error("Could not start the Auth Manager"); + } + } + // ----------------------------------------------------------- // Load mads // ----------------------------------------------------------- @@ -459,6 +491,11 @@ void Nebula::start() tm->load_mads(0); hm->load_mads(0); + if ( authm != 0 ) + { + authm->load_mads(0); + } + // ----------------------------------------------------------- // Wait for a SIGTERM or SIGINT signal // ----------------------------------------------------------- diff --git a/src/nebula/SConstruct b/src/nebula/SConstruct index b6943c3b91..ebc9f8145b 100644 --- a/src/nebula/SConstruct +++ b/src/nebula/SConstruct @@ -40,6 +40,7 @@ env.Append(LIBS=[ 'nebula_dm', 'nebula_tm', 'nebula_um', + 'nebula_authm', 'nebula_mad', 'nebula_template', 'nebula_image', diff --git a/src/rm/RequestManager.cc b/src/rm/RequestManager.cc index b983902807..a3f4b3af39 100644 --- a/src/rm/RequestManager.cc +++ b/src/rm/RequestManager.cc @@ -214,7 +214,7 @@ void RequestManager::do_action( void RequestManager::register_xml_methods() { xmlrpc_c::methodPtr vm_allocate(new - RequestManager::VirtualMachineAllocate(upool)); + RequestManager::VirtualMachineAllocate(vmpool, vnpool, ipool, upool)); xmlrpc_c::methodPtr vm_deploy(new RequestManager::VirtualMachineDeploy(vmpool,hpool,upool)); @@ -282,9 +282,6 @@ void RequestManager::register_xml_methods() xmlrpc_c::methodPtr user_allocate(new RequestManager::UserAllocate(upool)); - xmlrpc_c::methodPtr user_info(new - RequestManager::UserInfo(upool)); - xmlrpc_c::methodPtr user_delete(new RequestManager::UserDelete(upool)); @@ -357,7 +354,6 @@ void RequestManager::register_xml_methods() /* User related methods*/ RequestManagerRegistry.addMethod("one.user.allocate", user_allocate); - RequestManagerRegistry.addMethod("one.user.info", user_info); RequestManagerRegistry.addMethod("one.user.delete", user_delete); RequestManagerRegistry.addMethod("one.userpool.info", userpool_info); diff --git a/src/rm/RequestManagerAction.cc b/src/rm/RequestManagerAction.cc index af279c87cf..11ff2f1b9e 100644 --- a/src/rm/RequestManagerAction.cc +++ b/src/rm/RequestManagerAction.cc @@ -42,6 +42,8 @@ void RequestManager::VirtualMachineAction::execute( VirtualMachine * vm; ostringstream oss; + + const string method_name = "VirtualMachineAction"; NebulaLog::log("ReM",Log::DEBUG,"VirtualMachineAction invoked"); @@ -49,7 +51,6 @@ void RequestManager::VirtualMachineAction::execute( 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); @@ -58,21 +59,34 @@ void RequestManager::VirtualMachineAction::execute( goto error_vm_get; } - uid = vm->get_uid(); - + uid = vm->get_uid(); + vm->unlock(); - // Only oneadmin or the VM owner can perform operations upon the VM + //Authenticate the user rc = VirtualMachineAction::upool->authenticate(session); - - if ( rc != 0 && rc != uid) - { - goto error_authenticate; + + 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); + rc = dm->shutdown(vid); } else if (action == "hold") { @@ -108,13 +122,12 @@ void RequestManager::VirtualMachineAction::execute( } else { - rc = -3; + rc = -3; } if (rc != 0) { goto error_operation; - } arrayData.push_back(xmlrpc_c::value_boolean(true)); @@ -139,24 +152,28 @@ error_operation: goto error_common; error_vm_get: - oss << "The virtual machine " << vid << " does not exists"; + oss.str(get_error(method_name, "VM", vid)); goto error_common; error_authenticate: - oss << "User not authorized to perform operation upon VirtualMachine [" << vid << "]"; + 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 285f6c4d9b..f51d7c8470 100644 --- a/src/rm/RequestManagerAllocate.cc +++ b/src/rm/RequestManagerAllocate.cc @@ -27,55 +27,103 @@ void RequestManager::VirtualMachineAllocate::execute( xmlrpc_c::value * const retval) { string session; - string username; - string password; - string vm_template; + string str_template; - int vid; - int uid; + const string method_name = "VirtualMachineAllocate"; + + int vid, uid; int rc; - Nebula& nd = Nebula::instance(); - DispatchManager * dm = nd.get_dm(); - - User * user; - ostringstream oss; vector arrayData; xmlrpc_c::value_array * arrayresult; + VirtualMachineTemplate * vm_template; + 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)); - vm_template = xmlrpc_c::value_string(paramList.getString(1)); - vm_template += "\n"; + 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); - // First, we need to authenticate the user - rc = VirtualMachineAllocate::upool->authenticate(session); - - if ( rc == -1 ) + if (uid == -1) { goto error_authenticate; } - User::split_secret(session,username,password); + //-------------------------------------------------------------------------- + // Authorize this request + //-------------------------------------------------------------------------- + vm_template = new VirtualMachineTemplate; - // Now let's get the user - user = VirtualMachineAllocate::upool->get(username,true); + rc = vm_template->parse(str_template,&error_msg); - if ( user == 0 ) + if ( rc != 0 ) { - goto error_get_user; + goto error_parse; } - uid = user->get_uid(); + if ( uid != 0 ) + { + AuthRequest ar(uid); + string t64; - user->unlock(); + num = vm_template->get("DISK",vectors); - rc = dm->allocate(uid,vm_template,&vid); + for(int i=0; i(vectors[i]); + + if ( vector == 0 ) + { + continue; + } + + VirtualMachineAllocate::ipool->authorize_disk(vector,&ar); + } + + num = vm_template->get("NIC",vectors); + + for(int i=0; i(vectors[i]); + + if ( vector == 0 ) + { + continue; + } + + VirtualMachineAllocate::vnpool->authorize_nic(vector,&ar); + } + + ar.add_auth(AuthRequest::VM, + vm_template->to_xml(t64), + AuthRequest::CREATE, + uid, + false); + + if (UserPool::authorize(ar) == -1) + { + goto error_authorize; + } + } + + //-------------------------------------------------------------------------- + // Allocate the VirtualMAchine + //-------------------------------------------------------------------------- + rc = VirtualMachineAllocate::vmpool->allocate(uid,vm_template,&vid,false); if ( rc < 0 ) { @@ -92,26 +140,30 @@ void RequestManager::VirtualMachineAllocate::execute( delete arrayresult; // and get rid of the original - return; error_authenticate: - oss << "User not authenticated, aborting RequestManagerAllocate call."; + oss.str(authenticate_error(method_name)); goto error_common; -error_get_user: - oss << "User not recognized, cannot allocate VirtualMachine"; +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: - if (rc == -1) - { - oss << "Error inserting VM in the database, check oned.log"; - } - else - { - oss << "Error parsing VM template"; - } + oss.str(action_error(method_name, "CREATE", "VM", -2, rc)); goto error_common; error_common: diff --git a/src/rm/RequestManagerCancel.cc b/src/rm/RequestManagerCancel.cc index 2175ee720f..85322e3e0f 100644 --- a/src/rm/RequestManagerCancel.cc +++ b/src/rm/RequestManagerCancel.cc @@ -23,21 +23,23 @@ 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 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(); @@ -47,62 +49,75 @@ void RequestManager::VirtualMachineCancel::execute( session = xmlrpc_c::value_string(paramList.getString(0)); vid = xmlrpc_c::value_int (paramList.getInt(1)); - - // Retrieve the VM from the vmpool + // Retrieve the VM from the vmpool vm = VirtualMachineCancel::vmpool->get(vid,true); - - if ( vm == 0 ) - { - goto error_vm_get; + + if ( vm == 0 ) + { + goto error_vm_get; } - + uid = vm->get_uid(); vm->unlock(); - // Only oneadmin or the VM owner can perform operations upon the VM + //Authenticate the user rc = VirtualMachineCancel::upool->authenticate(session); - - if ( rc != 0 && rc != uid) - { - goto error_authenticate; + + 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 << "User not authorized to cancel VM"; + 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 << "Error getting vm for cancelling with VID = " << vid; + 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); - + + Nebula::log("ReM",Log::ERROR,oss); + xmlrpc_c::value_array arrayresult_error(arrayData); *retval = arrayresult_error; - + return; } diff --git a/src/rm/RequestManagerClusterAdd.cc b/src/rm/RequestManagerClusterAdd.cc index ec5a8642f5..b42f156e61 100644 --- a/src/rm/RequestManagerClusterAdd.cc +++ b/src/rm/RequestManagerClusterAdd.cc @@ -17,6 +17,8 @@ #include "RequestManager.h" #include "NebulaLog.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -29,6 +31,8 @@ void RequestManager::ClusterAdd::execute( int hid; int clid; int rc; + + const string method_name = "ClusterAdd"; Host * host; @@ -45,15 +49,28 @@ void RequestManager::ClusterAdd::execute( hid = xmlrpc_c::value_int (paramList.getInt(1)); clid = xmlrpc_c::value_int (paramList.getInt(2)); - - // Only oneadmin can add hosts to clusters + //Authenticate the user rc = ClusterAdd::upool->authenticate(session); - if ( rc != 0 ) + 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 host exists host = ClusterAdd::hpool->get(hid,true); @@ -87,18 +104,20 @@ void RequestManager::ClusterAdd::execute( return; error_authenticate: - oss << "User not authorized to add hosts to clusters"; + 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: - oss << "The host " << hid << " does not exists"; + oss.str(get_error(method_name, "HOST", hid)); goto error_common; error_cluster_add: host->unlock(); - - oss << "Can not add host " << hid << " to cluster " << clid << - ", returned error code [" << rc << "]"; + oss.str(action_error(method_name, "USE", "CLUSTER", clid, rc)); goto error_common; error_common: diff --git a/src/rm/RequestManagerClusterAllocate.cc b/src/rm/RequestManagerClusterAllocate.cc index ed77dea253..be09bdf110 100644 --- a/src/rm/RequestManagerClusterAllocate.cc +++ b/src/rm/RequestManagerClusterAllocate.cc @@ -17,6 +17,8 @@ #include "RequestManager.h" #include "NebulaLog.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -27,8 +29,9 @@ void RequestManager::ClusterAllocate::execute( string session; string clustername; - int id; + + const string method_name = "ClusterAllocate"; int rc; ostringstream oss; @@ -43,14 +46,27 @@ void RequestManager::ClusterAllocate::execute( session = xmlrpc_c::value_string(paramList.getString(0)); clustername = xmlrpc_c::value_string(paramList.getString(1)); - // Only oneadmin can add new clusters + //Authenticate the user rc = ClusterAllocate::upool->authenticate(session); - if ( rc != 0 ) + 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::hpool->allocate_cluster(&id, clustername); @@ -71,12 +87,15 @@ void RequestManager::ClusterAllocate::execute( return; error_authenticate: - oss << "User not authorized to add new clusters"; + 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 << "Can not allocate cluster " << clustername << - " in the ClusterPool, returned error code [" << rc << "]"; + oss.str(action_error(method_name, "CREATE", "CLUSTER", -2, rc)); goto error_common; error_common: @@ -84,8 +103,8 @@ 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); - + NebulaLog::log("ReM",Log::ERROR,oss); + xmlrpc_c::value_array arrayresult_error(arrayData); *retval = arrayresult_error; diff --git a/src/rm/RequestManagerClusterDelete.cc b/src/rm/RequestManagerClusterDelete.cc index 728da90d64..ddfcee56e3 100644 --- a/src/rm/RequestManagerClusterDelete.cc +++ b/src/rm/RequestManagerClusterDelete.cc @@ -17,6 +17,8 @@ #include "RequestManager.h" #include "NebulaLog.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -29,7 +31,9 @@ void RequestManager::ClusterDelete::execute( // of the cluster to delete from the HostPool int clid; ostringstream oss; - int rc; + int rc; + + const string method_name = "ClusterDelete"; /* -- RPC specific vars -- */ vector arrayData; @@ -41,14 +45,27 @@ void RequestManager::ClusterDelete::execute( session = xmlrpc_c::value_string(paramList.getString(0)); clid = xmlrpc_c::value_int (paramList.getInt(1)); - // Only oneadmin can delete clusters + //Authenticate the user rc = ClusterDelete::upool->authenticate(session); - if ( rc != 0 ) + 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; + } + } + rc = ClusterDelete::hpool->drop_cluster(clid); if ( rc != 0 ) @@ -68,12 +85,15 @@ void RequestManager::ClusterDelete::execute( return; error_authenticate: - oss << "User not authorized to delete clusters"; + 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_delete: - oss << "Can not delete cluster with CLID " << clid << - " from the ClusterPool, returned error code [" << rc << "]"; + oss.str(action_error(method_name, "DELETE", "CLUSTER", clid, rc)); goto error_common; error_common: diff --git a/src/rm/RequestManagerClusterInfo.cc b/src/rm/RequestManagerClusterInfo.cc index 2059858548..c11208b56f 100644 --- a/src/rm/RequestManagerClusterInfo.cc +++ b/src/rm/RequestManagerClusterInfo.cc @@ -17,6 +17,8 @@ #include "RequestManager.h" #include "NebulaLog.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -29,6 +31,8 @@ void RequestManager::ClusterInfo::execute( int clid; int rc; + + const string method_name = "ClusterInfo"; ostringstream oss; @@ -42,7 +46,7 @@ void RequestManager::ClusterInfo::execute( session = xmlrpc_c::value_string(paramList.getString(0)); clid = xmlrpc_c::value_int (paramList.getInt(1)); - // Check if it is a valid user + //Authenticate the user rc = ClusterInfo::upool->authenticate(session); if ( rc == -1 ) @@ -71,11 +75,11 @@ void RequestManager::ClusterInfo::execute( return; error_authenticate: - oss << "User not authenticated, ClusterInfo call aborted."; + oss.str(authenticate_error(method_name)); goto error_common; error_cluster: - oss << "Error getting cluster with CLID = " << clid; + oss.str(get_error(method_name, "CLUSTER", clid)); goto error_common; error_common: diff --git a/src/rm/RequestManagerClusterPoolInfo.cc b/src/rm/RequestManagerClusterPoolInfo.cc index 0742be92cd..7974fca010 100755 --- a/src/rm/RequestManagerClusterPoolInfo.cc +++ b/src/rm/RequestManagerClusterPoolInfo.cc @@ -17,6 +17,8 @@ #include "RequestManager.h" #include "NebulaLog.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -26,7 +28,9 @@ void RequestManager::ClusterPoolInfo::execute( { string session; ostringstream oss; - int rc; + int rc; + + const string method_name = "ClusterPoolInfo"; /* -- RPC specific vars -- */ vector arrayData; @@ -37,8 +41,7 @@ void RequestManager::ClusterPoolInfo::execute( // Get the parameters session = xmlrpc_c::value_string(paramList.getString(0)); - - // Check if it is a valid user + //Authenticate the user rc = ClusterPoolInfo::upool->authenticate(session); if ( rc == -1 ) @@ -46,7 +49,7 @@ void RequestManager::ClusterPoolInfo::execute( goto error_authenticate; } - // Perform the allocation in the vmpool + // Perform the allocation in the vmpool rc = ClusterPoolInfo::hpool->dump_cluster(oss); if ( rc != 0 ) @@ -69,11 +72,11 @@ void RequestManager::ClusterPoolInfo::execute( return; error_authenticate: - oss << "User not authenticated, RequestManagerClusterPoolInfo aborted."; + oss.str(authenticate_error(method_name)); goto error_common; error_dump: - oss << "Error getting Cluster pool"; + oss.str(get_error(method_name, "CLUSTER", -1)); goto error_common; error_common: @@ -81,7 +84,7 @@ 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); + NebulaLog::log("ReM",Log::ERROR,oss); xmlrpc_c::value_array arrayresult_error(arrayData); diff --git a/src/rm/RequestManagerClusterRemove.cc b/src/rm/RequestManagerClusterRemove.cc index af02c1ab75..573e1aeb00 100644 --- a/src/rm/RequestManagerClusterRemove.cc +++ b/src/rm/RequestManagerClusterRemove.cc @@ -17,6 +17,8 @@ #include "RequestManager.h" #include "NebulaLog.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -24,12 +26,14 @@ void RequestManager::ClusterRemove::execute( xmlrpc_c::paramList const& paramList, xmlrpc_c::value * const retval) { - string session; + string session; + + int hid; + int rc; + + const string method_name = "ClusterRemove"; - int hid; - int rc; - - Host * host; + Host * host; ostringstream oss; @@ -43,15 +47,26 @@ void RequestManager::ClusterRemove::execute( session = xmlrpc_c::value_string(paramList.getString(0)); hid = xmlrpc_c::value_int (paramList.getInt(1)); - - // Only oneadmin can remove hosts from clusters + // Only oneadmin can delete clusters rc = ClusterRemove::upool->authenticate(session); - if ( rc != 0 ) + 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); @@ -86,22 +101,23 @@ void RequestManager::ClusterRemove::execute( return; error_authenticate: - oss << "User not authorized to remove hosts from clusters"; + 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 << "The host " << hid << " does not exists"; + oss.str(get_error(method_name, "HOST", hid)); goto error_common; error_cluster_remove: host->unlock(); - - oss << "Can not remove host " << hid << " from its cluster, " - << "returned error code [" << rc << "]"; + 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())); diff --git a/src/rm/RequestManagerDeploy.cc b/src/rm/RequestManagerDeploy.cc index 8b49d42ed7..a921a85d7d 100644 --- a/src/rm/RequestManagerDeploy.cc +++ b/src/rm/RequestManagerDeploy.cc @@ -37,6 +37,8 @@ void RequestManager::VirtualMachineDeploy::execute( string tm_mad; string vmdir; + const string method_name = "VirtualMachineDeploy"; + VirtualMachine * vm; Host * host; @@ -56,10 +58,7 @@ void RequestManager::VirtualMachineDeploy::execute( vid = xmlrpc_c::value_int(paramList.getInt(1)); hid = xmlrpc_c::value_int(paramList.getInt(2)); - //We also need the hsid - //Get host info to deploy the VM - host = VirtualMachineDeploy::hpool->get(hid,true); if ( host == 0 ) @@ -76,7 +75,6 @@ void RequestManager::VirtualMachineDeploy::execute( host->unlock(); //Get the VM - vm = VirtualMachineDeploy::vmpool->get(vid,true); if ( vm == 0 ) @@ -86,21 +84,34 @@ void RequestManager::VirtualMachineDeploy::execute( uid = vm->get_uid(); - // Only oneadmin or the VM owner can perform operations upon the VM - rc = VirtualMachineDeploy::upool->authenticate(session); - - if ( rc != 0 && rc != uid) - { - goto error_authenticate; - } - if ( vm->get_state() != VirtualMachine::PENDING ) { goto error_state; } - //Update host info and share usage (cpu,mem....) + //Authenticate the user + rc = VirtualMachineDeploy::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; + } + } + + //Update host info and share usage (cpu,mem....) vm->add_history(hid,hostname,vmdir,vmm_mad,tm_mad); rc = VirtualMachineDeploy::vmpool->update_history(vm); @@ -113,13 +124,11 @@ void RequestManager::VirtualMachineDeploy::execute( vmpool->update(vm); //Insert last_seq in the DB //Deploy the VM - dm->deploy(vm); vm->unlock(); // Send results to client - arrayData.push_back(xmlrpc_c::value_boolean(true)); arrayresult = new xmlrpc_c::value_array(arrayData); @@ -130,36 +139,40 @@ void RequestManager::VirtualMachineDeploy::execute( return; -error_authenticate: - vm->unlock(); - oss << "User not authorized to perform the deploy"; - goto error_common; - error_host_get: - oss << "The host " << hid << " does not exists"; + oss.str(get_error(method_name, "HOST", hid)); goto error_common; error_vm_get: - oss << "The virtual machine " << vid << " does not exists"; - goto error_common; - -error_history: - vm->unlock(); - - oss << "Can not deploy VM " << vid << ", can not insert history"; + oss.str(get_error(method_name, "VM", vid)); goto error_common; error_state: - vm->unlock(); + oss << action_error(method_name, "MANAGE", "VM", vid, -1) + << ". Reason: VM in wrong state."; + goto error_common_lock; - oss << "Can not deploy VM " << vid << ", wrong state"; - 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", rc, vid)); + goto error_common_lock; + +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; diff --git a/src/rm/RequestManagerHostAllocate.cc b/src/rm/RequestManagerHostAllocate.cc index 7d3393f4d0..e94296624c 100644 --- a/src/rm/RequestManagerHostAllocate.cc +++ b/src/rm/RequestManagerHostAllocate.cc @@ -17,23 +17,27 @@ #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 im_mad_name; + string vmm_mad_name; string tm_mad_name; + + const string method_name = "HostAllocate"; - int hid; + int hid; - int rc; + int rc; ostringstream oss; /* -- RPC specific vars -- */ @@ -49,25 +53,39 @@ void RequestManager::HostAllocate::execute( vmm_mad_name = xmlrpc_c::value_string(paramList.getString(3)); tm_mad_name = xmlrpc_c::value_string(paramList.getString(4)); - // Only oneadmin can add new hosts + //Authenticate the user rc = HostAllocate::upool->authenticate(session); - - if ( rc != 0 ) - { - goto error_authenticate; + + 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, + im_mad_name, vmm_mad_name, - tm_mad_name); - if ( rc == -1 ) - { - goto error_host_allocate; + tm_mad_name); + if ( rc == -1 ) + { + goto error_host_allocate; } - - // All nice, return the new hid to client + + // 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); @@ -79,25 +97,26 @@ void RequestManager::HostAllocate::execute( return; error_authenticate: - oss << "User not authorized to add new hosts"; + 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 << "Can not allocate host " << hostname << - " in the HostPool, returned error code [" << rc << "]"; + oss.str(action_error(method_name, "CREATE", "HOST", -2, 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); - + + 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 index 9bafd227d2..0a453a8f56 100644 --- a/src/rm/RequestManagerHostDelete.cc +++ b/src/rm/RequestManagerHostDelete.cc @@ -17,20 +17,24 @@ #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; + int hid; Host * host; ostringstream oss; - int rc; + int rc; + + const string method_name = "HostDelete"; /* -- RPC specific vars -- */ vector arrayData; @@ -41,31 +45,44 @@ void RequestManager::HostDelete::execute( // Get the parameters session = xmlrpc_c::value_string(paramList.getString(0)); hid = xmlrpc_c::value_int (paramList.getInt(1)); - - // Only oneadmin can delete hosts + + //Authenticate the user rc = HostDelete::upool->authenticate(session); - - if ( rc != 0 ) - { - goto error_authenticate; + + if ( rc == -1 ) + { + goto error_authenticate; } - - // Perform the allocation in the hostpool - host = HostDelete::hpool->get(hid,true); - - if ( host == 0 ) - { - goto error_host_get; + + //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 allocation in the hostpool + host = HostDelete::hpool->get(hid,true); + + if ( host == 0 ) + { + goto error_host_get; + } + rc = HostDelete::hpool->drop(host); host->unlock(); - // All nice, return the host info to the client + // All nice, return the host info to the client arrayData.push_back(xmlrpc_c::value_boolean( rc == 0 )); // SUCCESS arrayresult = new xmlrpc_c::value_array(arrayData); - + // Copy arrayresult into retval mem space *retval = *arrayresult; // and get rid of the original @@ -74,11 +91,15 @@ void RequestManager::HostDelete::execute( return; error_authenticate: - oss << "User not authorized to delete hosts"; + 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 << "Error getting host with HID = " < arrayData; + vector arrayData; xmlrpc_c::value_array * arrayresult; NebulaLog::log("ReM",Log::DEBUG,"HostEnable method invoked"); @@ -43,39 +47,51 @@ void RequestManager::HostEnable::execute( hid = xmlrpc_c::value_int(paramList.getInt(1)); enable = xmlrpc_c::value_boolean(paramList.getBoolean(2)); - // Only oneadmin can enable hosts + //Authenticate the user rc = HostEnable::upool->authenticate(session); - - if ( rc != 0) - { - goto error_authenticate; + + if ( rc == -1 ) + { + goto error_authenticate; } - host = HostEnable::hpool->get(hid,true); - - if ( host == 0 ) - { - goto error_host_get; + //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(); + host->enable(); } else { - host->disable(); + 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; @@ -83,15 +99,19 @@ void RequestManager::HostEnable::execute( return; error_authenticate: - oss << "Only oneadmin can enable hosts"; + 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 << "Error getting host with HID = " << hid; + oss.str(get_error(method_name, "HOST", hid)); goto error_common; error_common: - NebulaLog::log("ReM",Log::ERROR,oss); + NebulaLog::log("ReM",Log::ERROR,oss); arrayData.push_back(xmlrpc_c::value_boolean(false)); arrayData.push_back(xmlrpc_c::value_string(oss.str())); @@ -99,7 +119,7 @@ error_common: xmlrpc_c::value_array arrayresult_error(arrayData); *retval = arrayresult_error; - + return; } diff --git a/src/rm/RequestManagerHostInfo.cc b/src/rm/RequestManagerHostInfo.cc index b586d59675..f6b351b2d6 100644 --- a/src/rm/RequestManagerHostInfo.cc +++ b/src/rm/RequestManagerHostInfo.cc @@ -23,14 +23,16 @@ void RequestManager::HostInfo::execute( xmlrpc_c::paramList const& paramList, xmlrpc_c::value * const retval) -{ - string session; +{ + string session; + + int hid; + int rc; + Host * host; - int hid; - int rc; - Host * host; - ostringstream oss; + + const string method_name = "HostInfo"; /* -- RPC specific vars -- */ vector arrayData; @@ -42,7 +44,7 @@ void RequestManager::HostInfo::execute( session = xmlrpc_c::value_string(paramList.getString(0)); hid = xmlrpc_c::value_int (paramList.getInt(1)); - // Check if it is a valid user + //Authenticate the user rc = HostInfo::upool->authenticate(session); if ( rc == -1 ) @@ -51,18 +53,18 @@ void RequestManager::HostInfo::execute( } // Get the host from the HostPool - host = HostInfo::hpool->get(hid,true); - - if ( host == 0 ) - { - goto error_host_get; + 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 + + // 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())); @@ -75,24 +77,23 @@ void RequestManager::HostInfo::execute( return; error_authenticate: - oss << "User not authenticated, HostInfo call aborted."; + oss.str(authenticate_error(method_name)); goto error_common; error_host_get: - oss << "Error getting host with HID = " << hid; + 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); - + + 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 index ba598a803d..babb66b745 100755 --- a/src/rm/RequestManagerHostPoolInfo.cc +++ b/src/rm/RequestManagerHostPoolInfo.cc @@ -23,11 +23,13 @@ void RequestManager::HostPoolInfo::execute( xmlrpc_c::paramList const& paramList, xmlrpc_c::value * const retval) -{ +{ string session; ostringstream oss; - int rc; - + int rc; + + const string method_name = "HostPoolInfo"; + /* -- RPC specific vars -- */ vector arrayData; xmlrpc_c::value_array * arrayresult; @@ -37,8 +39,7 @@ void RequestManager::HostPoolInfo::execute( // Get the parameters session = xmlrpc_c::value_string(paramList.getString(0)); - - // Check if it is a valid user + //Authenticate the user rc = HostPoolInfo::upool->authenticate(session); if ( rc == -1 ) @@ -46,16 +47,16 @@ void RequestManager::HostPoolInfo::execute( goto error_authenticate; } - // Perform the allocation in the vmpool + // 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 + + //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); @@ -69,24 +70,24 @@ void RequestManager::HostPoolInfo::execute( return; error_authenticate: - oss << "User not authenticated, RequestManagerHostPoolInfo aborted."; + oss.str(authenticate_error(method_name)); goto error_common; error_dump: - oss << "Error getting host pool"; + 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); - + + NebulaLog::log("ReM",Log::ERROR,oss); + xmlrpc_c::value_array arrayresult_error(arrayData); *retval = arrayresult_error; - + return; } diff --git a/src/rm/RequestManagerImageAllocate.cc b/src/rm/RequestManagerImageAllocate.cc index ce266d3a6d..84e1fd287f 100644 --- a/src/rm/RequestManagerImageAllocate.cc +++ b/src/rm/RequestManagerImageAllocate.cc @@ -15,10 +15,12 @@ /* -------------------------------------------------------------------------- */ #include "RequestManager.h" -#include "NebulaLog.h" +#include "NebulaLog.h" #include "Nebula.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -27,36 +29,76 @@ void RequestManager::ImageAllocate::execute( xmlrpc_c::value * const retval) { string session; - string image_template; + string str_template; + + ImageTemplate * img_template; int iid; int uid; int rc; + char * error_msg = 0; ostringstream oss; + const string method_name = "ImageAllocate"; + vector arrayData; xmlrpc_c::value_array * arrayresult; - NebulaLog::log("ReM",Log::DEBUG,"ImageAllocate invoked"); - session = xmlrpc_c::value_string(paramList.getString(0)); - image_template = xmlrpc_c::value_string(paramList.getString(1)); - image_template += "\n"; + session = xmlrpc_c::value_string(paramList.getString(0)); + str_template = xmlrpc_c::value_string(paramList.getString(1)); + str_template += "\n"; + //-------------------------------------------------------------------------- + // Authorize this request + //-------------------------------------------------------------------------- + uid = ImageAllocate::upool->authenticate(session); - // First, we need to authenticate the user - rc = ImageAllocate::upool->authenticate(session); - - if ( rc == -1 ) + if ( uid == -1 ) { goto error_authenticate; } - - uid = rc; - rc = ImageAllocate::ipool->allocate(uid,image_template,&iid); + //-------------------------------------------------------------------------- + // 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; + } + } + + //-------------------------------------------------------------------------- + // Allocate the Image + //-------------------------------------------------------------------------- + rc = ImageAllocate::ipool->allocate(uid,img_template,&iid); if ( rc < 0 ) { @@ -76,18 +118,27 @@ void RequestManager::ImageAllocate::execute( return; error_authenticate: - oss << "User not authenticated, aborting ImageAllocate call."; + 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: - if (rc == -1) - { - oss << "Error allocating image, check oned.log"; - } - else - { - oss << "Error parsing image template"; - } + oss.str(action_error(method_name, "CREATE", "IMAGE", -2, rc)); goto error_common; error_common: diff --git a/src/rm/RequestManagerImageDelete.cc b/src/rm/RequestManagerImageDelete.cc index f56473f114..20875bf5f7 100644 --- a/src/rm/RequestManagerImageDelete.cc +++ b/src/rm/RequestManagerImageDelete.cc @@ -15,10 +15,12 @@ /* -------------------------------------------------------------------------- */ #include "RequestManager.h" -#include "NebulaLog.h" +#include "NebulaLog.h" #include "Nebula.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -31,10 +33,15 @@ void RequestManager::ImageDelete::execute( 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; @@ -47,15 +54,13 @@ void RequestManager::ImageDelete::execute( // First, we need to authenticate the user - rc = ImageDelete::upool->authenticate(session); + uid = ImageDelete::upool->authenticate(session); - if ( rc == -1 ) + if ( uid == -1 ) { goto error_authenticate; } - - uid = rc; - + // Get image from the ImagePool image = ImageDelete::ipool->get(iid,true); @@ -63,10 +68,35 @@ void RequestManager::ImageDelete::execute( { goto error_image_get; } - - if ( uid != 0 && uid != image->get_uid() ) + + image_owner = image->get_uid(); + is_public = image->isPublic(); + + image->unlock(); + + //Authorize the operation + if ( uid != 0 ) // uid == 0 means oneadmin { - goto error_authorization; + AuthRequest ar(uid); + + ar.add_auth(AuthRequest::IMAGE, + iid, + AuthRequest::DELETE, + image_owner, + is_public); + + if (UserPool::authorize(ar) == -1) + { + goto error_authorize; + } + } + + // Get image from the ImagePool + image = ImageDelete::ipool->get(iid,true); + + if ( image == 0 ) + { + goto error_image_get; } rc = ImageDelete::ipool->drop(image); @@ -91,20 +121,20 @@ void RequestManager::ImageDelete::execute( return; error_authenticate: - oss << "User not authenticated, aborting ImageDelete call."; + oss.str(authenticate_error(method_name)); goto error_common; error_image_get: - oss << "Error getting image with ID = " << iid; + oss.str(get_error(method_name, "IMAGE", iid)); goto error_common; -error_authorization: - oss << "User not authorized to delete image, aborting ImageDelete call."; - image->unlock(); +error_authorize: + oss.str(authorization_error(method_name, "DELETE", "IMAGE", uid, iid)); goto error_common; error_delete: - oss << "Cannot delete image, VMs might be running on it."; + oss << action_error(method_name, "DELETE", "IMAGE", iid, rc) + << ". Reason: VMs might be running on it."; image->unlock(); goto error_common; diff --git a/src/rm/RequestManagerImageEnable.cc b/src/rm/RequestManagerImageEnable.cc index 6d5cec9dcb..498875fb28 100644 --- a/src/rm/RequestManagerImageEnable.cc +++ b/src/rm/RequestManagerImageEnable.cc @@ -15,10 +15,12 @@ /* -------------------------------------------------------------------------- */ #include "RequestManager.h" -#include "NebulaLog.h" +#include "NebulaLog.h" #include "Nebula.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -33,9 +35,14 @@ void RequestManager::ImageEnable::execute( 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; @@ -48,15 +55,13 @@ void RequestManager::ImageEnable::execute( enable_flag = xmlrpc_c::value_boolean(paramList.getBoolean(2)); // First, we need to authenticate the user - rc = ImageEnable::upool->authenticate(session); + uid = ImageEnable::upool->authenticate(session); - if ( rc == -1 ) + if ( uid == -1 ) { goto error_authenticate; } - uid = rc; - // Get image from the ImagePool image = ImageEnable::ipool->get(iid,true); @@ -65,11 +70,36 @@ void RequestManager::ImageEnable::execute( goto error_image_get; } - if ( uid != 0 && uid != image->get_uid() ) + image_owner = image->get_uid(); + is_public = image->isPublic(); + + image->unlock(); + + //Authorize the operation + if ( uid != 0 ) // uid == 0 means oneadmin { - goto error_authorization; - } + 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 = ImageEnable::ipool->get(iid,true); + + if ( image == 0 ) + { + goto error_image_get; + } + rc = image->enable(enable_flag); if ( rc < 0 ) @@ -94,21 +124,19 @@ void RequestManager::ImageEnable::execute( return; error_authenticate: - oss << "[ImageEnable] User not authenticated, aborting call."; + oss.str(authenticate_error(method_name)); goto error_common; error_image_get: - oss << "[ImageEnable] Error getting image with ID = " << iid; + oss.str(get_error(method_name, "IMAGE", iid)); goto error_common; -error_authorization: - oss << "[ImageEnable] User not authorized to enable/disable image" << - " attributes, aborting call."; - image->unlock(); +error_authorize: + oss.str(authorization_error(method_name, "MANAGE", "IMAGE", uid, iid)); goto error_common; error_enable: - oss << "[ImageEnable] Cannot enable/disable image [" << iid << "]"; + oss.str(action_error(method_name, "ENABLE/DISABLE", "IMAGE", iid, rc)); image->unlock(); goto error_common; diff --git a/src/rm/RequestManagerImageInfo.cc b/src/rm/RequestManagerImageInfo.cc index 37beb6927c..9359460887 100644 --- a/src/rm/RequestManagerImageInfo.cc +++ b/src/rm/RequestManagerImageInfo.cc @@ -17,21 +17,25 @@ #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 uid; - int rc; - Image * image; - + int iid; + int uid; // Image owner user id + int rc; // Requesting user id + Image * image; + ostringstream oss; + + const string method_name = "ImageInfo"; /* -- RPC specific vars -- */ vector arrayData; @@ -42,30 +46,30 @@ void RequestManager::ImageInfo::execute( // Get the parameters session = xmlrpc_c::value_string(paramList.getString(0)); iid = xmlrpc_c::value_int (paramList.getInt(1)); - + // Get image from the ImagePool - image = ImageInfo::ipool->get(iid,true); - - if ( image == 0 ) - { - goto error_image_get; + image = ImageInfo::ipool->get(iid,true); + + if ( image == 0 ) + { + goto error_image_get; } - + uid = image->get_uid(); // Check if it is a valid user rc = ImageInfo::upool->authenticate(session); - if ( rc != 0 && rc != uid && !image->is_public()) - { - goto error_authenticate; + if ( rc == -1 ) + { + goto error_authenticate; } oss << *image; - + image->unlock(); - - // All nice, return the host info to the client + + // 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())); @@ -76,28 +80,26 @@ void RequestManager::ImageInfo::execute( delete arrayresult; // and get rid of the original return; - + error_image_get: - oss << "Error getting image with ID = " << iid; + oss.str(get_error(method_name, "IMAGE", iid)); goto error_common; error_authenticate: - oss << "User doesn't exist, or not authorized to use image with " << - "ID = " << iid << " , ImageInfo call aborted."; + oss.str(authenticate_error(method_name)); 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); - + + 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 index e1880b4fc7..d634243c3e 100755 --- a/src/rm/RequestManagerImagePoolInfo.cc +++ b/src/rm/RequestManagerImagePoolInfo.cc @@ -32,6 +32,8 @@ void RequestManager::ImagePoolInfo::execute( int rc; int uid; int filter_flag; + + const string method_name = "ImagePoolInfo"; /* -- RPC specific vars -- */ vector arrayData; @@ -44,14 +46,12 @@ void RequestManager::ImagePoolInfo::execute( filter_flag = xmlrpc_c::value_int(paramList.getInt(1)); // Check if it is a valid user - rc = ImagePoolInfo::upool->authenticate(session); + uid = ImagePoolInfo::upool->authenticate(session); - if ( rc == -1 ) + if ( uid == -1 ) { goto error_authenticate; } - - uid = rc; where_string.str(""); @@ -68,21 +68,13 @@ void RequestManager::ImagePoolInfo::execute( switch(filter_flag) { case -2: - if ( uid != 0 ) - { - goto error_authorization; - } + // TODO define authentication bug #278 // where remains empty. break; case -1: where_string << "UID=" << uid << " OR public = 'YES'"; break; default: - // Only oneadmin or the user can list a specific user's images. - if ( uid != 0 && uid != filter_flag ) - { - goto error_authorization; - } where_string << "UID=" << filter_flag; } @@ -109,23 +101,18 @@ void RequestManager::ImagePoolInfo::execute( return; error_authenticate: - oss << "User not authenticated, ImagePoolInfo call aborted."; + oss.str(authenticate_error(method_name)); goto error_common; -error_authorization: - oss << "User not authorized to perform this operation."; - goto error_common; - error_filter_flag: oss << "Incorrect filter_flag, must be >= -2."; goto error_common; error_dump: - oss << "Error getting image pool"; + 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())); diff --git a/src/rm/RequestManagerImagePublish.cc b/src/rm/RequestManagerImagePublish.cc index f88c328b72..9137766983 100644 --- a/src/rm/RequestManagerImagePublish.cc +++ b/src/rm/RequestManagerImagePublish.cc @@ -15,10 +15,12 @@ /* -------------------------------------------------------------------------- */ #include "RequestManager.h" -#include "NebulaLog.h" +#include "NebulaLog.h" #include "Nebula.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -31,11 +33,15 @@ void RequestManager::ImagePublish::execute( int iid; bool publish_flag; int uid; - int rc; + + int image_owner; + bool is_public; Image * image; ostringstream oss; + + const string method_name = "ImagePublish"; vector arrayData; xmlrpc_c::value_array * arrayresult; @@ -48,15 +54,13 @@ void RequestManager::ImagePublish::execute( publish_flag = xmlrpc_c::value_boolean(paramList.getBoolean(2)); // First, we need to authenticate the user - rc = ImagePublish::upool->authenticate(session); + uid = ImagePublish::upool->authenticate(session); - if ( rc == -1 ) + if ( uid == -1 ) { goto error_authenticate; } - uid = rc; - // Get image from the ImagePool image = ImagePublish::ipool->get(iid,true); @@ -65,11 +69,36 @@ void RequestManager::ImagePublish::execute( goto error_image_get; } - if ( uid != 0 && uid != image->get_uid() ) + image_owner = image->get_uid(); + is_public = image->isPublic(); + + image->unlock(); + + //Authorize the operation + if ( uid != 0 ) // uid == 0 means oneadmin { - goto error_authorization; - } + 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; + } + image->publish(publish_flag); ImagePublish::ipool->update(image); @@ -88,17 +117,15 @@ void RequestManager::ImagePublish::execute( return; error_authenticate: - oss << "[ImagePublish] User not authenticated, aborting call."; + oss.str(authenticate_error(method_name)); goto error_common; error_image_get: - oss << "[ImagePublish] Error getting image with ID = " << iid; + oss.str(get_error(method_name, "IMAGE", iid)); goto error_common; -error_authorization: - oss << "[ImagePublish] User not authorized to publish/unpublish image" << - ", aborting call."; - image->unlock(); +error_authorize: + oss.str(authorization_error(method_name, "MANAGE", "IMAGE", uid, iid)); goto error_common; error_common: diff --git a/src/rm/RequestManagerImageRemoveAttribute.cc b/src/rm/RequestManagerImageRemoveAttribute.cc index 348fefb4bf..a86d05882b 100644 --- a/src/rm/RequestManagerImageRemoveAttribute.cc +++ b/src/rm/RequestManagerImageRemoveAttribute.cc @@ -15,10 +15,12 @@ /* -------------------------------------------------------------------------- */ #include "RequestManager.h" -#include "NebulaLog.h" +#include "NebulaLog.h" #include "Nebula.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -32,10 +34,15 @@ void RequestManager::ImageRemoveAttribute::execute( 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; @@ -48,15 +55,13 @@ void RequestManager::ImageRemoveAttribute::execute( name = xmlrpc_c::value_string(paramList.getString(2)); // First, we need to authenticate the user - rc = ImageRemoveAttribute::upool->authenticate(session); + uid = ImageRemoveAttribute::upool->authenticate(session); - if ( rc == -1 ) + if ( uid == -1 ) { goto error_authenticate; } - - uid = rc; - + // Get image from the ImagePool image = ImageRemoveAttribute::ipool->get(iid,true); @@ -64,11 +69,35 @@ void RequestManager::ImageRemoveAttribute::execute( { goto error_image_get; } - - - if ( uid != 0 && uid != image->get_uid() ) + + image_owner = image->get_uid(); + is_public = image->isPublic(); + + image->unlock(); + + //Authorize the operation + if ( uid != 0 ) // uid == 0 means oneadmin { - goto error_authorization; + 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 = ImageRemoveAttribute::ipool->remove_attribute(image, name); @@ -92,22 +121,19 @@ void RequestManager::ImageRemoveAttribute::execute( return; error_authenticate: - oss << "[ImageRemoveAttribute] User not authenticated, aborting call."; + oss.str(authenticate_error(method_name)); goto error_common; error_image_get: - oss << "[ImageRemoveAttribute] Error getting image with ID = " << iid; + oss.str(get_error(method_name, "IMAGE", iid)); goto error_common; -error_authorization: - oss << "[ImageRemoveAttribute] User not authorized to remove image" << - " attributes aborting call."; - image->unlock(); +error_authorize: + oss.str(authorization_error(method_name, "MANAGE", "IMAGE", uid, iid)); goto error_common; error_remove_attribute: - oss << "[ImageRemoveAttribute] Cannot remove attribute with name = " - << name << " for image [" << iid << "]"; + oss.str(action_error(method_name, "PUBLISH/UNPUBLISH", "IMAGE", iid, rc)); image->unlock(); goto error_common; diff --git a/src/rm/RequestManagerImageUpdate.cc b/src/rm/RequestManagerImageUpdate.cc index 780eac63f4..acc6eef587 100644 --- a/src/rm/RequestManagerImageUpdate.cc +++ b/src/rm/RequestManagerImageUpdate.cc @@ -15,10 +15,12 @@ /* -------------------------------------------------------------------------- */ #include "RequestManager.h" -#include "NebulaLog.h" +#include "NebulaLog.h" #include "Nebula.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -33,6 +35,9 @@ void RequestManager::ImageUpdate::execute( string name; string value; int rc; + + int image_owner; + bool is_public; Image * image; @@ -40,7 +45,8 @@ void RequestManager::ImageUpdate::execute( vector arrayData; xmlrpc_c::value_array * arrayresult; - + + const string method_name = "ImageUpdate"; NebulaLog::log("ReM",Log::DEBUG,"ImageUpdate invoked"); @@ -50,15 +56,13 @@ void RequestManager::ImageUpdate::execute( value = xmlrpc_c::value_string(paramList.getString(3)); // First, we need to authenticate the user - rc = ImageUpdate::upool->authenticate(session); + uid = ImageUpdate::upool->authenticate(session); - if ( rc == -1 ) + if ( uid == -1 ) { goto error_authenticate; } - - uid = rc; - + // Get image from the ImagePool image = ImageUpdate::ipool->get(iid,true); @@ -66,10 +70,35 @@ void RequestManager::ImageUpdate::execute( { goto error_image_get; } - - if ( uid != 0 && uid != image->get_uid() ) + + image_owner = image->get_uid(); + is_public = image->isPublic(); + + image->unlock(); + + //Authorize the operation + if ( uid != 0 ) // uid == 0 means oneadmin { - goto error_authorization; + 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; } // This will perform the update on the DB as well, @@ -95,21 +124,19 @@ void RequestManager::ImageUpdate::execute( return; error_authenticate: - oss << "User not authenticated, aborting ImageUpdate call."; + oss.str(authenticate_error(method_name)); goto error_common; error_image_get: - oss << "Error getting image with ID = " << iid; + oss.str(get_error(method_name, "IMAGE", iid)); goto error_common; -error_authorization: - oss << "User not authorized to modify image attributes " << - ", aborting ImageUpdate call."; - image->unlock(); +error_authorize: + oss.str(authorization_error(method_name, "MANAGE", "IMAGE", uid, iid)); goto error_common; error_update: - oss << "Cannot modify image [" << iid << "] attribute with name = " << name; + oss.str(action_error(method_name, "UPDATE ATTRIBUTE", "IMAGE", iid, rc)); image->unlock(); goto error_common; diff --git a/src/rm/RequestManagerInfo.cc b/src/rm/RequestManagerInfo.cc index 35574ad663..1fed884046 100644 --- a/src/rm/RequestManagerInfo.cc +++ b/src/rm/RequestManagerInfo.cc @@ -23,13 +23,15 @@ void RequestManager::VirtualMachineInfo::execute( xmlrpc_c::paramList const& paramList, xmlrpc_c::value * const retval) -{ +{ string session; - int vid; + int vid, rc; VirtualMachine * vm; - ostringstream oss; + ostringstream oss; + + const string method_name = "VirtualMachineInfo"; /* -- RPC specific vars -- */ vector arrayData; @@ -41,19 +43,27 @@ void RequestManager::VirtualMachineInfo::execute( session = xmlrpc_c::value_string(paramList.getString(0)); vid = xmlrpc_c::value_int (paramList.getInt(1)); - // Get the details of the virtual machine + // Check if it is a valid user + rc = VirtualMachineInfo::upool->authenticate(session); + + if ( rc == -1 ) + { + goto error_authenticate; + } + + // Get the details of the virtual machine vm = VirtualMachineInfo::vmpool->get(vid,true); - if ( vm == 0 ) - { - goto error_vm_get; + if ( vm == 0 ) + { + goto error_vm_get; } - + oss << *vm; - + vm->unlock(); - - // All nice, return the vm info to the client + + // 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())); @@ -65,21 +75,24 @@ void RequestManager::VirtualMachineInfo::execute( return; +error_authenticate: + oss.str(authenticate_error(method_name)); + goto error_common; + error_vm_get: - oss << "Error getting vm with VID = " << vid; + 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); - + + NebulaLog::log("ReM",Log::ERROR,oss); + xmlrpc_c::value_array arrayresult_error(arrayData); *retval = arrayresult_error; - + return; } diff --git a/src/rm/RequestManagerMigrate.cc b/src/rm/RequestManagerMigrate.cc index 5b60552dcd..cd03ab3e67 100644 --- a/src/rm/RequestManagerMigrate.cc +++ b/src/rm/RequestManagerMigrate.cc @@ -48,18 +48,18 @@ void RequestManager::VirtualMachineMigrate::execute( 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 deploy the VM - + //Get host info to migrate the VM host = VirtualMachineMigrate::hpool->get(hid,true); if ( host == 0 ) @@ -76,7 +76,6 @@ void RequestManager::VirtualMachineMigrate::execute( host->unlock(); //Get the VM and migrate it - vm = VirtualMachineMigrate::vmpool->get(vid,true); if ( vm == 0 ) @@ -89,11 +88,25 @@ void RequestManager::VirtualMachineMigrate::execute( // Only oneadmin or the VM owner can perform operations upon the VM rc = VirtualMachineMigrate::upool->authenticate(session); - if ( rc != 0 && rc != uid) + 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)) { @@ -123,7 +136,6 @@ void RequestManager::VirtualMachineMigrate::execute( vm->unlock(); // Send results to client - arrayData.push_back(xmlrpc_c::value_boolean(true)); arrayresult = new xmlrpc_c::value_array(arrayData); @@ -134,33 +146,36 @@ void RequestManager::VirtualMachineMigrate::execute( return; -error_authenticate: - vm->unlock(); - oss << "User not authorized to perform migration upon this VM"; - goto error_common; error_host_get: - oss << "The host " << hid << " does not exists"; + oss.str(get_error(method_name, "HOST", hid)); goto error_common; error_vm_get: - oss << "The virtual machine " << vid << " does not exists"; + 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: - vm->unlock(); - - oss << "Can not migrate VM " << vid << ", can not insert history"; - goto error_common; + oss.str(action_error(method_name, "INSERT HISTORY", "VM", vid, rc)); + goto error_common_lock; error_state: - vm->unlock(); + oss << action_error(method_name, "MANAGE", "VM", vid, rc) + << ". Reason: VM in wrong state."; + goto error_common_lock; - oss << "Can not migrate VM " << vid << ", wrong state"; - goto error_common; +error_common_lock: + vm->unlock(); error_common: - arrayData.push_back(xmlrpc_c::value_boolean(false)); arrayData.push_back(xmlrpc_c::value_string(oss.str())); diff --git a/src/rm/RequestManagerPoolInfo.cc b/src/rm/RequestManagerPoolInfo.cc index 7461ff9d39..ba4d4dfd5c 100644 --- a/src/rm/RequestManagerPoolInfo.cc +++ b/src/rm/RequestManagerPoolInfo.cc @@ -23,22 +23,22 @@ void RequestManager::VirtualMachinePoolInfo::execute( xmlrpc_c::paramList const& paramList, xmlrpc_c::value * const retval) -{ +{ string session; string username; string password; int filter_flag; int rc; - + ostringstream oss; ostringstream where_string; - User * user; - /* -- RPC specific vars -- */ vector arrayData; xmlrpc_c::value_array * arrayresult; + + const string method_name = "VirtualMachinePoolInfo"; NebulaLog::log("ReM",Log::DEBUG,"VirtualMachinePoolInfo method invoked"); @@ -54,43 +54,28 @@ void RequestManager::VirtualMachinePoolInfo::execute( goto error_authenticate; } - where_string.str(""); - - /** Filter flag meaning table + /* Filter flag meaning table * <=-2 :: ALL VMs * -1 :: User's VMs * >=0 :: UID User's VMs - **/ + */ if (filter_flag == -1) { - User::split_secret(session,username,password); - - // Now let's get the user - user = VirtualMachinePoolInfo::upool->get(username,true); - - if ( user == 0 ) - { - goto error_get_user; - } - - where_string << "UID=" << user->get_uid(); - - user->unlock(); + where_string << "UID=" << rc; } else if (filter_flag>=0) - { - where_string << "UID=" << filter_flag; - } + { + where_string << "UID=" << filter_flag; + } - // Perform the allocation in the vmpool rc = VirtualMachinePoolInfo::vmpool->dump(oss,where_string.str()); - + if ( rc != 0 ) - { + { goto error_dump; } - - // All nice, return the vm info to the client + + // 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())); @@ -103,30 +88,25 @@ void RequestManager::VirtualMachinePoolInfo::execute( return; error_authenticate: - oss << "User not authenticated, aborting RequestManagerPoolInfo call."; - goto error_common; - -error_get_user: - oss << "An error ocurred getting the user from the UserPool, aborting RequestManagerPoolInfo call"; + oss.str(authenticate_error(method_name)); goto error_common; error_dump: - oss << "Error getting the pool info"; + 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; - + return; } /* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ \ No newline at end of file diff --git a/src/rm/RequestManagerUserAllocate.cc b/src/rm/RequestManagerUserAllocate.cc index 63aa6d18af..d3ada755d8 100644 --- a/src/rm/RequestManagerUserAllocate.cc +++ b/src/rm/RequestManagerUserAllocate.cc @@ -17,25 +17,29 @@ #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 password; + int uid; - int rc; + int rc; ostringstream oss; User * user; + const string method_name = "UserAllocate"; + /* -- RPC specific vars -- */ vector arrayData; xmlrpc_c::value_array * arrayresult; @@ -44,16 +48,32 @@ void RequestManager::UserAllocate::execute( // 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)); - - // Only oneadmin can add users + rc = UserAllocate::upool->authenticate(session); - - if ( rc != 0 ) - { - goto error_authenticate; + + 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 @@ -63,51 +83,54 @@ void RequestManager::UserAllocate::execute( { goto error_duplicate; } - + // Now let's add the user rc = UserAllocate::upool->allocate(&uid,username,password,true); - - if ( rc == -1 ) - { - goto error_allocate; - } - - // All nice, return the new uid to client + + 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 << "User not authorized to add new users"; - goto error_common; - -error_duplicate: - oss << "Existing user, cannot duplicate"; + 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 << "Error allocating user"; + oss.str(action_error(method_name, "CREATE", "USER", -2, 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); - + + NebulaLog::log("ReM",Log::ERROR,oss); + xmlrpc_c::value_array arrayresult_error(arrayData); *retval = arrayresult_error; - + return; } diff --git a/src/rm/RequestManagerUserDelete.cc b/src/rm/RequestManagerUserDelete.cc index 508580c1a3..6b798bee7f 100644 --- a/src/rm/RequestManagerUserDelete.cc +++ b/src/rm/RequestManagerUserDelete.cc @@ -17,21 +17,25 @@ #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; +{ + string session; - int uid; - User * user; + int uid; + User * user; - int rc; + int rc; ostringstream oss; + const string method_name = "UserDelete"; + /* -- RPC specific vars -- */ vector arrayData; xmlrpc_c::value_array * arrayresult; @@ -47,33 +51,49 @@ void RequestManager::UserDelete::execute( { goto error_oneadmin_deletion; } - - // Only oneadmin can delete users + rc = UserDelete::upool->authenticate(session); - - if ( rc != 0 ) + + if ( rc == -1 ) { goto error_authenticate; } - // Now let's get the user + //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) + + 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 + + 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 @@ -85,31 +105,36 @@ void RequestManager::UserDelete::execute( return; error_oneadmin_deletion: - oss << "User oneadmin cannot be deleted"; + oss << action_error(method_name, "DELETE", "USER", uid, -1) + << ". Reason: Oneadmin cannot be deleted."; goto error_common; error_authenticate: - oss << "User not authorized to delete users"; + 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 << "Error retrieving user " << uid; + oss.str(get_error(method_name, "USER", uid)); goto error_common; error_delete: - oss << "Error deleting user " << uid; + 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); - + + 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 1c7ea7fc19..0000000000 --- a/src/rm/RequestManagerUserInfo.cc +++ /dev/null @@ -1,100 +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 "RequestManager.h" -#include "NebulaLog.h" - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - -void RequestManager::UserInfo::execute( - xmlrpc_c::paramList const& paramList, - xmlrpc_c::value * const retval) -{ - string session; - int uid; - - User * user; - - int rc; - ostringstream oss; - - /* -- 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)); - uid = xmlrpc_c::value_int(paramList.getInt(1)); - - // Only oneadmin can retrieve user information - rc = UserInfo::upool->authenticate(session); - - if ( rc != 0 ) - { - goto error_authenticate; - } - - // Now let's get the user - user = UserInfo::upool->get(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 << "User not authorized to retrieve user information"; - goto error_common; - -error_get_user: - oss << "Error getting user"; - 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 index 96bd11f977..70c9434b90 100644 --- a/src/rm/RequestManagerUserPoolInfo.cc +++ b/src/rm/RequestManagerUserPoolInfo.cc @@ -17,6 +17,8 @@ #include "RequestManager.h" #include "NebulaLog.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -26,8 +28,11 @@ void RequestManager::UserPoolInfo::execute( { string session; - int rc; + int rc; + int uid; ostringstream oss; + + const string method_name = "UserPoolInfo"; /* -- RPC specific vars -- */ vector arrayData; @@ -39,15 +44,31 @@ void RequestManager::UserPoolInfo::execute( session = xmlrpc_c::value_string(paramList.getString(0)); // Only oneadmin can list the whole user pool - rc = UserPoolInfo::upool->authenticate(session); + uid = UserPoolInfo::upool->authenticate(session); - if ( rc != 0 ) + if ( uid == -1 ) { goto error_authenticate; } - // Now let's get the info - + //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 ) @@ -67,15 +88,18 @@ void RequestManager::UserPoolInfo::execute( return; error_authenticate: - oss << "User not authorized to pull user pool info. Error code: " << rc; + 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 << "Error dumping pool info"; + 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())); diff --git a/src/rm/RequestManagerVirtualNetworkAllocate.cc b/src/rm/RequestManagerVirtualNetworkAllocate.cc index 791d0f4b57..0856d29d81 100644 --- a/src/rm/RequestManagerVirtualNetworkAllocate.cc +++ b/src/rm/RequestManagerVirtualNetworkAllocate.cc @@ -17,6 +17,8 @@ #include "RequestManager.h" #include "NebulaLog.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -25,19 +27,20 @@ void RequestManager::VirtualNetworkAllocate::execute( xmlrpc_c::value * const retval) { string session; - string username; - string password; string name; - string stemplate; + string str_template; + + VirtualNetworkTemplate * vn_template; int nid; int uid; int rc; - - User * user; + char * error_msg = 0; ostringstream oss; + const string method_name = "VirtualNetworkAllocate"; + /* -- RPC specific vars -- */ vector arrayData; xmlrpc_c::value_array * arrayresult; @@ -45,27 +48,57 @@ void RequestManager::VirtualNetworkAllocate::execute( NebulaLog::log("ReM",Log::DEBUG,"VirtualNetworkAllocate method invoked"); // Get the parameters & host - session = xmlrpc_c::value_string(paramList.getString(0)); - stemplate = xmlrpc_c::value_string(paramList.getString(1)); + session = xmlrpc_c::value_string(paramList.getString(0)); + str_template = xmlrpc_c::value_string(paramList.getString(1)); - if ( User::split_secret(session,username,password) != 0 ) + //-------------------------------------------------------------------------- + // Authorize this request + //-------------------------------------------------------------------------- + uid = VirtualNetworkAllocate::upool->authenticate(session); + + if ( uid == -1 ) { - goto error_session; + goto error_authenticate; } - // Now let's get the user - user = VirtualNetworkAllocate::upool->get(username,true); + //-------------------------------------------------------------------------- + // Authorize this request + //-------------------------------------------------------------------------- + vn_template = new VirtualNetworkTemplate; - if ( user == 0 ) + rc = vn_template->parse(str_template,&error_msg); + + if ( rc != 0 ) { - goto error_get_user; + goto error_parse; } - uid = user->get_uid(); + if ( uid != 0 ) + { + AuthRequest ar(uid); + string t64; + string pub; + string pub_name = "PUBLIC"; - user->unlock(); + vn_template->get(pub_name, pub); + transform (pub.begin(), pub.end(), pub.begin(),(int(*)(int))toupper); - rc = vnpool->allocate(uid,stemplate,&nid); + ar.add_auth(AuthRequest::NET, + vn_template->to_xml(t64), + AuthRequest::CREATE, + uid, + (pub == "YES")); + + if (UserPool::authorize(ar) == -1) + { + goto error_authorize; + } + } + + //-------------------------------------------------------------------------- + // Allocate the Virtual Network + //-------------------------------------------------------------------------- + rc = vnpool->allocate(uid,vn_template,&nid); if ( rc < 0 ) { @@ -84,16 +117,28 @@ void RequestManager::VirtualNetworkAllocate::execute( return; -error_session: - oss << "Session information malformed, cannot allocate VirtualNetwork"; +error_authenticate: + oss.str(authenticate_error(method_name)); goto error_common; -error_get_user: - oss << "User not recognized, cannot allocate VirtualNetwork"; +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 << "Error allocating VN with template: " << endl << stemplate; + oss.str(action_error(method_name, "CREATE", "NET", -2, rc)); goto error_common; error_common: diff --git a/src/rm/RequestManagerVirtualNetworkDelete.cc b/src/rm/RequestManagerVirtualNetworkDelete.cc index b16e9803aa..d365f36ca3 100644 --- a/src/rm/RequestManagerVirtualNetworkDelete.cc +++ b/src/rm/RequestManagerVirtualNetworkDelete.cc @@ -17,6 +17,8 @@ #include "RequestManager.h" #include "NebulaLog.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -34,6 +36,8 @@ void RequestManager::VirtualNetworkDelete::execute( int rc; ostringstream oss; + + const string method_name = "VirtualNetworkDelete"; /* -- RPC specific vars -- */ vector arrayData; @@ -45,6 +49,27 @@ void RequestManager::VirtualNetworkDelete::execute( session = xmlrpc_c::value_string(paramList.getString(0)); nid = xmlrpc_c::value_int (paramList.getInt (1)); + // Only oneadmin or the VN owner can perform operations upon the VN + rc = VirtualNetworkDelete::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::NET,nid,AuthRequest::DELETE,0,false); + + if (UserPool::authorize(ar) == -1) + { + goto error_authorize; + } + } + // Retrieve VN from the pool vn = vnpool->get(nid,true); @@ -54,14 +79,6 @@ void RequestManager::VirtualNetworkDelete::execute( } uid = vn->get_uid(); - - // Only oneadmin or the VN owner can perform operations upon the VN - rc = VirtualNetworkDelete::upool->authenticate(session); - - if ( rc != 0 && rc != uid) - { - goto error_authenticate; - } rc = vnpool->drop(vn); @@ -79,16 +96,19 @@ void RequestManager::VirtualNetworkDelete::execute( return; error_authenticate: - vn->unlock(); - oss << "User cannot delete VN"; + 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 << "Error getting Virtual Network with NID = " << nid; + oss.str(get_error(method_name, "NET", nid)); goto error_common; error_common: - NebulaLog::log ("Rem",Log::ERROR,oss); + NebulaLog::log ("ReM",Log::ERROR,oss); arrayData.push_back(xmlrpc_c::value_boolean(false)); // FAILURE arrayData.push_back(xmlrpc_c::value_string(oss.str())); diff --git a/src/rm/RequestManagerVirtualNetworkInfo.cc b/src/rm/RequestManagerVirtualNetworkInfo.cc index 046f74b20d..664cf4fdc4 100644 --- a/src/rm/RequestManagerVirtualNetworkInfo.cc +++ b/src/rm/RequestManagerVirtualNetworkInfo.cc @@ -17,6 +17,8 @@ #include "RequestManager.h" #include "NebulaLog.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -33,6 +35,8 @@ void RequestManager::VirtualNetworkInfo::execute( VirtualNetwork * vn; ostringstream oss; + + const string method_name = "VirtualNetworkInfo"; /* -- RPC specific vars -- */ vector arrayData; @@ -51,7 +55,7 @@ void RequestManager::VirtualNetworkInfo::execute( { goto error_authenticate; } - + vn = vnpool->get(nid,true); if ( vn == 0 ) @@ -76,15 +80,14 @@ void RequestManager::VirtualNetworkInfo::execute( return; error_authenticate: - oss << "User not authenticated, VirtualNetworkInfo call aborted."; + oss.str(authenticate_error(method_name)); goto error_common; error_vn_get: - oss << "Error getting Virtual Network with NID = " << nid; + 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())); diff --git a/src/rm/RequestManagerVirtualNetworkPoolInfo.cc b/src/rm/RequestManagerVirtualNetworkPoolInfo.cc index ac1294d203..ba36bffaa5 100755 --- a/src/rm/RequestManagerVirtualNetworkPoolInfo.cc +++ b/src/rm/RequestManagerVirtualNetworkPoolInfo.cc @@ -31,11 +31,13 @@ void RequestManager::VirtualNetworkPoolInfo::execute( ostringstream oss; ostringstream where_string; - int rc; + int rc; int filter_flag; User * user; - + + const string method_name = "VirtualNetworkPoolInfo"; + /* -- RPC specific vars -- */ vector arrayData; xmlrpc_c::value_array * arrayresult; @@ -61,6 +63,8 @@ void RequestManager::VirtualNetworkPoolInfo::execute( * -1 :: User's VMs * >=0 :: UID User's VMs **/ + + // TODO define authorization (bug #278) if (filter_flag == -1) { User::split_secret(session,username,password); @@ -105,15 +109,15 @@ void RequestManager::VirtualNetworkPoolInfo::execute( return; error_authenticate: - oss << "User not authenticated, NetworkPoolInfo call aborted."; + oss.str(authenticate_error(method_name)); goto error_common; error_get_user: - oss << "Error getting user, aborting NetworkPoolInfo call"; + oss.str(get_error(method_name, "USER", -1)); goto error_common; error_dump: - oss << "Error getting virtual network pool"; + oss.str(get_error(method_name, "HOST", -1)); goto error_common; error_common: diff --git a/src/rm/RequestManagerVirtualNetworkPublish.cc b/src/rm/RequestManagerVirtualNetworkPublish.cc index 985ae289b0..c8d0befb6e 100644 --- a/src/rm/RequestManagerVirtualNetworkPublish.cc +++ b/src/rm/RequestManagerVirtualNetworkPublish.cc @@ -15,10 +15,12 @@ /* -------------------------------------------------------------------------- */ #include "RequestManager.h" -#include "NebulaLog.h" +#include "NebulaLog.h" #include "Nebula.h" +#include "AuthManager.h" + /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -31,12 +33,13 @@ void RequestManager::VirtualNetworkPublish::execute( int nid; bool publish_flag; int uid; - int rc; VirtualNetwork * vn; ostringstream oss; + const string method_name = "VirtualNetworkPublish"; + vector arrayData; xmlrpc_c::value_array * arrayresult; @@ -48,15 +51,13 @@ void RequestManager::VirtualNetworkPublish::execute( publish_flag = xmlrpc_c::value_boolean(paramList.getBoolean(2)); // First, we need to authenticate the user - rc = VirtualNetworkPublish::upool->authenticate(session); + uid = VirtualNetworkPublish::upool->authenticate(session); - if ( rc == -1 ) + if ( uid == -1 ) { goto error_authenticate; } - uid = rc; - // Get virtual network from the VirtualNetworkPool vn = VirtualNetworkPublish::vnpool->get(nid,true); @@ -65,9 +66,21 @@ void RequestManager::VirtualNetworkPublish::execute( goto error_vn_get; } - if ( uid != 0 && uid != vn->get_uid() ) + //Authorize the operation + if ( uid != 0 ) // uid == 0 means oneadmin { - goto error_authorization; + AuthRequest ar(uid); + + ar.add_auth(AuthRequest::NET, + nid, + AuthRequest::MANAGE, + 0, + vn->isPublic()); + + if (UserPool::authorize(ar) == -1) + { + goto error_authorize; + } } vn->publish(publish_flag); @@ -88,16 +101,15 @@ void RequestManager::VirtualNetworkPublish::execute( return; error_authenticate: - oss << "[VirtualNetworkPublish] User not authenticated, aborting call."; + oss.str(authenticate_error(method_name)); goto error_common; error_vn_get: - oss << "[VirtualNetworkPublish] Error getting VN with ID = " << nid; + oss.str(get_error(method_name, "NET", nid)); goto error_common; -error_authorization: - oss << "[VirtualNetworkPublish] User not authorized to (un)publish VN" << - ", aborting call."; +error_authorize: + oss.str(authorization_error(method_name, "MANAGE", "NET", uid, nid)); vn->unlock(); goto error_common; diff --git a/src/rm/SConstruct b/src/rm/SConstruct index 5cc33d17ac..2f651c74bd 100644 --- a/src/rm/SConstruct +++ b/src/rm/SConstruct @@ -54,7 +54,6 @@ source_files=[ 'RequestManagerVirtualNetworkPublish.cc', 'RequestManagerVirtualNetworkDelete.cc', 'RequestManagerUserAllocate.cc', - 'RequestManagerUserInfo.cc', 'RequestManagerUserDelete.cc', 'RequestManagerUserPoolInfo.cc' ] diff --git a/src/um/User.cc b/src/um/User.cc index abcf2f4ade..85d5693127 100644 --- a/src/um/User.cc +++ b/src/um/User.cc @@ -307,21 +307,6 @@ string& User::to_str(string& str) const /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ -int User::authenticate(string _password) -{ - if (enabled && _password==password) - { - return oid; - } - else - { - return -1; - } -} - -/* -------------------------------------------------------------------------- */ -/* -------------------------------------------------------------------------- */ - int User::split_secret(const string secret, string& user, string& pass) { size_t pos; diff --git a/src/um/UserPool.cc b/src/um/UserPool.cc index f7293ada1b..3e5d030950 100644 --- a/src/um/UserPool.cc +++ b/src/um/UserPool.cc @@ -20,6 +20,8 @@ #include "UserPool.h" #include "NebulaLog.h" +#include "Nebula.h" +#include "AuthManager.h" #include #include @@ -165,21 +167,98 @@ int UserPool::authenticate(string& session) { map::iterator index; + User * user = 0; string username; - string password; + string secret, u_pass; + int uid; - int user_id = -1; + int user_id = -1; + int rc; - // session holds username:password + Nebula& nd = Nebula::instance(); + AuthManager * authm = nd.get_authm(); - if ( User::split_secret(session,username,password) == 0 ) + rc = User::split_secret(session,username,secret); + + if ( rc != 0 ) { - index = known_users.find(username); + return -1; + } - if ( index != known_users.end() ) + index = known_users.find(username); + + if ( index != known_users.end() ) //User known to OpenNebula + { + user = get((int)index->second,true); + + if ( user == 0 ) { - User * user = get((int)index->second,false); - user_id = user->authenticate(password); + return -1; + } + + u_pass = user->password; + uid = user->get_uid(); + + user->unlock(); + } + else //External User + { + u_pass = "-"; + uid = -1; + } + + AuthRequest ar(uid); + + ar.add_authenticate(username,u_pass,secret); + + if ( uid == 0 ) //oneadmin + { + if (ar.plain_authenticate()) + { + user_id = 0; + } + } + else if (authm == 0) //plain auth + { + if ( user != 0 && ar.plain_authenticate()) //no plain for external users + { + user_id = uid; + } + } + else //use the driver + { + authm->trigger(AuthManager::AUTHENTICATE,&ar); + ar.wait(); + + if (ar.result==true) + { + if ( user != 0 ) //knwon user_id + { + user_id = uid; + } + else //External user, user_id in driver message + { + istringstream is(ar.message); + + if ( is.good() ) + { + is >> user_id; + } + + if ( is.fail() || user_id <= 0 ) + { + ar.message = "Can't convert user_id from driver"; + user_id = -1; + } + } + } + + if (user_id == -1) + { + ostringstream oss; + oss << "Auth Error: " << ar.message; + + NebulaLog::log("AuM",Log::ERROR,oss); } } @@ -189,6 +268,43 @@ int UserPool::authenticate(string& session) /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ +int UserPool::authorize(AuthRequest& ar) +{ + Nebula& nd = Nebula::instance(); + AuthManager * authm = nd.get_authm(); + int rc = -1; + + if (authm == 0) + { + if (ar.plain_authorize()) + { + rc = 0; + } + } + else + { + authm->trigger(AuthManager::AUTHORIZE,&ar); + ar.wait(); + + if (ar.result==true) + { + rc = 0; + } + else + { + ostringstream oss; + oss << "Auth Error: " << ar.message; + + NebulaLog::log("AuM",Log::ERROR,oss); + } + } + + return rc; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + int UserPool::dump_cb(void * _oss, int num, char **values, char **names) { ostringstream * oss; diff --git a/src/um/test/SConstruct b/src/um/test/SConstruct index 2b6eb98931..fcce418e74 100644 --- a/src/um/test/SConstruct +++ b/src/um/test/SConstruct @@ -41,10 +41,12 @@ main_env.Append(CPPPATH=[ # Library dirs main_env.Append(LIBPATH=[ cwd + '/src/common', + cwd + '/src/mad', cwd + '/src/log', cwd + '/src/nebula', cwd + '/src/pool', cwd + '/src/sql', + cwd + '/src/authm', cwd + '/src/um', '/usr/include/openssl/', ]) @@ -53,7 +55,9 @@ main_env.Append(LIBS=[ 'nebula_um', 'nebula_pool', 'nebula_log', + 'nebula_authm', 'nebula_common', + 'nebula_mad', 'nebula_core', 'nebula_sql', 'cppunit', diff --git a/src/vm/VirtualMachine.cc b/src/vm/VirtualMachine.cc index a81b68a661..42549a8e09 100644 --- a/src/vm/VirtualMachine.cc +++ b/src/vm/VirtualMachine.cc @@ -36,12 +36,11 @@ /* Virtual Machine :: Constructor/Destructor */ /* ************************************************************************** */ -VirtualMachine::VirtualMachine(int id): +VirtualMachine::VirtualMachine(int id, VirtualMachineTemplate * _vm_template): PoolObjectSQL(id), uid(-1), last_poll(0), name(""), - vm_template(), state(INIT), lcm_state(LCM_INIT), stime(time(0)), @@ -56,6 +55,14 @@ VirtualMachine::VirtualMachine(int id): previous_history(0), _log(0) { + if (_vm_template != 0) + { + vm_template = _vm_template; + } + else + { + vm_template = new VirtualMachineTemplate; + } } VirtualMachine::~VirtualMachine() @@ -74,6 +81,11 @@ VirtualMachine::~VirtualMachine() { delete _log; } + + if ( vm_template != 0 ) + { + delete vm_template; + } } /* ************************************************************************** */ @@ -140,7 +152,7 @@ int VirtualMachine::select_cb(void *nil, int num, char **values, char **names) last_seq = atoi(values[LAST_SEQ]); // Virtual Machine template ID is the VM ID - vm_template.id = oid; + vm_template->id = oid; return 0; } @@ -176,7 +188,7 @@ int VirtualMachine::select(SqlDB * db) } //Get the template - rc = vm_template.select(db); + rc = vm_template->select(db); if (rc != 0) { @@ -270,9 +282,9 @@ int VirtualMachine::insert(SqlDB * db) // ----------------------------------------------------------------------- // Set a template ID if it wasn't already assigned // ------------------------------------------------------------------------ - if ( vm_template.id == -1 ) + if ( vm_template->id == -1 ) { - vm_template.id = oid; + vm_template->id = oid; } // ----------------------------------------------------------------------- @@ -283,7 +295,7 @@ int VirtualMachine::insert(SqlDB * db) attr = new SingleAttribute("VMID",value); - vm_template.set(attr); + vm_template->set(attr); get_template_attribute("NAME",name); @@ -294,7 +306,7 @@ int VirtualMachine::insert(SqlDB * db) name = oss.str(); attr = new SingleAttribute("NAME",name); - vm_template.set(attr); + vm_template->set(attr); } this->name = name; @@ -345,7 +357,7 @@ int VirtualMachine::insert(SqlDB * db) // Insert the template first, so we get a valid template ID. Then the VM // ------------------------------------------------------------------------ - rc = vm_template.insert(db); + rc = vm_template->insert(db); if ( rc != 0 ) { @@ -363,7 +375,7 @@ int VirtualMachine::insert(SqlDB * db) error_update: NebulaLog::log("ONE",Log::ERROR, "Can not update VM in the database"); - vm_template.drop(db); + vm_template->drop(db); goto error_common; error_template: @@ -385,6 +397,7 @@ error_context: error_requirements: NebulaLog::log("ONE",Log::ERROR, "Could not parse REQUIREMENTS for VM"); + goto error_common; error_common: release_network_leases(); @@ -405,7 +418,7 @@ int VirtualMachine::parse_context() string * str; string parsed; - num = vm_template.remove("CONTEXT", array_context); + num = vm_template->remove("CONTEXT", array_context); if ( num == 0 ) { @@ -437,7 +450,7 @@ int VirtualMachine::parse_context() context_parsed = new VectorAttribute("CONTEXT"); context_parsed->unmarshall(parsed," @^_^@ "); - vm_template.set(context_parsed); + vm_template->set(context_parsed); } /* --- Delete old context attributes --- */ @@ -463,7 +476,7 @@ void VirtualMachine::parse_graphics() vector array_graphics; VectorAttribute * graphics; - num = vm_template.get("GRAPHICS", array_graphics); + num = vm_template->get("GRAPHICS", array_graphics); if ( num == 0 ) { @@ -510,7 +523,7 @@ int VirtualMachine::parse_requirements() string parsed; - num = vm_template.remove("REQUIREMENTS", array_reqs); + num = vm_template->remove("REQUIREMENTS", array_reqs); if ( num == 0 ) { @@ -532,7 +545,7 @@ int VirtualMachine::parse_requirements() SingleAttribute * reqs_parsed; reqs_parsed = new SingleAttribute("REQUIREMENTS",parsed); - vm_template.set(reqs_parsed); + vm_template->set(reqs_parsed); } /* --- Delete old requirements attributes --- */ @@ -802,7 +815,7 @@ int VirtualMachine::get_disk_images() Nebula& nd = Nebula::instance(); ipool = nd.get_ipool(); - num_disks = vm_template.get("DISK",disks); + num_disks = vm_template->get("DISK",disks); for(int i=0, index=0; ivector_value("IID"); + iid = disk->vector_value("IMAGE_ID"); if ( iid.empty() ) { @@ -885,7 +898,7 @@ int VirtualMachine::get_network_leases() Nebula& nd = Nebula::instance(); vnpool = nd.get_vnpool(); - num_nics = vm_template.get("NIC",nics); + num_nics = vm_template->get("NIC",nics); for(int i=0; ivector_value("VNID"); + vnid = nic->vector_value("NETWORK_ID"); if ( vnid.empty() ) { @@ -1125,7 +1138,7 @@ string& VirtualMachine::to_xml(string& xml) const << "" << net_tx << "" << "" << net_rx << "" << "" << last_seq << "" - << vm_template.to_xml(template_xml); + << vm_template->to_xml(template_xml); if ( hasHistory() ) { @@ -1162,7 +1175,7 @@ string& VirtualMachine::to_str(string& str) const << "NET TX : " << net_tx << endl << "NET RX : " << net_rx << endl << "LAST SEQ : " << last_seq << endl - << "Template" << endl << vm_template.to_str(template_str) << endl; + << "Template" << endl << vm_template->to_str(template_str) << endl; if ( hasHistory() ) { diff --git a/src/vm/VirtualMachinePool.cc b/src/vm/VirtualMachinePool.cc index 73a8365d64..bc1a744c24 100644 --- a/src/vm/VirtualMachinePool.cc +++ b/src/vm/VirtualMachinePool.cc @@ -151,19 +151,16 @@ VirtualMachinePool::VirtualMachinePool(SqlDB * db, int VirtualMachinePool::allocate ( int uid, - const string& stemplate, + VirtualMachineTemplate * vm_template, int * oid, bool on_hold) { VirtualMachine * vm; - char * error_msg; - int rc; - // ------------------------------------------------------------------------ // Build a new Virtual Machine object // ------------------------------------------------------------------------ - vm = new VirtualMachine; + vm = new VirtualMachine(-1,vm_template); if (on_hold == true) { @@ -176,24 +173,6 @@ int VirtualMachinePool::allocate ( vm->uid = uid; - // ------------------------------------------------------------------------ - // Parse template - // ------------------------------------------------------------------------ - rc = vm->vm_template.parse(stemplate,&error_msg); - - if ( rc != 0 ) - { - ostringstream oss; - - oss << error_msg; - NebulaLog::log("ONE", Log::ERROR, oss); - free(error_msg); - - delete vm; - - return -1; - } - // ------------------------------------------------------------------------ // Insert the Object in the pool // ------------------------------------------------------------------------ diff --git a/src/vm/test/SConstruct b/src/vm/test/SConstruct index 9124675c1b..362a0dd4ea 100644 --- a/src/vm/test/SConstruct +++ b/src/vm/test/SConstruct @@ -48,6 +48,7 @@ main_env.Append(LIBPATH=[ cwd + '/src/template', cwd + '/src/vm', cwd + '/src/hm', + cwd + '/src/authm', cwd + '/src/mad', cwd + '/src/vnm', cwd + '/src/um', @@ -58,12 +59,13 @@ main_env.Append(LIBPATH=[ main_env.Append(LIBS=[ 'nebula_um', 'nebula_vm', - 'nebula_mad', 'nebula_hm', 'nebula_vnm', + 'nebula_authm', 'nebula_template', 'nebula_pool', 'nebula_image', + 'nebula_mad', 'nebula_common', 'nebula_log', 'nebula_core', diff --git a/src/vm/test/VirtualMachinePoolTest.cc b/src/vm/test/VirtualMachinePoolTest.cc index e9a61d9e4d..04ce70247e 100644 --- a/src/vm/test/VirtualMachinePoolTest.cc +++ b/src/vm/test/VirtualMachinePoolTest.cc @@ -80,6 +80,40 @@ const string xml_history_dump = const string replacement = "0000000000"; +/* ************************************************************************* */ +/* ************************************************************************* */ + +class VirtualMachinePoolFriend : public VirtualMachinePool +{ +public: + VirtualMachinePoolFriend(SqlDB * db, vector hook_mads): + VirtualMachinePool(db, hook_mads) + {}; + + + int allocate ( + int uid, + const string& stemplate, + int * oid, + bool on_hold = false) + { + VirtualMachineTemplate * vm_template; + char * error_msg = 0; + int rc; + + vm_template = new VirtualMachineTemplate; + rc = vm_template->parse(stemplate,&error_msg); + + if( rc == 0 ) + { + return VirtualMachinePool::allocate(uid, vm_template, oid, on_hold); + } + else + { + return -1; + } + }; +}; /* ************************************************************************* */ /* ************************************************************************* */ @@ -114,15 +148,15 @@ protected: { // The VM pool needs a vector containing the vm hooks vector vm_hooks; - return new VirtualMachinePool(db, vm_hooks); + return new VirtualMachinePoolFriend(db, vm_hooks); }; int allocate(int index) { int oid; - return ((VirtualMachinePool*)pool)->allocate(uids[index], - templates[index], - &oid, false); + return ((VirtualMachinePoolFriend*)pool)->allocate( uids[index], + templates[index], + &oid, false); }; void check(int index, PoolObjectSQL* obj) @@ -231,7 +265,8 @@ public: void dump() { - VirtualMachinePool * vmp = static_cast(pool); + VirtualMachinePoolFriend * vmp = + static_cast(pool); set_up_user_pool(); @@ -253,7 +288,8 @@ public: void dump_where() { - VirtualMachinePool * vmp = static_cast(pool); + VirtualMachinePoolFriend * vmp = + static_cast(pool); set_up_user_pool(); @@ -275,7 +311,8 @@ public: void dump_history() { - VirtualMachinePool * vmp = static_cast(pool); + VirtualMachinePoolFriend * vmp = + static_cast(pool); VirtualMachine* vm; string hostnames[] = {"A_hostname", "B_hostname", "C_hostname"}; @@ -374,8 +411,9 @@ public: void history() { - VirtualMachine * vm; - VirtualMachinePool * vmp = static_cast(pool); + VirtualMachine * vm; + VirtualMachinePoolFriend * vmp = + static_cast(pool); int rc, oid; @@ -395,7 +433,7 @@ public: // Add a history item vm->add_history(0, hostname, vm_dir, vmm_mad, tm_mad); - rc = vmp->update(vm); + rc = vmp->update(vm); CPPUNIT_ASSERT( rc == 0 ); rc = vmp->update_history(vm); @@ -403,7 +441,7 @@ public: vm->add_history(0, new_hostname, vm_dir, vmm_mad, tm_mad); - rc = vmp->update(vm); + rc = vmp->update(vm); CPPUNIT_ASSERT( rc == 0 ); vm->set_reason(History::USER); diff --git a/src/vnm/VirtualNetwork.cc b/src/vnm/VirtualNetwork.cc index ee5e8d0740..c7a04e1670 100644 --- a/src/vnm/VirtualNetwork.cc +++ b/src/vnm/VirtualNetwork.cc @@ -22,17 +22,30 @@ #include "RangedLeases.h" #include "FixedLeases.h" +#include "AuthManager.h" +#include "UserPool.h" + /* ************************************************************************** */ /* Virtual Network :: Constructor/Destructor */ /* ************************************************************************** */ -VirtualNetwork::VirtualNetwork(): +VirtualNetwork::VirtualNetwork(VirtualNetworkTemplate *_vn_template): PoolObjectSQL(-1), name(""), uid(-1), bridge(""), type(UNINITIALIZED), - leases(0){}; + leases(0) +{ + if (_vn_template != 0) + { + vn_template = _vn_template; + } + else + { + vn_template = new VirtualNetworkTemplate; + } +}; /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ @@ -43,6 +56,11 @@ VirtualNetwork::~VirtualNetwork() { delete leases; } + + if (vn_template != 0) + { + delete vn_template; + } } /* ************************************************************************** */ @@ -86,7 +104,7 @@ int VirtualNetwork::select_cb(void * nil, int num, char **values, char **names) public_vnet = atoi(values[PUBLIC]); // Virtual Network template ID is the Network ID - vn_template.id = oid; + vn_template->id = oid; return 0; } @@ -125,7 +143,7 @@ int VirtualNetwork::select(SqlDB * db) } //Get the template - rc = vn_template.select(db); + rc = vn_template->select(db); if (rc != 0) { @@ -312,16 +330,16 @@ int VirtualNetwork::insert(SqlDB * db) public_vnet = (pub == "YES"); - vn_template.erase("PUBLIC"); + vn_template->erase("PUBLIC"); - // ------------ TEMPLATE -------------------- + // ------------ INSERT THE TEMPLATE -------------------- - if ( vn_template.id == -1 ) + if ( vn_template->id == -1 ) { - vn_template.id = oid; + vn_template->id = oid; } - rc = vn_template.insert(db); + rc = vn_template->insert(db); if ( rc != 0 ) { @@ -422,7 +440,7 @@ error_template: error_update: ose << "Can not update Virtual Network id " << oid; - vn_template.drop(db); + vn_template->drop(db); goto error_common; error_addr: @@ -503,7 +521,7 @@ int VirtualNetwork::vn_drop(SqlDB * db) ostringstream oss; int rc; - vn_template.drop(db); + vn_template->drop(db); if ( leases != 0 ) { @@ -555,7 +573,7 @@ string& VirtualNetwork::to_xml(string& xml) const "" << type << "" << "" << bridge << "" << "" << public_vnet << "" << - vn_template.to_xml(template_xml); + vn_template->to_xml(template_xml); if (leases) { os << leases->to_xml(leases_xml); @@ -593,7 +611,8 @@ string& VirtualNetwork::to_str(string& str) const os << "Bridge : " << bridge << endl; os << "Public : " << public_vnet << endl << endl; - os << "....: Template :...." << vn_template.to_str(template_str) << endl << endl; + os << "....: Template :...." << vn_template->to_str(template_str) << endl << +endl; if (leases) { @@ -612,7 +631,6 @@ int VirtualNetwork::nic_attribute(VectorAttribute *nic, int vid) { int rc; - string network; string model; string ip; string mac; @@ -621,7 +639,6 @@ int VirtualNetwork::nic_attribute(VectorAttribute *nic, int vid) map new_nic; - network = nic->vector_value("NETWORK"); model = nic->vector_value("MODEL"); ip = nic->vector_value("IP"); vnid << oid; @@ -648,11 +665,11 @@ int VirtualNetwork::nic_attribute(VectorAttribute *nic, int vid) // NEW NIC ATTRIBUTES //-------------------------------------------------------------------------- - new_nic.insert(make_pair("NETWORK",network)); - new_nic.insert(make_pair("MAC" ,mac)); - new_nic.insert(make_pair("BRIDGE" ,bridge)); - new_nic.insert(make_pair("VNID" ,vnid.str())); - new_nic.insert(make_pair("IP" ,ip)); + new_nic.insert(make_pair("NETWORK" ,name)); + new_nic.insert(make_pair("MAC" ,mac)); + new_nic.insert(make_pair("BRIDGE" ,bridge)); + new_nic.insert(make_pair("NETWORK_ID",vnid.str())); + new_nic.insert(make_pair("IP" ,ip)); if (!model.empty()) { diff --git a/src/vnm/VirtualNetworkPool.cc b/src/vnm/VirtualNetworkPool.cc index 80e5620a4d..2e6d755e11 100644 --- a/src/vnm/VirtualNetworkPool.cc +++ b/src/vnm/VirtualNetworkPool.cc @@ -17,6 +17,7 @@ #include "VirtualNetworkPool.h" #include "NebulaLog.h" +#include "AuthManager.h" #include #include @@ -70,35 +71,15 @@ VirtualNetworkPool::VirtualNetworkPool(SqlDB * db, int VirtualNetworkPool::allocate ( int uid, - const string& stemplate, + VirtualNetworkTemplate * vn_template, int * oid) { VirtualNetwork * vn; - char * error_msg; - int rc; - // Build a new Virtual Network object - vn = new VirtualNetwork(); + vn = new VirtualNetwork(vn_template); vn->uid = uid; - rc = vn->vn_template.parse(stemplate,&error_msg); - - if ( rc != 0 ) - { - ostringstream oss; - - oss << error_msg; - NebulaLog::log("VNM", Log::ERROR, oss); - free(error_msg); - - delete vn; - - return -1; - } - - // Insert the VN in the pool so we have a valid OID - *oid = PoolSQL::allocate(vn); return *oid; @@ -214,3 +195,99 @@ int VirtualNetworkPool::dump(ostringstream& oss, const string& where) return rc; } + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +int VirtualNetworkPool::nic_attribute(VectorAttribute * nic, int vid) +{ + string network; + VirtualNetwork * vnet = 0; + + network = nic->vector_value("NETWORK"); + + if (network.empty()) + { + istringstream is; + int network_id; + + network = nic->vector_value("NETWORK_ID"); + + if(network.empty()) + { + return -2; + } + + is.str(network); + is >> network_id; + + if( !is.fail() ) + { + vnet = get(network_id,true); + } + } + else + { + vnet = get(network,true); + } + + if (vnet == 0) + { + return -1; + } + + int rc = vnet->nic_attribute(nic,vid); + + vnet->unlock(); + + return rc; +} + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + +void VirtualNetworkPool::authorize_nic(VectorAttribute * nic, AuthRequest * ar) +{ + string network; + VirtualNetwork * vnet = 0; + + network = nic->vector_value("NETWORK"); + + if (network.empty()) + { + istringstream is; + int network_id; + + network = nic->vector_value("NETWORK_ID"); + + if(network.empty()) + { + return; + } + + is.str(network); + is >> network_id; + + if( !is.fail() ) + { + vnet = get(network_id,true); + } + } + else + { + vnet = get(network,true); + } + + if (vnet == 0) + { + return; + } + + ar->add_auth(AuthRequest::NET, + vnet->get_vnid(), + AuthRequest::USE, + vnet->get_uid(), + vnet->isPublic()); + + vnet->unlock(); +} diff --git a/src/vnm/test/SConstruct b/src/vnm/test/SConstruct index 221228318e..811f856d6b 100644 --- a/src/vnm/test/SConstruct +++ b/src/vnm/test/SConstruct @@ -40,7 +40,9 @@ main_env.Append(CPPPATH=[ # Library dirs main_env.Append(LIBPATH=[ + cwd + '/src/authm', cwd + '/src/common', + cwd + '/src/mad', cwd + '/src/nebula', cwd + '/src/sql', cwd + '/src/log', @@ -54,9 +56,11 @@ main_env.Append(LIBS=[ 'nebula_log', 'nebula_um', 'nebula_vnm', + 'nebula_authm', 'nebula_template', 'nebula_pool', 'nebula_common', + 'nebula_mad', 'nebula_core', 'nebula_sql', 'cppunit', diff --git a/src/vnm/test/VirtualNetworkPoolTest.cc b/src/vnm/test/VirtualNetworkPoolTest.cc index 8809cbb60b..7c3239a17e 100644 --- a/src/vnm/test/VirtualNetworkPoolTest.cc +++ b/src/vnm/test/VirtualNetworkPoolTest.cc @@ -85,6 +85,41 @@ const string xml_dump_where = /* ************************************************************************* */ /* ************************************************************************* */ +class VirtualNetworkPoolFriend : public VirtualNetworkPool +{ +public: + + VirtualNetworkPoolFriend( SqlDB * db, + const string& str_mac_prefix, + int default_size): + + VirtualNetworkPool( db, str_mac_prefix, default_size) + {}; + + + int allocate(const int& uid, const std::string& stemplate, int* oid) + { + VirtualNetworkTemplate * vn_template; + char * error_msg = 0; + int rc; + + vn_template = new VirtualNetworkTemplate; + rc = vn_template->parse(stemplate,&error_msg); + + if( rc == 0 ) + { + return VirtualNetworkPool::allocate(uid, vn_template, oid); + } + else + { + return -1; + } + }; +}; + +/* ************************************************************************* */ +/* ************************************************************************* */ + class VirtualNetworkPoolTest : public PoolTest { CPPUNIT_TEST_SUITE (VirtualNetworkPoolTest); @@ -107,6 +142,7 @@ class VirtualNetworkPoolTest : public PoolTest CPPUNIT_TEST (overlapping_leases_rr); CPPUNIT_TEST (drop_leases); CPPUNIT_TEST (public_attribute); + CPPUNIT_TEST (vnpool_nic_attribute); CPPUNIT_TEST_SUITE_END (); @@ -127,7 +163,7 @@ protected: int allocate(int index) { int oid; - return ((VirtualNetworkPool*)pool)->allocate(uids[index], + return ((VirtualNetworkPoolFriend*)pool)->allocate(uids[index], templates[index], &oid); }; @@ -181,9 +217,10 @@ public: void allocate_rcs() { - VirtualNetworkPool * vnpool = static_cast(pool); + VirtualNetworkPoolFriend * vnpool = + static_cast(pool); VirtualNetwork * vn; - int rc; + int rc; // Check case rc = allocate(2); @@ -207,6 +244,9 @@ public: CPPUNIT_ASSERT( rc == -1 ); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void get_using_name() { VirtualNetworkPool * vnpool = static_cast(pool); @@ -235,6 +275,9 @@ public: check(1, vn); }; +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void wrong_get_name() { VirtualNetworkPool * vnpool = static_cast(pool); @@ -252,16 +295,23 @@ public: CPPUNIT_ASSERT( vn == 0 ); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void update() { // TODO }; +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void size() { - VirtualNetworkPool * vnpool = static_cast(pool); + VirtualNetworkPoolFriend * vnpool = + static_cast(pool); - int rc; + int rc; VirtualNetwork* vnet; string templ[] = { @@ -338,10 +388,14 @@ public: } } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void duplicates() { int rc, oid_0, oid_1; - VirtualNetworkPool * vnpool = static_cast(pool); + VirtualNetworkPoolFriend * vnpool = + static_cast(pool); VirtualNetwork * vnet; // Allocate a vnet @@ -382,9 +436,13 @@ public: check(0, vnet); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void dump() { - VirtualNetworkPool * vnpool = static_cast(pool); + VirtualNetworkPoolFriend * vnpool = + static_cast(pool); int oid, rc; ostringstream oss; @@ -401,9 +459,13 @@ public: CPPUNIT_ASSERT( result == xml_dump ); }; +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void dump_where() { - VirtualNetworkPool * vnpool = static_cast(pool); + VirtualNetworkPoolFriend * vnpool = + static_cast(pool); int oid, rc; ostringstream oss; @@ -421,8 +483,13 @@ public: CPPUNIT_ASSERT( result == xml_dump_where ); }; +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void fixed_leases() { + VirtualNetworkPoolFriend * vnpool = + static_cast(pool); int rc, oid; VirtualNetwork *vn; @@ -435,7 +502,7 @@ public: oid = allocate(0); CPPUNIT_ASSERT( oid != -1 ); - vn = ((VirtualNetworkPool*)pool)->get(oid, false); + vn = vnpool->get(oid, false); CPPUNIT_ASSERT( vn != 0 ); // Ask for an IP @@ -454,7 +521,7 @@ public: pool->clean(); // Read the Vnet from the DB - vn = ((VirtualNetworkPool*)pool)->get(oid, false); + vn = vnpool->get(oid, false); CPPUNIT_ASSERT( vn != 0 ); // Ask for another IP @@ -495,8 +562,13 @@ public: CPPUNIT_ASSERT( bridge == "br1" ); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void ranged_leases() { + VirtualNetworkPoolFriend * vnpool = + static_cast(pool); int rc, oid; VirtualNetwork *vn; @@ -512,10 +584,10 @@ public: "NETWORK_ADDRESS = 192.168.50.0\n"; - ((VirtualNetworkPool*)pool)->allocate(45, tmpl, &oid); + vnpool->allocate(45, tmpl, &oid); CPPUNIT_ASSERT( oid != -1 ); - vn = ((VirtualNetworkPool*)pool)->get(oid, false); + vn = vnpool->get(oid, false); CPPUNIT_ASSERT( vn != 0 ); // Ask for an IP @@ -533,7 +605,7 @@ public: pool->clean(); // Read the Vnet from the DB - vn = ((VirtualNetworkPool*)pool)->get(oid, false); + vn = vnpool->get(oid, false); CPPUNIT_ASSERT( vn != 0 ); // Ask for the IP already in use @@ -587,8 +659,13 @@ public: CPPUNIT_ASSERT( bridge == "bridge0" ); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void wrong_leases() { + VirtualNetworkPoolFriend * vnpool = + static_cast(pool); int rc, oid_0, oid_1; VirtualNetwork *vn; @@ -601,7 +678,7 @@ public: oid_0 = allocate(0); CPPUNIT_ASSERT( oid_0 != -1 ); - vn = ((VirtualNetworkPool*)pool)->get(oid_0, false); + vn = vnpool->get(oid_0, false); CPPUNIT_ASSERT( vn != 0 ); // Ask for a non-defined IP @@ -616,7 +693,7 @@ public: oid_1 = allocate(1); CPPUNIT_ASSERT( oid_1 != -1 ); - vn = ((VirtualNetworkPool*)pool)->get(oid_1, false); + vn = vnpool->get(oid_1, false); CPPUNIT_ASSERT( vn != 0 ); // Ask for an out of range IP @@ -635,6 +712,9 @@ public: CPPUNIT_ASSERT( rc == -1 ); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void overlapping_leases_ff() { // It is a different Vnet from #0: different user, name, and bridge. @@ -649,6 +729,9 @@ public: overlapping_leases(templates[0], tmpl_B); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void overlapping_leases_fr() { // Now use a ranged network, also containig the IP 130.10.0.1 @@ -662,6 +745,9 @@ public: overlapping_leases(templates[0], tmpl_B); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void overlapping_leases_rf() { // It is a different Vnet from #0: different user, name, and bridge. @@ -676,6 +762,9 @@ public: overlapping_leases(tmpl_A, templates[0]); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void overlapping_leases_rr() { // It is a different Vnet from #0: different user, name, and bridge. @@ -697,10 +786,14 @@ public: overlapping_leases(tmpl_A, tmpl_B); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ // Runs a test using the given templates void overlapping_leases(string tmpl_A, string tmpl_B) { + VirtualNetworkPoolFriend * vnpool = + static_cast(pool); int rc, oid_0, oid_new; VirtualNetwork *vn; @@ -712,15 +805,15 @@ public: // First VNet template - ((VirtualNetworkPool*)pool)->allocate(13, tmpl_A, &oid_0); + vnpool->allocate(13, tmpl_A, &oid_0); CPPUNIT_ASSERT( oid_0 != -1 ); // Second VNet - ((VirtualNetworkPool*)pool)->allocate(45, tmpl_B, &oid_new); + vnpool->allocate(45, tmpl_B, &oid_new); CPPUNIT_ASSERT( oid_new != -1 ); // Get this second VNet - vn = ((VirtualNetworkPool*)pool)->get(oid_new, false); + vn = vnpool->get(oid_new, false); CPPUNIT_ASSERT( vn != 0 ); // Set a lease. Ask for the IP that both Vnets have @@ -742,7 +835,7 @@ public: // Now check that the first VNet has that IP available - vn = ((VirtualNetworkPool*)pool)->get(oid_0, false); + vn = vnpool->get(oid_0, false); CPPUNIT_ASSERT( vn != 0 ); // Ask the first VNet for the IP that both Vnets have @@ -759,7 +852,7 @@ public: // Get again the second VNet - vn = ((VirtualNetworkPool*)pool)->get(oid_new, false); + vn = vnpool->get(oid_new, false); CPPUNIT_ASSERT( vn != 0 ); // Ask for the IP, should be still used @@ -778,8 +871,13 @@ public: CPPUNIT_ASSERT(results.size() == 1); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + void drop_leases() { + VirtualNetworkPoolFriend * vnpool = + static_cast(pool); int rc, oid; VirtualNetwork *vn; @@ -793,7 +891,7 @@ public: oid = allocate(0); CPPUNIT_ASSERT( oid != -1 ); - vn = ((VirtualNetworkPool*)pool)->get(oid, false); + vn = vnpool->get(oid, false); CPPUNIT_ASSERT( vn != 0 ); // Drop the VNet @@ -808,11 +906,14 @@ public: CPPUNIT_ASSERT(results.size() == 0); } +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ void public_attribute() { int oid; - VirtualNetworkPool * vnp = static_cast(pool); + VirtualNetworkPoolFriend * vnp = + static_cast(pool); VirtualNetwork * vn; string templates[] = @@ -897,12 +998,103 @@ public: CPPUNIT_ASSERT( vn != 0 ); //cout << endl << i << ":expected " << results[i] << " got " << vn->is_public(); - - CPPUNIT_ASSERT( vn->is_public() == results[i] ); - + CPPUNIT_ASSERT( vn->isPublic() == results[i] ); i++; } } + +/* -------------------------------------------------------------------------- */ +/* -------------------------------------------------------------------------- */ + + void vnpool_nic_attribute() + { + VirtualNetworkPoolFriend * vnp = + static_cast(pool); + + VectorAttribute * disk; + int oid_0, oid_1; + string value; + + // --------------------------------------------------------------------- + // Allocate 2 vnets + + string template_0 = "NAME = \"Net 0\"\n" + "TYPE = FIXED\n" + "BRIDGE = br1\n" + "LEASES = [IP=130.10.0.1, MAC=50:20:20:20:20:20]"; + + string template_1 = "NAME = \"Net 1\"\n" + "TYPE = FIXED\n" + "BRIDGE = br2\n" + "LEASES = [IP=130.10.0.5, MAC=50:20:20:20:20:25]"; + + + vnp->allocate(0, template_0, &oid_0); + CPPUNIT_ASSERT( oid_0 == 0 ); + + vnp->allocate(0, template_1, &oid_1); + CPPUNIT_ASSERT( oid_1 == 1 ); + + + // Disk using network 0 + disk = new VectorAttribute("DISK"); + disk->replace("NETWORK", "Net 0"); + + ((VirtualNetworkPool*)vnp)->nic_attribute(disk, 0); + + + value = ""; + value = disk->vector_value("NETWORK"); + CPPUNIT_ASSERT( value == "Net 0" ); + + value = ""; + value = disk->vector_value("MAC"); + CPPUNIT_ASSERT( value == "50:20:20:20:20:20" ); + + value = ""; + value = disk->vector_value("BRIDGE"); + CPPUNIT_ASSERT( value == "br1" ); + + value = ""; + value = disk->vector_value("NETWORK_ID"); + CPPUNIT_ASSERT( value == "0" ); + + value = ""; + value = disk->vector_value("IP"); + CPPUNIT_ASSERT( value == "130.10.0.1" ); + + delete disk; + + + // Disk using network 1 index + disk = new VectorAttribute("DISK"); + disk->replace("NETWORK_ID", "1"); + + ((VirtualNetworkPool*)vnp)->nic_attribute(disk, 0); + + value = ""; + value = disk->vector_value("NETWORK"); + CPPUNIT_ASSERT( value == "Net 1" ); + + value = ""; + value = disk->vector_value("MAC"); + CPPUNIT_ASSERT( value == "50:20:20:20:20:25" ); + + value = ""; + value = disk->vector_value("BRIDGE"); + CPPUNIT_ASSERT( value == "br2" ); + + value = ""; + value = disk->vector_value("NETWORK_ID"); + CPPUNIT_ASSERT( value == "1" ); + + value = ""; + value = disk->vector_value("IP"); + CPPUNIT_ASSERT( value == "130.10.0.5" ); + + delete disk; + } + }; /* ************************************************************************* */